Computer Programming

75 downloads 0 Views 3MB Size Report
Urdu, French, Gujarati etc. ..... First character must be an alphabet or underscore and subsequent .... Case matters (that is, upper- and lowercase letters). Thus ...
Computer Programming DCSA-1303

Bangladesh Open University School of Science and Technology

School of Science and Technology

Computer Programming DCSA-1303

Course Development Team Writer Amran Hossain Department of Computer Science and Engineering Dhaka University of Engineering & Technology, Gazipur Mohammad Mamunur Rashid School of Science and Technology Bangladesh Open University

Editor Professor Dr. K.M. Rezanur Rahman School of Science and Technology Bangladesh Open University

Overall Supervision Professor Dr. K.M. Rezanur Rahman School of Science and Technology Bangladesh Open University

BANGLADESH OPEN UNIVERSITY

First Edition: 1998 Second Edition: April 2017

Published by Publishing, Printing and Distribution Division Bangladesh Open University Gazipur-1705. Cover Design Monirul Islam

Graphics Abdul Malek

Computer Compose Mohammad Mamunur Rashid Printed by M/S Monirampur Printing Press 76/A, Naya Paltan, Dhaka.

ISBN: 984-34-4003-X

©Bangladesh Open University

Bangladesh Open University School of Science and Technology Gazipur-1705 Website: www.bou.edu.bd

Contents Programming Fundamentals ………………………………………………...... Lesson-1: Introduction to Computer Programming……………………………... Lesson-2: Algorithm and Flowchart …….……………………………………… Lesson-3: Overview of C language ………………………………………........... Lesson-4: Basic Structure of C Program ………………………………………...

1 1 2 5 7 9

Keyword, Variable and Data Type ………………………..………………….. Lesson-1: Keyword, and Identifier ……. ……………………………………….. Lesson-2: Variable …………………………………………………………………….. Lesson-3: Constant …………………………………………..………………….. Lesson-4: Data Type …………………………………..……………...................

13 13 14 16 20 22

Operators ……………………………………………………………………...... Lesson-1: Operator Part -1...……..………………………………………............ Lesson-2: Operator Part-2 …………………………………….…………………

26 26 27 30

Decision Making and Branching …………………………………….………... Lesson-1: Basic Concept on Decision Making Statements ……………………... Lesson-2: Decision Making Using If And If-Else Statements ………………...... Lesson-3: Decision Making Using Nesting Of If-Else Statements ……………... Lesson-4: Decision Making Using Else-If Ladder Statements …………………. Lesson-5: Decision Making Using Switch Case Statement ……………………..

33 33 34 36 44 50 56

Decision Making and Looping ………………………………………………… Lesson-1: Basic Concept On Loop Control Structures …………………………. Lesson-2: Understanding While Loop ………………………………………….. Lesson-3: Understanding Do-While Loop ……………………………………… Lesson-4: Understanding For Loop …………………………………………...... Lesson-5: Understanding Break And Continue Statements………….………….. Lesson-6: Understanding goto Statement ………………………….....................

60 60 61 64 68 72 79 87

Arrays and Strings ……………………………………………………………... Lesson-1: Familiar With Arrays………………………………............................ Lesson-2: Familiar with One Dimensional Array ……………………………… Lesson-3: Familiar with Two Dimensional Arrays …………………………….. Lesson-4: Introduction to Strings ……………………………………………..... Lesson-5: Understanding String Handling Functions …………………...............

92 92 93 96 104 115 122

Functions ………………………………………………………………………..

129 129

Unit 1

Unit 2

Unit 3

Unit 4

Unit 5

Unit 6

Unit 7

Lesson-1: Introduction to C functions ………………………………………….. Lesson-2: Function Prototype and Definition …………………………………... Lesson-3: Categories of User Defined Functions ………………………………. Lesson-4: Function With No Arguments and No Return Value ………………... Lesson-5: Function With No Arguments and Return Value ……………………. Lesson-6: Function With Arguments And No Return Value …………………… Lesson-7: Functions With Arguments And Return Value ……………………… Lesson-8: Recursive Function …………………………………………………... Lesson-9: Uses of Local and Global Variables in Function ……………………..

130 133 139 140 143 146 150 154 159

Structures and Unions …………………………………………………………. Lesson-1: Introduction to C Structures …………………………………………. Lesson-2: Structures Initialization ………………………………………………

170 170 171 177

Unit 8

Unit 9 Pointers …………………………………………………………………………………..

Lesson-1: Introduction to C Pointers ……………………………………………. Lesson-2: Pointer Declaration and Initialization ………………………………… Lesson-3: Accessing Variable and Pointer Expression ………………………….. Units True / False and MCQ Answer …………………………………………………

181 181 182 185 188 191

Preface to the 2nd Edition

Computers are used to automate methods for processing information. Apart from information processing, computers play ever increasing role in many other areas of modern life. Programming is a vital element in efficient utilization of a computer. The present volume is written according to the revised syllabus of the “Computer Programming” for distance learners of DCSA Program. The high level programming language “C” has been described in the book to familiar a learner with C language and design a program. The basic aspects of computer programming are presented. Data types, Operator, Loop, array are described. The book is split into 9 units. Important topics such as structures, union and pointers are described in unit 8 and unit 9 respectively. At the end of the each lesson, there is activity, study skill, assignment, exercise and hands on practice for preparation of examination. I am confirm that the book is written in a simple and understandable manner and lessons are organized well, so that learners can adopt and familiar easily while reading the book. Hope that the book is useful for learners, teachers, educators and all concerns. Any suggestion or feedback for further improvement of the book would be highly appreciated.

Amran Hossain Mohammad Mamunur Rashid

School of Science and Technology

Programming Fundamentals INTRODUCTION

DCSA Program

Unit 1

In order to communicate with each other, we use natural languages like Bengali, English, Hindi, Urdu, French, Gujarati etc. We have different language around us in our real life to communicate with each other. Basically, human beings cannot speak or write in computer language, and since computers cannot speak or write in human language, an intermediate language had to be devised to allow people to communicate with the computers. These intermediate languages, known as programming languages, allow computer programmer to direct the activities of the computer. In this unit, we shall be exposed to general terms related to computer programming such as languages, algorithms and flowcharts. You will be familiar with these terms after reading this unit. The importance of an algorithm in a programming language can be realized. This unit overviews history of C language in addition basic structure of a C program is discussed. Timeframe We expect that this unit will take maximum 8 hours to complete. How long ?

Unit Structure Lesson- 1 : Introduction to Computer Programming Lesson- 2 : Algorithm and Flowchart Lesson- 3 : Overview of C language Lesson- 4 : Basic structure of C

1

School of Science and Technology

Lesson-1

DCSA Program

Introduction to Computer Programming

Learning Outcomes

Outcomes Upon completion of this lesson you will be able to    

Define computer programming. State Why Programming. State the Categories of programming language. Define machine, assembly and high-level language. Keywords

Computer, Language, Program, Assembly, Machine

Hope all of you are conscious with the term language. Language is a system of communication between two persons. Observe, In order to communicate with each other, we use languages like Bengali, English, Hindi, Urdu, French etc. We have different language around us in our real life to communicate with each other. However, human beings cannot speak or write in computer language, and since computers cannot speak or write in human language, so an intermediate language had to be devised (design) to allow people to communicate with the computers. These intermediate languages, known as Computer Language, that allow a computer programmer to direct the activities of the computer. COMPUTER PROGRAM Let us first recall computer and what they do.  A computer is an electronic device or machine used for processing data to deliver required information.  A computer is a programmable electronic machine that receives input, stores and process data, and provides output in a useful format.  Computer has no intelligence of its own to perform any task.  We also know that hardware (Computer) is all of the physical equipments or components which are visible and touchable. A computer without a computer program (software) is just a dump box; it is programs that make computers active. The usefulness of the computer depends on the programs that are written to manipulate it. As you know computer cannot do anything on its own and has to be guided (directed) by the user. In order to do any specific job you have to give a sequence of instructions to the computer. This set of instructions is called a computer program. Computer program is a sequence of instructions written in a Computer Language to perform a specified task by the computer. Computer Programming is the process of developing and implementing various sets of instructions to enable a computer to do a certain task. Program is a series of instructions that guides the computer to solve a particular problem.

2

School of Science and Technology

DCSA Program

WHY PROGRAMMING? Hope all of us know that computer can neither think nor make any judgments on its own; it can't do anything by themselves. They do exactly what you tell them to do: no more, no less unlike human beings. Suppose, if someone asks you, “What is the sum of 2+2?” or “add 2+2=?” or just, “2+2=?” you understand anyway but computer is different. Instructions to the computer should be explicitly stated. So we can say that computer needs a program to tell it what to do.

Activity

1. Mention the significance of Computer programming by your own concept. ………………………………………………………………………………….. …………………………………………………………………………………... ..………………………………………………………………………………….

PROGRAMMING LANGUAGE In earlier section we have learnt about computer language, computer program. In this section we will learn about programming language. We have different language around us in our real life to communicate with each other. What do you think if a Bengali person talks to an English man in Bengali language who does not know Bengali, can they communicate with each other? I am sure all of you will say no. In the same way if you tell the computer do this work or koro ei kaj ta, computer will not understand anything because computer understand only its own language (0 and 1). That’s why need programming language. To build programs, people use languages which are similar to human languages that are translated into machine code, which computers understand. A Programming Language (Computer) is composed of a set of characters, words and rules of the language that can be used to perform specific tasks by writing a computer program. Examples of some of the programming languages are BASIC, FORT RAN, COBOL, C, C++ etc. There are three types of programming language according to their levels and they are as follows: 

Machine Language



Assembly language



High Level Language

Low Level Language – Machine Oriented

MACHINE LANGUAGE 

Machine language is the only language that is directly understood by the computer. It is written in binary form that is 0 and1.

It is most efficient for the computer as the instructions are directly executed. 

It is not an easy language to learn because of its complexity as it consists of 1's and 0's. Program instruction may look like this: 1011000111101  Machine language is hardware dependent. A program written for one computer might not run on other computers with different hardware configuration. It is also difficult to debug the program written in this language.  The only advantage is that program of machine language run very fast because no translation program is required for the CPU.  It is considered to the first generation language. The following program is an example of a machine language program for adding two numbers.

3

School of Science and Technology 0011 0000 0000 0000 1000 0011 0110 0000 0111

1110 0111 0110 1010 0000 1010 0110 0000 0110

DCSA Program

Load A register with value 7 value 7 Load B register with 10 A= A + B Store the result into the memory location whose address is 100 (decimal) Halt processing

ASSEMBLY LANGUAGE 

In assembly language, the operation code is expressed as a combination of letters rather than binary numbers, sometimes called mnemonics. This allows the programmer to remember the operations codes easily than when expressed strictly as binary numbers.  Translator program (called Assembler) translate the programs written in assembly language into machine language for execution by the computer.  It is relatively easier to correct errors and modify program instructions.  Assembly Language has almost the same efficiency of execution as the machine language.  Assembly language is machine dependent. A program written for one computer might not run on other computers with different hardware configuration.  It is considered to be a second generation language. Example of an assembly language program for adding two numbers as follows: LDA, 7 Load register A with 7 LDB ,10 Load register B with 10 ADD A,B AA + B LD(100), A Save the result in the location 100 HALT Halt process HIGH LEVEL LANGUAGE      

High Level Languages are user-friendly languages which are similar to English with vocabulary of words and symbols. High level languages are simple language that use English and mathematical symbols like +, , %, /, etc. for its program construction. High level language has to be converted to machine language for the computer to understand. High level languages are easy to learn and use. It is because that they are similar to the languages used by us in our day-to-day life. The code is then translated into object code, using a translator called Compiler or Interpreter. The programs can easily be debugged and are machine independent. For Example: FORTRAN, COBOL, PASCAL C, C++, Java, C#, Visual Basic etc.

4

School of Science and Technology

Lesson-2

DCSA Program

Algorithm and Flowchart

Learning Outcomes

Outcomes Upon completion of this lesson you will be able to     

Define algorithm. Write algorithm. Define flowchart. Explain Flowchart symbols & their meanings. Draw flowchart. Keywords

Algorithm, flowchart, Symbol

ALGORITHM From programming point of view,  An algorithm is a step by step procedure (technique) for solving any problem.  An algorithm is an effective method expressed as a finite set of well defined instructions.  Refers to the logic of a program and step by step description of how to arrive at the solution of a given problem. For example, find the sum of two numbers. Step 1: Start Step 2: Input A Step 3: Input B Step 4: Calculate C = A + B Step 5: Output C Step 6: Stop Another example, Consider the following instructions that you need to boiling water.

Step 1: Start Step 2: Take water in a kettle. Step 3: Place the kettle on the oven. Step 4: Turn the oven on. Step 5: Check whether water is boiled Step 6: Turn the oven off Step 7: Stop FLOWCHART  

5

A flowchart is a graphical/ pictorial representation of an algorithm. a flowchart is most helpful in planning, designing, and structuring a program. Uses symbols (boxes of different shapes) that have standardized meanings to denote different types of instructions.

School of Science and Technology

DCSA Program

 

Process of drawing a flowchart for an algorithm is called flowcharting. Boxes are connected by solid lines having arrow marks to indicate exact sequence in which the instructions are to be executed. Symbols of Flowchart

For example

Advantages of Flowchart    

Efficient coding Systematic debugging Systematic testing Proper documentation

6

School of Science and Technology

Lesson-3

DCSA Program

Overview of C language

Learning Outcomes

Outcomes Upon completion of this lesson you will be able to    

Write history of C. Explain the importance of C. Write application of C. Define compiler and interpreter.

Keywords

History, Unix, Portable

BRIEF HISTORY OF C 

C is a fast, general-purpose, platform independent, high-level programming language that evolved by “Dennis Ritchie” at Bell Laboratories from two previous programming languages, BCPL and B on DEC PDP-11 machine in 1972. Initially, C widely known as the development language of the UNIX operating system but today all new major operating systems are written in C and/or C++. Evolved over the years     

1972 – C invented 1978 – The C Programming Language published; first specification of language 1989 – C89 standard (known as ANSI C or Standard C) 1990 – ANSI C adopted by ISO, known as C90 and 1999 – C99 standard 2007 – work on new C standard C1X announced

WHY C  C is a powerful and flexible language.  C is the most widely used and popular System Programming Language.  C has rich set of built-in functions and support variety of data types & operators.  C is highly portable (Machine independent) and it is static (compiled), typed, structured and imperative.  C has ability to extend itself and it is stable (the language doesn’t change much).  C is quick running (code written in c is efficient & fast).  C is the basis for many other languages (C++, C#, Java, Perl etc).  C is small (only 32 keywords) and it is a Programmers Language. APPLICATIONS OF C  Systems Programming: e.g., compilers and interpreters  Operating System: e.g., Linux ,Unix  Microcontrollers: automobiles and airplanes  Embedded Processors: phones, portable electronics etc.  Database systems and DSP Processors: digital audio and TV systems. CREATION, COMPI LATION AND EXECUTION OF C PROGRAM Environment Setup

7

School of Science and Technology

DCSA Program

Though Environment Setup is not the part of Programming Language, but it is the first step to be followed before setting on to write a program. Thus, we need to have the required software setup, i.e., installation on our PC which will be used to write computer programs, compile, and execute them. Once C compiler is installed in your machine, you can create, compile and execute C programs. You need the following two software tools available on your computer to set up your environment for starting C programming language, (i) Text Editor / Code editor and (ii) C Compiler. You are able to write program in Notepad but, notepad and the other editors don't provide you with the right tools to do software development. That’s why code editor or an IDE is better option instead of notepad. Code editor is a piece of software that you can use to write your code and it will behave like the tool you need to develop software, for example, coloring keywords, display the line numbers that's important for debugging, allow for multiple text manipulation and add a file explorer or project explorer to select the files you need to work on. Beside, a compiler is necessary to compile the program which converts your program (source code) into a language understandable by a computer. So before proceeding, make sure you have C compiler available at your computer. There are many compilers available on the internet and sold commercially in stores or online. Most compilers come with a builtin code editor that can be used to enter source code; however, some don't. When you save a source file, you must give it a name. The name should describe what the program does. In addition, when you save C program source files, give the file a .C extension. COMPILER AND INTERPRETER As we write the code in English and we know that computers can understand only 0s and 1s. So we need a translator which translates the code of our program into machine language. There are two kinds of translators which are known as Interpreter and Compilers. These translators translate our program which is written in C-Language into Machine language. Compilers also translate the English like language (Code written in C) into a language (Machine language) which computers can understand. The Compiler read the entire (whole) program first and then translates it into machine language completely. The program written by the programmer in higherlevel language is called source program. After this program is converted to machine language by the compiler it is called object program. A compiler can translate only those source programs, which have been written, in that language for which the compiler is meant for. For example, FORTRAN compiler will not compile source code written in COBOL language. Interpreters translates the program line by line that means it reads one line of program and translates it into machine language and executes it immediately, then it reads second line, translate it into machine language and executes it immediately and so on. Here translation and execution are carried out for each statement. It differs from compiler, which translate the entire source program into machine code and then involve in its execution. The benefit of it is that we get the errors as we go along and it is very easy to correct the errors. The drawback of the interpreter is that the program executes slowly as the interpreter translates the program line by line. Another drawback is that as interpreters are reading the program line by line so they cannot get the overall picture of the program hence cannot optimize the program making it efficient. The difference between interpreter and compiler is that compiler will stop translating if it finds an error and there will be no executable code generated whereas Interpreter will execute all the lines before error and will stop at the line which contains the error. So Compiler needs syntactically correct program to produce an executable code.

8

School of Science and Technology

Lesson-4

DCSA Program

Basic Structure of C Program

Learning Outcomes

Outcomes Upon completion of this lesson you will be able to 

Explain basic element of C program.

Keywords

Comments, printf, scanf, Compound, Statement

Let us look at a simple program (code) that will print a Line of Text / * first program in C */ #include int main() { printf( "Welcome to C" ); return 0; } Output Welcome to C Let's look at the elements of the program. /* first program in C */ Known as comments. Comments are like helping text in your C program and they are ignored by the compiler and Can appear almost anywhere. They start with /* and terminate with the characters */ #include #include, the first word of any C program. It is also known as pre-processor. The main work of preprocessor is to initialize the environment of program, i.e to link the program with the header file . Standard header files are provided with each compiler, and cover a range of areas like string handling, mathematical functions, data conversion, printing and reading of variables. To use any of the standard functions, the appropriate header file must be included. This is done at the beginning of the C source file. For example, to use the printf() function in a program, the line #include is responsible. main() The next important line is main(). main() function is a function that must be used in every C program. main() function starts the execution of C program. Parentheses “( )” is used to indicate a function. Braces ({ and }) indicate a block. The bodies of all functions must be contained in braces. printf( "Welcome to C" ); The printf() is a library function to send formatted output to display on the screen. Printf() instructs computer to perform an action; specifically, prints the string of characters within quotes (“ ”). There is a semicolon (;) at the end of the above statement. In a C program, the semicolon is a statement

9

School of Science and Technology

DCSA Program

terminator; each individual statement must be ended with a semicolon (;). This is very important missing of a semicolon (;) at the end of statement is a syntax error and compiler will report an error during compilation. return 0; A way to exit a function., in this case terminates the main() function and returns the value 0 Don’t forget to have a main function, or mistype the name, the compiler will give you an error. INPUT/ OUTPUT STATEMENT In this section we will learn how a computer reads data (input) and prints data (output). Two commonly used functions for I/O (Input/Output) are scanf() and printf(). scanf() function scanf() function reads one or more values from an input device, and stores them into variables specified by the programmer. In scanf() syntax a special character format specifier is used to specify the data type of value.  In C programming language, scanf() function is used to read character, string, numeric data from keyboard.  The format specifier %d is used in scanf() statement. So that, the value entered is received as an integer and %s for string.  Ampersand (&) is used before variable name in scanf() statement as &number. Syntax scanf("format specifiers",&value1,&value2,.....); Example int a; float b; char c; scanf("%d%f %c ",&a,&b,&c); In the above example scanf() is able to read three input values ( integer, float value and character) and those are stored in a, b and c variable respectively. Format specifier: Format specifier Type of value %d Integer %f Float %lf Double %c Single character %s String %u Unsigned int %ld Long int %lf Long double printf() function Printf is a predefined function in "stdio.h" header file, by using this function, we can display the data or user defined message on monitor. 

In C programming language, printf() function is used to display the “character, string, float, integer, octal and hexadecimal values” onto the output screen. While working with printf(), it can take any number of arguments but first argument must be within the double cotes (" ") and every argument should separated with comma ( , ) Within the double cotes, whatever we pass, it prints same.

10

School of Science and Technology

DCSA Program



We use printf() function with %d format specifier to display the value of an integer variable. Similarly %c is used to display character, %f for float variable, %s for string variable, %lf for double and %x for hexadecimal variable.  To create a newline,we use “\n” in C printf() statement. Syntax printf("user defined message"); prinf("Format specifers",value1,value2,..); Example of printf() function int a=10; double d=13.4; char c='A'; printf("%f%d",d,a,c); SIMPLE AND COMPOUND STATEMENT Statements can be either simple or compound. A simple statement performs a single action. Examples of simple statements are as follows: printf( "Welcome to C" ); int i = 12; Compound statement does several actions in sequence. A compound statement is composed of simple statements enclosed within a pair of braces {}. The following is an example of compound statements in C. { pi= 3.141593; area= pi*radius*radius; } Summary

Summary In this lesson   

We have understood C programming language and programming language types. Also understood difference betwen compiler and interpreter. Also understood various C syntax, flowchart and formate specefier.

Assessment Fill in the blanks Assessment

1. ……….. developed the C language. 2. printf() is used to ……. the output and scanf() is used to ……... the input. 3. C programs are stored with ………. Extension. Multiple Choice Questions (MCQ) 1. What is a program? a) set of instruction c) set of algorithm b) set of pseudo code d) none of these 2. Which of the following is a graphical representation of a program’s flow?

11

School of Science and Technology

DCSA Program

a) algorithm c) control of flow b) flowchart d) UML diagram 3. The C language has been developed at? a) AT & T Bell Labs c) IBM b) Borland International d) Sun Microsystems 4. What is the only function that all C programs must contain? a) start() c) system() b) main() d) program() 5. Which of the following is the correct way of writing comments? a) */comments/* c)**comment** b) /*comment*/ d){comment} Exercises 1. 2. 3. 4. 5. 6. 7. 8.

Define computer programming language. Define machine, assembly and high-level languages. Differentiate between an interpreter and compiler. Compare an algorithm with a flowchart. Explain the symbols for flowchart. Write the syntax of printf and scanf function. Define simple and compound statement. Write the format specifier available in C language.

12

School of Science and Technology

Keyword, Variable and Data Type INTRODUCTION

DCSA Program

Unit 2

C tokens, Identifiers and Keywords are the basics and are part of the syntax in a C program. All are explained in this unit with definition and simple example programs. Also, you will learn about variables, rules for naming a variable, constants and different type of constants in C programming. Through this unit you will learn about data types which are very important in programming. C data types are defined as the data storage format that a variable can store a data to perform a specific operation. Size of variable, constant and array are determined by data types. C language has some predefined set of data types to handle various kinds of data that we use in our program. Timeframe We expect that this unit will take maximum 8 hours to complete. How long ?

Unit Structure Lesson- 1 : Keyword and Identifier Lesson- 2 : Variable Lesson- 3 : Constant Lesson- 4 : Data type

13

School of Science and Technology

Lesson -1

DCSA Program

Keyword and Identifier

Learning Outcomes

Outcomes Upon completion of this lesson you will be able to 

Define token.



Define identifier.



Define keyword. Keywords

Identifier, Token

TOKENS IN C A C program consists of various tokens and a token is either keywords, an identifiers, a constants, a strings literal, operator or a symbols. KEYWORDS Keywords are pre-defined words in a C compiler. Each keyword is meant to perform a specific function. Different programming languages have different set of reserved keywords, but there is one important and common rule in all the programming languages that these reserved words cannot be used as constants or variables or any other identifier names. So we should keep in mind that; while giving a name to your variable, constants or any other identifier you should not use any reserved keyword for that programming language. The following list shows the reserved words in C. auto

else

case

extern return

const

for

default if

long

switch break

enum register typedef

union

float

char

short

unsigned

signed void

continue goto

sizeof

volatile

static

do

struct

_Packed

while

int

double

Keywords cannot be used as constants or variables or any other identifier names.

IDENTIFIER In C any name is called identifier. This name can be variable name, function name, enum constant name, micro constant name, goto label name, any other data type name like structure, union, enum names or typedef name. In other words in C, identifier is a name used to identify a variable, function, or any other user defined item. Rules for constructing identifiers  First character must be an alphabet or underscore and subsequent characters must be either letter, digits, or underscore.

14

School of Science and Technology

DCSA Program

  

C does not allow punctuation characters such as @, $, and % within identifiers. Only 31 characters are significant. Can not be the same as C keywords and should not have the same name as functions that are in C library.  C is a case-sensitive programming language. Thus, Name, names, NAME are three different identifiers in C.  Must not contain white space Here are some examples of acceptable identifiers: mohd zara abc move_name a_123 myname50 _temp j a23b9 retVal 1. Let’s do simple exercise. In this exercise we will match valid and invalid identifier. Activity

Match the column

valid identifier

invalid identifier

2.

Determine which of the following are valid identifiers. If invalid, explain why. a) c) e) g) i)

15

(a)_no (b) 34_ (c) char (d) _char (e)num ber (f) @no

record1 file_3 $tax name and address name-and-address

b) d) f) h) j)

1record return name name_and_address 123-45-6789.

School of Science and Technology

Lesson-2

DCSA Program

Variable

Learning Outcomes

Outcomes Upon completion of this lesson you will be able to 

Define variable.



Declare variables and assign values to variables.



Write programs using variables.

Keywords

Variable, Declaration

VARIABLE

Computer programs usually work with different types of data and need a way to store the values being used. These values can be numbers or characters. C has two ways of storing number values such as variables and constants with many options for each. A variable is a data storage location that has a value that can change during program execution. So finally we can say that an identifier whose value is allowed to change during the execution of a program is called a variable. Every variable must be individually declared (i.e., defined) before it can appear in a statement. In other word we can say variable is container of data. In real world you have used various type containers for specific purpose. For example you have used match box to store match sticks, file cabinet to store files etc. In the same way variables of different data type is used to store different types of data. As for example integer variables are used to store integers char variables is used to store characters etc. Before you get to variables, you need to know a little about the operation of your computer's memory. Hope all of us already know that computer uses random access memory (RAM) to store information while it's operating. Each computer has a certain amount of RAM installed. RAM is located in integrated circuits, or chips, inside your computer. RAM is volatile, which means that it is erased and replaced with new information as often as needed. Being volatile also means that RAM "remembers" only while the computer is turned on and loses its information when you turn the computer off. The amount of RAM in a system is usually specified in kilobytes (KB) or megabytes (MB), or gigabytes (GB) and so on One kilobyte of memory consists of 1,024 bytes. Thus, a system with 640KB of memory actually has 640 * 1,024, or 65,536, bytes of RAM. One megabyte is 1,024 kilobytes. A machine with 4MB of RAM would have 4,096KB or 4,194,304 bytes of RAM. The RAM in computer is organized sequentially, one byte following another. Each byte of memory has a unique address by which it is identified an address that also distinguishes it from all other bytes in memory. Now that you understand a little about the nuts and bolts of memory storage, you can get back to C programming and how C uses memory to store information. In programming, a variable is a container (storage area) to hold data. To indicate the storage area, each variable should be given a unique name (identifier). Variable name is just the representation of a memory location. Every variable must be individually Study skills

16

School of Science and Technology

DCSA Program

declared (i.e., defined) before it can appear in a statement and value of the variable can change during program execution. For example: int number = 15; Here, number is a variable of integer type. The variable is assigned value 15. PROPERTIES OF VARIABLE IN C: Every variable in c have three most fundamental attributes. They are: 1. Name 2. Value 3. Address VARIABLE DECLARATIONS C programming language requires a variable creation, i.e., declaration before its usage in your program. You cannot use a variable name in your program without declaring it. The purposes of a variable declaration tells the compiler what the variable name is.  specifies what type of data the variable will hold. Where variables to be declared: - Inside function (local variables) - In the definition of function parameters (Formal parameters) - Outside of all functions (global variables) A variable declaration has the following form: General syntax: type varable_name; Example: int a float temp; char flag, ; You can declare multiple variables of the same type on one line by separating the variable names with commas: int count, number, start; /* three integer variables */ float percent, total; /* two float variables If your program attempts to use a variable that hasn't been declared, the compiler generates an error message. STORING VALUES IN VARIABLES You have seen how to declare variables in the previous section. Now, let's store some values in those variables: int a; int b; a = 10; b = 20; Here we are storing 10 in variable a and 20 in variable b. Almost all the programming languages have similar way of storing values in variable where we keep variable name in the left side of an equal sign = and value we want to store in the variable, we keep that value in the right side. When above statement is executed, the memory location named a will hold 10 and memory location b will hold 20.

17

School of Science and Technology

DCSA Program

Some more examples: int a, b, sum; a = 50; b = 60; sum = a + b; We can also assign value at the time of declare as follows int a = 50, b = 60, sum; sum = a + b; CATEGORY OF C VARIABLE

On the basis of how many data a variable will store, we can categorize the all c variable in three groups. 1. Variables which can store only one data at time. Example: integer variables, char variables, pointer variables etc. 2. Variables which can store more than one data of similar type at a time. Example: array variables 3. Variables, which can store more than one value of dissimilar type at a time. Example: structure or union variables. Not two variables in c can have same name with same visibility. For example: #include int main(){ auto int a=5; //Visibility is within main block static int a=10; //Visibility is within main block /* Two variables of same name */ printf("%d",a); return 0; } Output: compilation error But it is possible that two variable with same name but different visibility. In this case variable name can access only that variable which is more local. In c there is not any way to access global variable if any local variable is present of same name. For example: (a) #include int a=50; //Visibility is whole the program int main(){ int a=10; //Visibility within main block printf("%d",a); return 0; } Output: 10 (b) #include int main(){ int a=10; //Visibility within main block. { a=a+5; //Accessing outer local variable a. int a=20; //Visibility within inner block. a=a+10; //Accessing inner local variable a.

18

School of Science and Technology

DCSA Program

printf(“%d”,a);//Accessing inner local variable a. } printf(“%d”,a); //Accessing outer local variable a. return 0; } Output: 30 15 RULES FOR NAMING VARIABLES To use variables in your C programs, you must know how to create variable names. In C, variable names must adhere to the following rules:  The name can contain letters, digits, and the underscore character (_).  The first character of the name must be a letter. The underscore is also a legal first character, but its use is not recommended.  Case matters (that is, upper- and lowercase letters). Thus, the names count and Count refer to two different variables.  C keywords can't be used as variable names. A keyword is a word that is part of the C language The following list contains some examples of legal and illegal C variable names: Variable Percent y2x5__ annual_ _1990_tax savings#account double 9winter

Study skills

19

Name Percent fg7h profit Legal Illegal: Illegal: Illegal:

Legality Legal Legal Legal but not advised Contains the illegal character # Is a C keyword First character is a digit

Let’s consider a simple example. In this example we take two integers, add them and display the answer on the screen. The code of the program is written below. #include main() { int x; int y; int z; x = 5; y = 10; z = x + y; } The first three lines declare three variables x, y and z. These three declarations can also be written on one line. C provides us the comma separator (,). The above three lines can be written in a single line as below int x, y, z;  As we know that semicolon (;) indicates the end of the statement. So we can write many statements on a single line. In this way we can also write the above declarations in the following form int x; int y; int z;  For good programming practice, write a single statement on a single line.  We have declared all the variables in a single line by using comma separator (,). This is a short method to declare a number of variables of the same data type.

School of Science and Technology

DCSA Program

Lesson-3 Constant Learning Outcomes

Outcomes Upon completion of this lesson you will be able to 

Define constant.



Declare constant.



Apply escape sequence. Keywords

Constants, Escape Sequence

CONSTANT Like a variable, a constant is a data storage location used by your program. As its name implies, the value stored in a constant can't be changed (fixed) during program execution. Constants (i.e., fixed values) are also called literals. A constant is a value or an identifier whose value cannot be altered in a program. For example: 1, 2.5, "C programming", etc. As mentioned, an identifier also can be defined as a constant. const double PI = 3.14 INTEGER CONSTANT An integer constant is a numeric constant (associated with number) without any fractional or exponential part. There are three types of integer constants in C programming:  decimal constant(base 10)  octal constant(base 8)  hexadecimal constant(base 16) For example: Decimal constants: 0, -9, 22 etc Octal constants: 021, 077, 033 etc Hexadecimal constants: 0x7f, 0x2a, 0x521 etc In C programming, octal constant starts with a 0 and hexadecimal constant starts with a 0x. FLOATING-POINT CONSTANT A floating point constant is a numeric constant that has either a fractional form or an exponent form. For example: -2.0 0.0000234 -0.22E-5 CHARACTER CONSTANT A character constant is a constant which uses single quotation around characters. For example: 'a', 'l', 'm', 'F' STRING CONSTANT String constants are the constants which are enclosed in a pair of double-quote marks. For example: "Bangladesh" //string constant "" //null string constant " " //string constant of six white space

20

School of Science and Technology

DCSA Program

"x" //string constant having single character. "Bangladesh Open University\n" //prints string with newline ESCAPE SEQUENCES There are some characters which we use very frequently but they are invisible in your program and these characters are spaces, tabs (\t), new lines (\n). These characters are called whitespaces. These three important whitespace characters are common in all the programming languages and they remain invisible in your text document. In order to use these characters, escape sequence is used. Escape Sequences Escape Sequences Character \b Backspace \f Form feed \n Newline \r Return \t Horizontal tab \v Vertical tab \\ Backslash \' Single quotation mark \" Double quotation mark \? Question mark \0 Null character

1. Determine which of the following are valid character constants? Activity

a) b) c) d) e) f) g) h) i) j)

`a` `$` `\n` `/n` `\\` `\a` `T` `\0` `xyz` `\052`.

2. Determine which of the following are valid string constants? a) b) c) d) e) f) g)

21

`8:15 P.M.` ``Red, White and Blue`` ``Name: ``Chap. 3 (Cont\’d)`` ``1.3e-12 ``NEW YORK, NY 10020`` ``The professor said, “Please don’t sleep in class``

School of Science and Technology

DCSA Program

Lesson-4 Data Type Learning Outcomes

Outcomes Upon completion of this lesson you will be able to 

Define data type.



Describe the data type in C.



Understand the declaration of data type.

Keywords

integer, float, double.

INTRODUCING C DATA TYPE Every programming language deals with some data. For example to print any message it requires charterer or string type of data. To solve any mathematic expression it requires integral as well as real number (floating type) of data. C is very rich in data type. Data types specify how we enter data into our programs and what type of data we enter. C language has some predefined set of data types to handle various kinds of data that we use in our program. These data types have different storage capacities. Data types are used to define a variable before to use in a program. Size of variable, constant and array are determined by data types. There are four data types in C language. C DATA TYPES Types Basic data types Enumeration data type Derived data type Void data type

Data Types int, char, float, double enum pointer, array, structure, union void

INTEGER DATA TYPE  Integer data type allows a variable to store numeric values.  “int” keyword is used to refer integer data type.  The storage size of int data type is 2 or 4 or 8 byte.  It varies depend upon the processor in the CPU that we use. If we are using 16 bitprocessor, 2 byte (16 bit) of memory will be allocated for int data type. Like wise, 4 byte (32 bit) of memory for 32 bit processor and 8 byte (64 bit) of memory for 64 bit processor is allocated for int datatype.  int (2 byte) can store values from -32,768 to +32,767  int (4 byte) can store values from -2,147,483,648 to +2,147,483,647.  If you want to use the integer value that crosses the above limit, you can go for “long int” and “long long int” for which the limits are very high.

22

School of Science and Technology

DCSA Program

We can’t store decimal values using int data type. If we use int data type to store decimal values, decimal values will be truncated and we will get only whole number. In this case, float data type can be used to store decimal values in a variable. FLOATING POINT DATA TYPE: Floating point data type consists of 2 types. They are, 1. float 2. double FLOAT  Float data type allows a variable to store decimal values.  Storage size of float data type is 4. This also varies depend upon the processor in the CPU as “int” data type.  We can use up-to 6 digits after decimal using float data type.  For example, 10.456789 can be stored in a variable using float data type. DOUBLE  Double data type is also same as float data type which allows up-to 10 digits after decimal.  The range for double datatype is from 1E–37 to 1E+37 CHARACTER DATA TYPE So far we have been looking on data types to store numbers, In programming we do need to store characters like a,b,c etc. For storing the character data C language provides char data type. By using char data type we can store characters in variables. While assigning a character value to a char type variable single quotes are used around the character as ‘a’.  Character data type allows a variable to store only one character.  Storage size of character data type is 1. We can store only one character using character data type.  “char” keyword is used to refer character data type.  For example, ‘A’ can be stored using char datatype. You can’t store more than one character using char data type. Let’s take a look into different data types that the C language provides us to deal with whole numbers, real numbers and character data. int - data type int is used to define integer numbers. #include int main() { int number; printf("Enter an integer: "); scanf("%d",&number); printf("Entered Number is = %d",number); return 0; } Output Enter an integer: 4 Entered Number is = 4 float - data type float is used to define floating point numbers.

23

School of Science and Technology

DCSA Program

#include int main() { float f; printf("Enter a number: "); scanf("%f",&f); printf("Value = %f", f); return 0; } Output Enter a number: 23.45 Value = 23.450000 double - data type double is used to define BIG floating point numbers. It reserves twice the storage for the number. { double atoms; atoms = 2500000; } char - data type #include int main() { char chr; printf("Enter a character: "); scanf("%c",&chr); printf("You entered %c.",chr); return 0; } Output Enter a character: g You entered g. { char letter; letter = 'x'; } DERIVED DATA TYPE IN C LANGUAGE Array, pointer, structure and union are called derived data type in C language. You will learn about these from the next units. Size of data types in c DATA TYPE SIZE (IN BYTE) int 2 short int 2 long int 4 float 4 double 8 long double 10 char 1

24

School of Science and Technology enum

DCSA Program 2

Summary

Summary In this lesson   

We have understood about C keywords and data types. Also understood C constants and variables. Also understood that how variables are declared in program.

Assessment Fill in the blanks Assessment

1. A character constant which uses ………………..around characters. 2. Variable is a ………………………to hold data. Multiple Choice Questions (MCQ) 1. Which of the following are tokens in C? a) Keywords b) Variables c) Constants d) All of the above 2. Which of the following is not a keyword a) void b) int c) main d) for

Exercises 1. Describe the keywords and identifiers in C. 2. What is variable? Discuss how to declare variables and assign values to variables with an example. 3. What is constant? 4. What is the difference between a constant and a variable? 5. What is a string constant? How do string constants differ from character constants? Do string constants represent numerical values? 6. Write simple programs using constants and variables 7. What is data type? Describe the data types in C.?

25

School of Science and Technology

DCSA Program

Operators Unit 3

INTRODUCTION

In the previous units (unit 1 and 2) you have learned about the basics of computer programming, different data types, constants, keywords and basic structure of a C program. You've learned how to declare and initialize variables and constant. In this unit you will learn about operator, Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result; and finally will explore the operators available in C programming language. Timeframe We expect that this unit will take maximum 3 hours to complete. How long ?

Unit Structure Lesson- 1 : Operator part -1 Lesson- 2 : Operator part -2

26

School of Science and Technology

Lesson -1

DCSA Program

Operator Part-1

Learning Outcomes

Outcomes Upon completion of this lesson you will be able to  Define Operator.  Classify Operator.  Explain arithmetic operator. Keywords

Operator, Arithmetic, Precedence

OPERATOR An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. Operators, functions, constants and variables are combined together to form expressions. Consider the expression A + B * 5 where, +, * are operators, A, B are variables, 5 is constant and A + B * 5 is an expression. C language is rich in built-in operators and provides the following types of operators: Types of Operators Arithmetic operators Assignment operators Relational operators Logical operators Bit wise operators Conditional (ternary) operators Increment/decrement operators Special operators

Description These are used to perform mathematical calculations like addition, subtraction, multiplication, division and modulus These are used to assign the values for the variables in C programs. These operators are used to compare the value of two variables. These operators are used to perform logical operations on the given two variables. These operators are used to perform bit operations on given two variables. Conditional operators return one value if condition is true and returns another value is condition is false. These operators are used to either increase or decrease the value of the variable by one. &, *, sizeof( ) and ternary operators.

ARITHMETIC OPERATORS Computer programs are widely used for mathematical calculations. In C language we have the usual arithmetic operators for addition, subtraction, multiplication and division. C also provides a special arithmetic operator which is called modulus. All these operators are binary operators which means they operate on two operands. So we need two values for addition, subtraction, multiplication, division and modulus. The following table lists down a few of the important arithmetic operators available in C programming language. Assume variable x holds 10 and variable y holds 20, then:

27

School of Science and Technology

DCSA Program

OPERATOR

OPERATION

DESCRIPTIONS

+ -

Addition Subtraction

Adds two operands Subtracts second operand from the first

* /

Multiplication Division

%

Modulus

Multiplies both operands Divides numerator by de-numerator provide remainder of an integer division

C EXPRESSION x+y x-y

EXAMPLE

x*y x/y

x * y = 200 x/y=2

x%y

x%y=0

x + y = 30 x-y = 10

Addition, subtraction and multiplication are same as we use in algebra. There is one thing to note in division that when we use integer division (i.e. both operands are integers) yields an integer result. This means that if, for example, you are dividing 5 by 2 (5 / 2) it will give integer result as 2 instead of actual result 2.5. Thus in integer division the result is truncated to the whole number, the fractional part (after decimal) is ignored. If we want to get the correct result, then we should use float data type. The modulus operator returns the remainder after division. This operator can only be used with integer operands. The expression x % y returns the remainder after x is divided by y. For example, the result of 5 % 2 will be 1, 23 % 5 will be 3 and 107%10 will be 7. INCREMENT, DECREMENT OPERATORS (++, --) Increment and decrement are common arithmetic operation. C provides two short cuts for the same. Postfix- will return the current value and then increment/ decrement. x++ is a short cut for x=x+1; will return the current value and then increment. x-- is a short cut for x=x-1; will return the current value and then decrement. Prefix: ++x is a short cut for x=x+1; will increment x and then return the value (so it will return one greater than the original value) --x is a short cut for x=x-1; will decrement a and then return the value (so it will return one less than the original value) PRECEDENCE OF OPERATORS The arithmetic operators in an expression are evaluated according to their precedence. The precedence means which operator will be evaluated first and which will be evaluated after that and so on. In an expression, the parentheses ( ) are used to force the evaluation order. The operators in the parentheses ( ) are evaluated first. If there are nested parentheses then the inner most is evaluated first. The expressions are always evaluated from left to right. The operators *, / and % have the highest precedence after parentheses. These operators are evaluated before + and – operators. Thus + and – operators has the lowest precedence. It means that if there are * and + operators in an expression then first the * will be evaluated and then its result will be added to other operand. If there are * and / operators in an expression then the operator which occurs first from left will be evaluated first and then the next, except you force any operator to evaluate by putting parentheses around it. The following table explains the precedence of the arithmetic operators: OPERATOR () *, /, or % + or -

OPERATIONS Parentheses Multiplication, Division, Modulus Addition, Subtraction

PRECEDENCE (ORDER OF EVALUATION) Evaluated first Evaluated second. If there are several, they are evaluated from left to right Evaluated last. If there are several, they are evaluated from left to right

28

School of Science and Technology

DCSA Program

Let’s look some examples. What is the result of 10 + 10 * 5? The answer is 60 not 100. As * has higher precedence than + so 10 * 5 is evaluated first and then the answer 50 is added to 10 and we get the result 60. The answer will be 100 if we force the addition operation to be done first by putting 10 + 10 in parentheses. Thus the same expression rewritten as (10 + 10) * 5 will give the result 100. Note that how the parentheses affect the evaluation of an expression. Similarly the expression 5 * 3 + 6 / 3 gives the answer 17, and not 7. The evaluation of this expression can be clarified by writing it with the use of parentheses as (5 * 3) + (6 /3) which gives 15 + 2 = 17. Thus you should be careful while writing arithmetic expressions.

Activity

1. Suppose a, b and c are integer variables that have been assigned the values a = 8, b = 3 and c = -5. Determine the value of each of the following arithmetic expressions. a) a +b + c b) 2 * b + 3 * (a-c) c) a / b d) a % b e) a * b / c f) a * (b / c) g) (a * c) % b h) a * (c % b). 2. Is 2 + 5 * 2 equal to (2 + 5) * 2? 3. Does 7 % 2 produce the same result as 4 % 3?

29

School of Science and Technology

Lesson-2

DCSA Program

Operator Part-2

Learning Outcomes

Outcomes Upon completion of this lesson you will be able to 

Define relational operator.



Use logical Operator.



Explain assignment operator.

Keywords

Relational, Logical, Bitwise

RELATIONAL OPERATOR A relational operator takes a pair of expressions as operands and returns a logical value, true or false. There are six common relational operators: ==, !=, >, <  ,  , . The following table shows all the relational operators supported by C. Assume variable x holds 10 and variable y holds 20, then: OPERATOR == != > < >= y) is not true. (x < y) is true. (x >= y) is not true. (x 5)&&(y=10)||(y>=10) || condition becomes true. Logical NOT Use to reverses the logical state of its ! operand. If a condition is true then Logical !((x>5)&&(y 100 ? 0 : 1); In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if else conditional statements. One more example if(a > b) result = x; else result = y; is equivalent to result = a > b ? x : y;

Study skills

31

1. What is the output of this C code? #include int main() { int a = 1, b = 1, c; c = a++ + b; printf("%d, %d", a, b); } a) a = 1, b = 1 b) a = 2, b = 1 c) a = 1, b = 2 d) a = 2, b = 2 Correct answer is: b

2. What is the output of this C code? #include int main() { int a = 10, b = 10; if (a = 5) b--; printf("%d, %d", a, b--); } a) a = 10, b = 9 b) a = 10, b = 8 c) a = 5, b = 9 d) a = 5, b = 8

School of Science and Technology

DCSA Program

Summary

Summary In this lesson  

We have understood about various types of C operators and operands. Also understood operator precedence.

Assessment

Assessment

Fill in the blanks 3. In C logical AND represents as………… 4. …….. operator is called “modulus operator” in C Multiple Choice Questions (MCQ) 1. Which of the following is not an arithmetic operation? e) a *= 10; f) a /= 10; g) a != 10; h) a %= 10; 2. The operator + in a+=4 means a) a=a+4 b) a + 4 = a c) a = 4 d) a = 4 + 4 3. The most commonly used assignment operator is a) = b) == c) >= d) :=

Exercises 1. State C operators and their classification. 2. What is an operand? What is the relationship between operators and operands? 3. Write the difference between = and == in C programming. 4. Describe the arithmetic, relational, logical, assignment, increment, decrement and conditional operators with suitable example. 5. Describe the precedence of arithmetic operators. 6. Write programs using operators. 7. Describe the four relational operators include in C. With what type of operands can they be used?

32

School of Science and Technology

DCSA Program

Decision Making and Branching Unit 4 INTRODUCTION In the previous lessons we have learned about the programming structure, data types, declaration of variables, tokens, constants, keywords and operators as well as how to write program in C and how to execute program. In this unit we will teach about another feature of C. In this unit we will also learn how to make a decision in program and how to execute this concept. Timeframe We expect that this unit will take maximum 10 hours to complete. How long ?

Unit Structure Lesson- 1 : Basic concept on decision making statements Lesson- 2 : Decision making using if and if-else statements Lesson- 3 : Decision making using nesting of if-else statements Lesson- 4 : Decision making using else-if ladder statements Lesson- 5 : Decision making using switch case statements

33

School of Science and Technology

Lesson-1

DCSA Program

Basic Concept on Decision Making Statements

Learning Outcomes

Outcomes Upon completion of this lesson you will be able to 

Understand basic idea about decision making statements.

Keywords

Decision making, Statements, Control, Execution

PRELIMINARIES We have already seen that, basically a C program is a set of statements which are usually executed successively. But in practice, we have a number of situations where we may have to change the order of execution of statements based on certain conditions, or replicate a group of statements until certain specified circumstances are met. The general form of a standard decision making structure found in most of the programming languages like C is as follows: Entry Condition ?

If condition is true Conditional code

If condition is false

Figure 4.1.1 General form of decision making structure C language handles decision-making by supporting the following statements: i. ii. iii. iv. v.

if statement if-else statement nesting if-else statement else-if ladder statement switch case statement

34

School of Science and Technology

DCSA Program

We have a number of situations where we may have to change the order of execution of statements based on certain conditions The above decision making statements are shortly described here, and described in details in next lessons. 

  



if statement: if statement is used to control the flow of execution of statements. It allows evaluate the condition or expression first and then, depending on whether the value of the expression is true or false. if-else statement: if-else statement is used to carry out a logical test and then take one of two possible actions depending on the result of the test. Nesting if-else statement: nesting if-else statements are used, when a series of decisions are concerned, we may have to employ more than one if-else statement. else-if ladder statements: else-if ladder statements are used, when multipath decisions are concerned. A multipath decision is a chain of ifs in which the statement associated with each else is an if. switch case statement: switch statement checks the value of a given expression against a list of case values and when a match is found a block of statements associated with the case is executed.

Summary

Summary In this lesson 

We have understood about C language decision making statements.

Assessment Fill in the blanks Assessment

1. if statement is used to ……………………. of execution of statements. 2. A multipath decision is a chain of…………………. 3. if-else statement is used to carry out a ……….. test. Multiple Choice Questions (MCQ) 1. C language handles decision-making by supportinga) 3 statements b) 4 statements c) 5 statements d) 6 statements 2. Nesting if-else statements are useda) When a series of decisions are b) When a single of decision is concerned concerned c) No decision are allowed d) None of these

Exercises 1. What do you mean by control statement? 2. Explain shortly various decision making statements.

35

School of Science and Technology

DCSA Program

Decision Making Using if and if-else Statements

Lesson-2 Learning Outcomes

Outcomes Upon completion of this lesson you will be able to 

Understand about the if statement.



Understand about the if-else statement.

Keywords

Statement, If, If-else, Execution, Expression, Condition

SIMPLE IF STATEMENT The simple if statement is an influential decision making statement. It is used to control the flow of execution of statements. On other hand, it is also a two-way decision making statement. It is also used to evaluate the expression or condition first and then, depending on whether the value of the expression is true or false. The general structure of a simple if statement is as follows: if ( Condition/expression ) { Statement-block; …………………. } Statement-n;

Here, statement-block can be single or a group of statements. If condition/expression is true then, the statement-block will be executed, otherwise the statement-block will be omitted and the execution will jump to the statement-n. In this situation, it is remembered that, when the condition is true both the statement-block and statement-n are executed in sequence. The general flow chart of if statement is shown in below:

36

School of Science and Technology

DCSA Program

Entry

Test Conditions ?

True

Statement-block

False Statement-n

Next Statement Figure 4.2.1: Flowchart of simple if control statement Consider the following program segment: void Main() { ……………………………. …………………………… if( N= =100) { N=N+50; } printf(“%d”, N); . …………………… …………………….. } In the above program segment, the program checks the value of N. If the value of N is 100 then extra 50 are added with N before printed, otherwise the value of N will be printed. The if statement is used to evaluate the expression or condition first and then, depending on whether the value of the expression is true or false

Program 4.2.1 Write a program to display a number if user enters negative number. If user enters positive number, that number won't be displayed.

#include #include void main() { int num; printf("Enter Integer Number:"); scanf("%d",&num);

37

School of Science and Technology

DCSA Program

if(num < 0) { printf("You entered %d. \n", num); } printf("Have a nice Day!!"); getch(); } …………………………………………………………………………………… Output Enter Integer Number:-10 You entered -10. Have a nice Day!! Enter Integer Number: 50 Have a nice Day!!

Program 4.2.2 Write a program to display salary of an employee, where if salary is less than 20000 taka then add home allowance 5000 taka with basic salary, otherwise display salary without home allowance.

#include #include void main() { long int salary; printf("Enter Basic salary of an employee:"); scanf("%ld",&salary); if(salary < 20000) { salary=salary+5000; } printf("Employee Salary is:%ld\n",salary); getch(); } ……………………………………………………………………………………. Output Enter Basic salary of an employee: 10000 Employee Salary is:15000 Enter Basic salary of an employee: 30000 Employee Salary is:30000 SIMPLE IF-ELSE STATEMENT The if-else statement is an extension of the simple if statement. This type of statement is used to carry out a logical test and then take one of the two possible actions depending on the result of the test. The general structure of if-else statement is as follows: if (test condition/expression) {

38

School of Science and Technology

DCSA Program

True statements-block; } else { False statements-block; } statement- n; The if-else statement executes some code if the test condition or expression is true and some other code if the test expression or condition is false. Here, if the test condition or expression is true (non-zero) then true statements-block is executed otherwise false (zero) statements-block is executed. It is remembered that, in if-else statement, either true statements-block or false statements-block will be executed, not both. In both cases the control is transferred subsequently to statement-n. The general flow chart of if-else statement is shown in below:

Entry

Test Condition/expression ?

True

True statements-block

False

False statements-block

Statement-n Figure 4.2.2: flowchart of if-else control statement Consider the following program segment: void main() { ................ ................ if(test= = 1) { scanf("%f",&radious); Area=3.14159*radious*radious; printf("Area of Circle is:= %f\n",Area); } else

39

School of Science and Technology

DCSA Program

{ scanf("%f %f",&base,&height); Area=0.5*base*height; printf("Area of traingle is:= %f\n",Area); } } In the above example, if the variable test value is only 1 then true statement block of if will be executed and print the area of circle, otherwise false statement block of else will be executed and print the area of triangle. Consider another programming example is as follows: void main() { int age; printf(" Enter your real age:"); scanf("%d",&age); if(age >= 18) { printf("you are eligible for voting."); } else { printf("you are not eligible for voting."); } } In the above example, user enter his or her age from keyboard, if the variable age value is greater than or equal 18 years then, true statement block of if will be executed and print ‘you are eligible for voting’, otherwise false statement block of else will be executed and print ‘you are not eligible for voting’. The if-else statement executes some code if the test condition or expression is true and some other code if the test expression or condition is false.

Program 4.2.3 write a program that checks a number is either EVEN or ODD. #include #include void main() { clrscr(); int number; printf("Enter a integer number:"); scanf("%d",&number);

40

School of Science and Technology

DCSA Program

if(number%2==0) { printf("Given Number is EVEN.\n"); } else { printf("Given Number is ODD.\n"); } getch(); } ………………………………………………………………………………….. Output Enter a integer number: 100 Given Number is EVEN. Enter a integer number: 15 Given Number is ODD

Program 4.2.4 Write a program to print employee monthly salary, where, if basic salary is grater that 20000 taka then 40% home allowance of basic salary and 1500 taka medical allowance are added with basic salary, otherwise 55% home allowance and 1000 taka medical allowance are added with basic salary. #include #include void main() { clrscr(); long int bsalary,msalary; printf("Enter Employee Basic salary: "); scanf("%ld",&bsalary); if(bsalary > 20000) { msalary=bsalary+bsalary*0.4+1500; printf("Employee Monthly Salary is: %ld",msalary); } else { msalary=bsalary+bsalary*0.55+1000; printf("Employee Monthly Salary is: %ld",msalary); } getch(); } …………………………………………………………………………………… Output Enter Employee Basic salary: 30000 Employee Monthly Salary is: 43500 Enter Employee Basic salary: 20000 Employee Monthly Salary is: 32000

41

School of Science and Technology

DCSA Program

1. Determine the output of the following program segment

Study skills

void main( ) { ....................... ...................... Test= 50; if( Test>=10) { printf(“%d”,Test); } Test= Test+100; printf(“%d”,Test); } 2. Determine the output of the following program segment void main( ) { ....................... ....................... Test= 50; if( Test>=10) { printf(“%d”,Test); } else { Test= Test+100; printf(“%d”,Test); } } 3. Find out the errors from the following program segments: a. .......................... ......................... If(x+y=p && z=1) Printf(“ ”); b. ................................ ................................ if( code>1) { a=b+c else a=0 } 4. The following is a segment of a program: X=1; Y=1; if(n>0){ X=X+1; Y=Y-1; } printf(“%d %d”,X,Y);

42

School of Science and Technology

DCSA Program

What will be the values of X and Y if n=1 and n=0.

Activity

1. Write a program to check you are either YOUNG or OLD. ….……………………………………………………………………………… .………………………………………………………………………………… 2. Write a program to find the number of and sum of all integers greater than 100 and less than 200 that are divisible by 7. …..……………………………………………………………………………… ……..……………………………………………………………………………

Summary

Summary In this lesson   

We have gathered knowledge about C control statements. Moreover we have learned that how if statement works in program. We also have understood that how if-else statement works in program.

ASSIGNMENT

Assignment

1. Mention the main differences between if and if-else statements. ……..………………………………………………………………………… ….………….………………………………………………………………… 2. Write a program to check whether a year is leap year or not. ………..……………………………………………………………………….. …………...…………………………………………………………………….

Assessment Write “T” for true and “F” for false for the following sentences Assessment

1. The if-else statement is an extension of the simple if statement. 2. if statement is a single-way decision making statement. 3. The if-else statement executes some code if the test condition is true and some other code if the test condition is false. Multiple Choice Questions (MCQ)

1. In the if-else statement, if the test condition or expression is true thena) true statements-block is executed b) false statements-block is executed c) both true and false statements are d) none of these executed

2. if statement isa) two-way decision making statement c) no way decision making statement

b) single way decision making statement d) none of these

Exercises

1. 2. 3. 4. 43

What do you mean by control statement? Differentiate between if and if-else conditional statements with an example. Explain if control statement with flowchart and an example. Explain if-else control statement with flowchart and an example.

School of Science and Technology

Lesson-3

DCSA Program

Decision Making Using Nesting of if-else Statements

Learning Outcomes

Outcomes Upon completion of this lesson you will be able to 

Explain nesting if-else statements.

Keywords

Statement, If-else, Execution, Expression, Nesting

NESTING OF IF-ELSE STATEMENTS In the previous lesson, we have seen that, the if-else statement executes only two different codes depending upon whether the test expression/condition is true or false. However, in practical, sometimes, a choice has to be made from more than two possibilities. When sequences of decisions are concerned, we may have to apply more than one if-else statement in nested form. Nested if-else statement is similar to if-else statement, where new block of if-else statement is defined in existing if or else block statement. The nested if-else statement allows us to verify for multiple test expressions and execute different codes for more than two conditions. The general structure of nesting of if-else statement is as follows: if(test expression-1) { if(test expression-2) { block of statement-1; } else { block of statement-2; } else { block of statement-3; } statement-n; The logic execution flow chart is demonstrated in figure 4.3.1.

44

School of Science and Technology

DCSA Program

Entry

Test Expression-1 ?

False

True

Test Expression-2 ?

True

False Block Statement-3

Block Statement-2

Block Statement-1

Statement-n Next Statement Figure 4.3.1: flowchart of nested if-else statements From the flowchart, we can say that, if the test expression-1 is false the block statement-3 will be executed; otherwise it continues to perform the second test expression. If the test expression-2 is true the block statement-1 will be executed; otherwise the block statement-2 will executed and then the control goes to the statement-n and so on. Nested if-else statement is similar to if-else statement, where new block of if-else statement is defined in existing if or else block statement.

Activity

1. Mention the significance of using nesting if-else by your own concept. …………………………………………………………………………………….. …………………………………………………………………………………….. 2. Write the nested if-else statements syntax with five if and three else. ……………………………………………………………………………………. …………………………………………………………………………………….

Program 4.3.1 Write a program to display largest number from three integer numbers using nested if-else statements. #include #include void main() { clrscr();

45

School of Science and Technology

DCSA Program

int num1,num2,num3; printf("Enter three integer numbers:\n "); scanf("%d %d %d",&num1,&num2,&num3); if(num1 > num2) { if(num1 > num3) { printf("Largest Number is: %d\n", num1); } else { printf("Largest number is: %d\n", num3); } } else { if(num3 > num2) { printf("Largest Number is: %d\n",num3); } else { printf("Largest Number is: %d\n",num2); } } getch(); } ………………………………………………………………………………….. Output Enter three integer numbers: 20 400 100 Largest Number is: 400 Program 4.3.2 Write a program to check username and password for login using nested if-else statements. #include #include void main() { char username; int password; clrscr(); printf("Enter Your Username:"); scanf("%c",&username); printf("Enter Your Password:"); scanf("%d",&password);

46

School of Science and Technology

DCSA Program

if(username = ='a') { if(password = =12345) { printf("Login successful"); } else { printf("Password is incorrect, Try again!!!"); } } else { printf("Username is incorrect, Try again!!!"); } getch(); } ....................................................................................................................................... Output Enter Your Username: am Enter Your Password:1234 Username is incorrect, Try again!!!" Enter Your Username: a Enter Your Password:12345 Login successful Program 4.3.3 Write a program to check monthly balance of a customer of a bank, where if customer sex is female and current balance is greater than 10000 taka, than bonus will be 10% of current balance, and if current balance is less than 10000 taka bonus will be 5%, otherwise bonus will be 2%. #include #include void main() { char sex; long int balance,bonus,mbalance; clrscr(); printf("Enter your sex:"); scanf("%c",&sex); printf("Enter your balance:"); scanf("%ld",&balance); if(sex=='F') { if(balance>10000) { bonus=balance*.10; } else { bonus=balance*.05; }

47

School of Science and Technology

DCSA Program

} else { bonus=balance*.02; } mbalance=balance+bonus; printf("Monthly Balance will be: %ld",mbalance); getch(); } ………………………………………………………………………………… Output Enter your sex: M Enter your balance: 12000 Monthly Balance will be: 12240 Enter your sex: F Enter your balance: 15000 Monthly Balance will be: 16500 1. Identify the errors form the following program segments and correct them :

Study skills

void main() { int x,y,z; x=10;y=5,z=6; if(x5) y=x++; else if(z = =6 && x=10) z=x+y; else x=x++; } printf("%d\n",&x) printf("%d\n",&y); } printf("%d\n",&z); } 2. After correction the above program what will be the output?

Summary Summary In this lesson  We have gathered knowledge about C control statements.  Moreover we have learned that how nesting if-else statement works in program.

48

School of Science and Technology

DCSA Program

ASSIGNMENT 1. Write down the benefits of nesting if-else in C program. ……..……………………………………………………………………….. ……………………………………………………………………………… Assignment

2. Determine the roots of the quadratic equation 𝑎𝑥 2 + 𝑏𝑥 + 𝑐 = 0 using the well known quadratic formula: −𝑏 ± √(𝑏 2 − 4𝑎𝑐) 𝑥= 2𝑎

Assessment Write “T” for true and “F” for false for the following sentences Assessment

1. When sequences of decisions are concerned, we may have to apply more than one if-else statement in nested form.

2. Nested if-else statement allows us to verify for multiple test expressions. Exercises

1. 2. 3. 4.

49

Define nesting if-else statements. What are the benefits of using nesting if-else statements? Draw and explain the flow graph of nesting if-else statements. Write a C program to determine maximum and minimum number from three integer numbers using nesting if-else statements.

School of Science and Technology

Lesson-4

DCSA Program

Decision Making Using else-if Ladder Statements

Learning Outcomes

Outcomes Upon completion of this lesson you will be able to 

Explain else-if ladder statements.



Explain else-if ladder general syntax.



Explain else-if ladder flowchart.

Keywords

Statement, If-else ladder, Execution, Flowchart

ELSE-IF LADDER STATEMENTS In practical, when we need to test different conditions with different statements, where multipath decisions are involved, this is called else-if ladder. Actually multipath decision is a sequence of ifs in which the statements related with each else is an if. If-else ladder statement is used to test set of conditions in sequence that is if we have different test conditions with different statements then we need else-if ladder statements. The general syntax of if-else ladder is as follows: if (test_condition-1) { statement-1; } else if(test_condition-2) { statement-2; } else if(test_condition-3) { statement-3; } else if(test_condition-4) { statement-4; } ……………… else if(test_condition-n) { statement-n; } else { default-statement; } Statement-X;

50

School of Science and Technology

DCSA Program

The above construction is known as if-else ladder. Here, the conditions are evaluated from top to bottom. As soon as when a test condition is true, then the statement(s) associated with it is executed and the programming control is transferred to the statement-X. When all conditions are failed or false then the final else containing the default-statement will be executed. The flowchart of if-else ladder is shown in bellow: Input Entry

Test Condition-1

False

True Test Condition-2

Statement-1

False

True Test Condition-3

Statement-2

True Statement-3

False

Test Condition-n

False

Statement-n Default statement

Statement-X Figure 4.4.1: Flowchart of if-else ladder If-else ladder statement is used to test set of conditions in sequence that is if we have different test conditions with different statements then we need else-if ladder statements

51

School of Science and Technology

DCSA Program

Program 4.4.1 Assume an example of grading system of the students in an institution. The grading is done according to the following rules: Obtained marks Grade Obtained marks Grade 80 to 100 A+ 55 to less than 60 B 75 to less than 80 A50 to less than 55 C+ 70 to less than 75 A 45 to less than 50 C 65 to less than 70 B+ 40 to less than 45 D 60 to less than 65 BLess than 40 F Now write a C program to Calculate students’ grade using if–else ladder concept. #include #include void main() { int marks; printf("Enter your Marks:"); scanf("%d",&marks); if(marks>100) { printf("\nInvalid Marks. Marks must be less than 100"); } else { if(marks=80) { printf("Your Grade is A+"); } else if(marks=75) { printf("Your Grade is A-"); } else if(marks=70) { printf("Your Grade is A"); } else if(marks=65) { printf("Your Grade is B+"); } else if(marks=60) { printf("Your Grade is B-"); } else if(marks=55) { printf("Your Grade is B"); } else if(marks=50) { printf("Your Grade is C+"); } else if(marks=45) {

52

School of Science and Technology

DCSA Program

printf("Your Grade is C"); } else if(marks=40) { printf("Your Grade is D"); } else { printf("Your Grade is F"); } } getch(); } ………………………………………………………………………………. Output Enter your Marks: 78 Your Grade is AEnter your Marks: 120 Invalid Marks. Marks must be less than or equal 100

Program 4.4.2 Assume that DESCO power distribution company charges its domestic customers as follows: Consumption Units Rate of charge Consumption Units Rate of charge 0-100 1.00 taka per unit 401-500 3.50 taka per unit 101-200 1.50 taka per unit 501-600 4.70 taka per unit 201-300 2.00 taka per unit 601-700 5.00 taka per unit 301-400 2.75 taka per unit 701 or above 8.50 taka per unit Now write a C program that reads power consumed unit and prints the amount to be paid by the customer. #include #include void main() { int units; float pa_amount; printf("Enter Consumed Units:"); scanf("%d",&units); if(units>701) { pa_amount=units*8.50; printf("\n Customer Total Payable amount is: %f Taka",pa_amount); } else { if(units=0) { pa_amount=units*1.00; printf("\n Customer Total Payable amount is: %f Taka",pa_amount); } else if(units=101) {

53

School of Science and Technology

DCSA Program

pa_amount=units*1.50; printf("\n Customer Total Payable amount is: %f Taka",pa_amount); } else if(units=201) { pa_amount=units*2.00; printf("\n Customer Total Payable amount is: %f } else if(units=301) { pa_amount=units*2.75; printf("\n Customer Total Payable amount is: %f } else if(units=401) { pa_amount=units*3.50; printf("\n Customer Total Payable amount is: %f } else if(units=501) { pa_amount=units*4.70; printf("\n Customer Total Payable amount is: %f } else if(units=601) { pa_amount=units*5.00; printf("\n Customer Total Payable amount is: %f }

Taka",pa_amount);

Taka",pa_amount);

Taka",pa_amount);

Taka",pa_amount);

Taka",pa_amount);

else { printf("Illigible Customer!!!!!"); } } getch(); } ………………………………………………………………………………….. Output Enter Consumed Units:800 Customer Total Payable amount is: 6800.00000 Taka Enter Consumed Units:300 Customer Total Payable amount is: 600.00000 Taka

Activity

1. Mention the significance of using if-else ladder statement by your own concept. ……………………………………………………………………………….. ……………………………………………………………………..………… 2. Write the if-else ladder statement syntax with 10 conditions. …………………………….………….………………………………………. ………..…………………………….…………………………………………

54

School of Science and Technology

DCSA Program

Summary Summary In this lesson  We have gathered knowledge about C control statements.  Moreover we have learned that how if-else ladder statement works in program.  We also have understood that how if-else ladder flowchart works in program. ASSIGNMENT 1. Suppose A Firm has 100 employee. The basic salary range and house rent and bonus of different categories employees are given bellow:

Assignment

Basic salary Greater than 40000 30000 to less than 40000 20000 to less than 30000 10000 to less than 20000 Less than 10000

House rent 35% of basic salary 40% of basic salary 45% of basic salary 50% of basic salary 55% of basic salary

Bonus 20% of basic salary 15% of basic salary 12% of basic salary 10% of basic salary 8% of basic salary

Now write a C program to calculate total salary of an employee, where total salary is the sum of basic salary, house rent and bonus. Assessment Write “T” for true and “F” for false for the following sentences Assessment

1. If-else ladder statement is used to test set of conditions in sequence. 2. When all conditions are failed or false then the final else containing the default-statement will not be executed.

Exercises 1. What are the benefits of using nesting if-else ladder statements? 2. Draw and explain the flow graph of if-else ladder statements.

55

School of Science and Technology

DCSA Program

Decision Making Using Switch Case Statement

Lesson-5 Learning Outcomes

Outcomes Upon completion of this lesson you will be able to 

Explain switch case statement.



Explain switch case general syntax.



Explain switch case flowchart. Keywords

Statement, Switch, Case, Execution, Expression, Flowchart

SWITCH CASE STATEMENT In previous lesson we have seen that the nested if-else statement allows us to execute a block of statements or code among many conditions or alternatives. If we are checking on the value of a single variable in nested if –else statement, in this situation it is better to use switch case statement. It is frequently faster than nested if-else but not always. Fortunately, C has built-in multi-way decision statement known as switch statement. A switch statement tests the value of a given variable or expression against a list of case values. In this statement, when case is matched or found then block of statements associated with that case is executed. This type of statement is mostly used when we have number of options or choices or cases and we may need to perform a different task for each choice or case. The general syntax of switch case statement is as follows: switch (variable or expression) { case Constant-1: block-code-1; break; case Constant-2: block-code-2; break; case Constant-3: block-code-3; break; …………………………… …………………………… case Constant-n: block-code-n; break; default: default block; break; }

56

School of Science and Technology

DCSA Program

Statement-X; In the above syntax, the expression is an integer expression or characters. Constant-1, Constant-2, Constant-3…. Constant-n are known as case labels. Here, each of these values must be unique within switch statement and bock-code-1, bock-code-2, bock-code-3… bock-code-n are statement lists. When switch is executed the variable or value of the expression is successively compared against the cases. If a case is found or matched with the value of the expression, then the associated block code or statement(s) are executed. The break statement at the end of the each block code means the end of specific case and causes an exit from the switch statement, and for that reason, transfers program control to statement-X. If the break statement is missed from any case, then program executes all statements until get break statement from another case. The default is optional. When variable or value of expression does not match with any of the case values then default statement(s) are executed. Input Entry

Switch Expression Case Constant-1 Block-code-1 Case Constant-2 Block-code-2

No match default Default block Statement-X Figure 4.5.1: Flowchart of switch case statement A switch statement tests the value of a given variable or expression against a list of case values. When case is matched or found then block of statements associated with that case is executed.

Activity

1. Mention the significance of using switch case statement by your own concept. …………………………………………………………………………………….. …………………………………………………………………………………….. 2. Write the switch case syntax with 10 cases. ……………………………………………..……………………………………… ……………………………………………..………………………………………

57

School of Science and Technology

DCSA Program

Program 4.5.1 Assume an example of grading system of the students in an institution. The grading is done according to the following rules: Obtained marks Grade Obtained marks Grade 80 to 100 A+ 50 to less than 60 C 70 to less than 80 A40 to less than 50 D 60 to less than 70 B Less than 40 F Now write a C program to Calculate students’ grade using Switch case concept. #include #include void main() { int marks, value; printf("Enter the marks: "); scanf("%d",&marks); value =marks/10; switch(value) { case 10: case 9: case 8: printf("Well done Your grade is A+");break; case 7: printf("Well done Your grade is A-");break; case 6: printf("Well done Your grade is B");break; case 5: printf("Well done Your grade is C"); break; case 4: printf("Well done Your grade is D");break; default: printf("Sorry Your grade is F!!"); } getch(); } ………………………………………………………………………………….. Output Enter the marks: 95 Well done Your grade is A+ Enter the marks: 66 Well done Your grade is B Enter the marks: 33 Sorry Your grade is F!!"

58

School of Science and Technology

DCSA Program

Summary Summary In this lesson  We have gathered knowledge about basic idea about switc case statement.  Moreover we have learned that how switch case statement works in program. ASSIGNMENT

Assignment

Suppose A Firm has 100 employee. The basic salary range and house rent and bonus of different categories employees are given bellow: Basic salary House rent Bonus Greater than 40000 35% of basic salary 20% of basic salary 30000 to less than 40000 40% of basic salary 15% of basic salary 20000 to less than 30000 45% of basic salary 12% of basic salary 10000 to less than 20000 50% of basic salary 10% of basic salary Less than 10000 55% of basic salary 8% of basic salary Now write a C program to calculate total salary of an employee, where total salary is the sum of basic salary, house rent and bonus using switch case statement.

Assessment Fill in the blanks with appropriate word Assessment

1. C has built-in …………. decision statement known as………… statement. 2. When switch is executed the ……………….. is successively compared against the cases. 3. In switch case statement the …………… is optional. 4. A ……….statement tests the value of a given…………….against a list of case values.

Exercises

1. 2. 3. 4.

59

What is switch in C program? Why is switch case statement used in C program? Draw and explain the flowchart of switch case statement. Briefly explain the general syntax of Switch case statement. In what ways does a switch statement differ from an if statement?

School of Science and Technology

DCSA Program

Decision Making and Looping Unit 5

INTRODUCTION

In the previous lessons we have learned about the programming structure, decision making procedure, how to write statements, as well as different types of decision or conditional statements and some basic control statement based program. In this unit we will learn about definition of loop, declaration and initialization of loop, various types of loop in C program and its applications and also how to handle loops in program. In C programming language loop is very useful statement. Timeframe We expect that this unit will take maximum 10 hours to complete. How long ?

Unit Structure Lesson- 1 : Basic concept on loop control structures Lesson- 2 : Understanding while loops Lesson- 3 : Understanding do-while loops Lesson- 4 : Understanding for loop Lesson- 5 : Understanding break and continue statements Lesson- 6 : Understanding goto statement

60

School of Science and Technology

Lesson-1

DCSA Program

Basic Concept On Loop Control Structures

Learning Outcomes

Outcomes Upon completion of this lesson you will be able to 

Define programming loop.



Understand the loop control structures.



Explain uses of loop in program.

Keywords

Program, Loop, Control Structure, Entry, Exit

INTRODUCTION TO LOOP In practical, we may encounter many circumstances, when a block of code needs to be executed several number of times. We have already learned that in program, statements are executed sequentially. The first statement is executed first, followed by the second, third and so on. C language provides various control structures that allow for more complicated execution paths. In programming, a loop is a sequence or arrangement of instruction(s) that is continually repeated until a certain condition is reached. In looping, a sequence of statements are executed until some conditions for end of the loop are satisfied. It is a necessary idea that is commonly used in writing programs. A loop statement permits us to execute a statement or group of statements several times. A program loop contains two sections, such as (1) body of the loop and (2) control statement. The control statement tests definite conditions and then guides the repeated execution of the statements checked in the body of the loop. A loop is a sequence or arrangement of instruction(s) that is continually repeated until a certain condition is reached.

LOOP CONTROL STRUCTURES A loop control structure may be classified either as the entry-controlled loop or as the exit-controlled loop. Both control structures are described in the following sections. Entry-controlled loop In the entry-controlled loop, the control conditions are tested before the start of the loop execution. It the conditions are not satisfied, then the body of the loop will not be executed. The flowchart of entrycontrolled loop is shown in below:

61

School of Science and Technology

DCSA Program

Input Entry

Test Condition

False

Running True Body of the loop

Figure 5.1.1: Entry-controlled loop structure Exit-controlled loop In the exit-controlled loop, the control conditions are tested at the end of the body of the loop. As result the body is executed unconditionally for the first time. The flowchart of exit-controlled loop is shown in below: Input Entry

Body of the loop

True Test Condition

False Figure 5.1.2: Exit-controlled loop structure A loop control structure may be classified either as the entry-controlled loop or as the exit-controlled loop.

LOOPING PROCESS Usually in a looping process, would include the subsequent four steps: 1. 2. 3. 4.

Setting and initialization of a counter variable. Execution of the statements in the loop. Test for a specified conditions for execution. Increment or decrement the counter variable.

62

School of Science and Technology

DCSA Program

The programming C language provides three loops for performing loop operation, which are as follows: (i) while loop, (ii) do-while loop, and (iii) for loop. We will briefly describe above loops in the later lessons one by one.

Activity

1. Mention the significance of using loop in C language by your own concept. ……………………………….…………………………………………………….. ……………………………………………………………………………………... …………………………..………………………………………………………….

Summary Summary In this lesson

 We have learned about C loop control structure.  Moreover we have learned how to design entry-controlled and exit-controlled loop structure flow chart. Assessment

Assessment

Fill in the blanks 1. A loop is a …………instruction(s). 2. A loop statement ……….. us to execute a statement or …………. several times. Multiple Choice Questions (MCQ) 1. a loop is a sequence or arrangement of a) Variables b) Constants c) Instructions d) None of these 2. In looping, a sequence of statements are executed untila) Some conditions for end of the b) Only one conditions for end of loop are satisfied the loop are satisfied c) Some variables for end of the d) None of these loop are satisfied 3. In the entry-controlled loop, the control conditions are tested a) Before the start of the loop execution b) After the start of the loop execution c) Middle of the loop execution d) End of the loop execution 4. In the exit-controlled loop, the control conditions are tested a) At the end of the body of the loop b) After the start of the loop execution c) Before the start of the loop execution d) None of these

Exercises 1. What is loop? Mention the major benefit of using loop in programming language. 2. Explain the loop control structures with flowchart. 3. Mention the looping process steps.

63

School of Science and Technology

Lesson-2

DCSA Program

Understanding While Loop

Learning Outcomes

Outcomes Upon completion of this lesson you will be able to 

Define the while loop.



Explain the while loop with syntax.



Explain the while loop flowchart and example.

Keywords

Program, Loop, While loop, Syntax, Flowchart

THE WHILE LOOP We have already learned that loops are used in programming to repeat a specific block until some end condition is met. While loop is simple loop in C. A while loop in C programming repeatedly executes a target statement as long as a given condition is true. The basic form or syntax of while loop is as follows: while( Test-condition) { Body of the loop or statement(s); } Here, body of the loop or statement(s) may be a single statement or a block of statements. The Testcondition may be any expression, and true is any nonzero value. The while loop is an entry-controlled loop.The Test-condition is evaluated and if the condition is true then the body of the loop or statements Input Entry

Test Condition

False

True Body of the loop

Figure 5.2.1: Flowchart of while loop

64

School of Science and Technology

DCSA Program

are executed. After execution of the body of the loop, the Test-condition is once again evaluated and it is true, the body of the loop is executed again. This process is repeated until the Test-condition finally becomes false and the programs control is transferred out of the loop. Finally we can say that, in while loop Test-condition is tested before the body of the loop is executed. The flowchart of while loop is shown in figure 5.2.1. Here, the important point is noted that a while loop might not execute at all, when the Test-condition is tested and the result is false, body of the loop will be skipped and the next statement after the while loop will be executed. A while loop in C programming repeatedly executes a target statement as long as a given condition is true.

Program 5.2.1 write a C program that prints 10 to 15 using while loop #include #include void main () { int a = 10; while( a 0) { factorial = factorial * number; --number; } printf("Factorial value is = %ld", factorial);

65

School of Science and Technology

DCSA Program

} …………………………………………………………………………….………. Output Enter an integer Number: 6 Factorial value is = 720 Enter an integer Number: 10 Factorial value is = 3628800 Program 5.2.3 write a C program that prints only odd numbers from 1 to 30 using while loop #include #include void main () { int a = 1; printf("Odd Numbers Till 30 are: \n"); while( a < 30 ) { printf("%d \t", a); a+=2; } getch(); } …………….……………………………………………………………….. Output 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29

A while loop might not execute at all, when the Test-condition is tested and the result is false, body of the loop will be skipped and the next statement after the while loop will be executed.

Activity

1. What will be the output of the following code segment #include #include void main () { int p = 5; while( p >20 ) { printf("value of a: %d\n", p); p++; } printf(" Hello Good day!!"); } 2. Find out errors from the following code segment void main () { int p = 5; while p =5 ; { printf("%d\n", a); p; }printf(" Hello Good day!!"); }

66

School of Science and Technology

DCSA Program

Summary Summary In this lesson

 We have learned about C while loop with its syntax.  We have also learned how a while loop works in program. ASSIGNMENT

Assignment

1. Write a C program that find out the odd and even numbers from N integer numbers using while loop. …………………………………………………………………………………… ………………………..………………………………………………………….. 2. Write a C program to print the result of the equation yx using while loop. …………………………………………………………………………………… …………………………………………………………………………………….

Assessment

Assessment

Write “T” for true and “F” for false the following sentences: 1. A while loop in C programming repeatedly executes a target statement as long as a given condition is false. 2. In while loop Test-condition finally becomes true and the programs control is transferred out of the loop. Multiple Choice Questions (MCQ) 1. In while loop body of the loop or statement(s) may be a) A single statement or a block of b) Only single statements statements c) Only two blocks d) None of these 2. A while loop in C programming repeatedly executes a target statement as long as a given a) Condition is true. b) Condition is false c) Both true and false is possible d) None of these 3. In while loop when the Test-condition is tested and the result is false, body of the loop will bea) Printed b) Terminated c) Executed d) Skipped

Exercises 1. What is while loop? Mention the major benefit of using while loop in programming language. 2. Explain the while loop control structures with flowchart. 3. Write a C program to calculates the power value of equation P=2N using while loop. 4. Write a C program to find out the value of following series using while loop: Y= 11+23+35+………………………………….Nn

67

School of Science and Technology

Lesson-3

DCSA Program

Understanding Do-While Loop

Learning Outcomes

Outcomes Upon completion of this lesson you will be able to 

Define do-while loop.



Explain the do-while loop with syntax.



Explain the do-while loop flowchart and example.

Keywords

Program, Loop, Do-while loop, Syntax, Flowchart

THE DO-WHILE LOOP We have learned that, in while loop a Test-condition is tested before body of the loop is executed. Consequently, if the Test condition is not satisfied at the first time, then the body of the loop may not be executed at all. But in some situations it might be necessary to execute the body of the loop or statement(s) before the test is executed. Such circumstances can be handled with the help of do-while loop. The general syntax of do-while loop is as follows: do { Body of the loop or statement(s); }while(Test-condition); In do-while loop, the program proceeds to evaluate the body of the loop or statement(s) first. In this loop, the Test-condition in while statement is evaluated at the end of the loop. Input Entry

Body of the loop

True

Test Condition

False

Figure 5.3.1: Flowchart of do-while loop If the Test-condition is true, the program continues to evaluate the body of the loop once again. This process continues as along as the Test-condition is true. If the Test-condition is false, the loop will be

68

School of Science and Technology

DCSA Program

terminated and program control goes to the statement that appears after while statement A do...while loop is similar to a while loop, but the point that it is exit-controlled loop and therefore the body of the loop is always executed at least one time. The flowchart of do-while loop is shown in figure 5.3.1. In do-while loop, the program proceeds to evaluate the body of the loop or statement(s) first. In this loop, the Test-condition in while statement is evaluated at the end of the loop Program 5.3.1 Write a program to calculate the average of N numbers and display the result using do-while loop. #include #include void main () { int number, count =1; float x, average, sum = 0.0; printf("How Many Numbers?:"); scanf("%d",&number); do { printf(" Enter the %d Number = ",count); scanf("%f",&x); sum = sum + x; ++count; }while(count < = number); average = sum/number; printf("\n The average is: %f",average); getch(); } ……………………………………………………………………………. Output How Many Numbers?: 3 Enter the 1 Number =10 Enter the 2 Number =20 Enter the 3 Number =30 The average is: 20.000000

Program 5.3.2 Write a C program that convert a line of lowercase text to Uppercase text using do-while loop. #include #include #include #define EOL '\n' void main () { char letter[80]; int value,count=-1; printf("Type text or line as lowercase:\n"); do { ++count;

69

School of Science and Technology

DCSA Program

}while((letter[count] = getchar())!= EOL); value = count; count=0; do { putchar(toupper(letter[count])); ++count; }while(count < value); getch(); } ……………………………………………………………………………… Output Type text or line as lowercase: i am a man. i read in bangladesh open university I AM A MAN. I READ IN BANGLADESH OPEN UNIVERSITY

Program 5.3.3 Write a C program that print the multiplication table of 5 from 1 to 10 using dowhile loop. #include #include void main() { int value=1; printf("Multiplication Table of 5 from 1 to 10:\n"); do { printf("5 * %d = %d\n",value,5*value); value++; }while(value p2 p1= = p2 and p1! = p2 are valid expressions. But we cannot use pointers in division or multiplication. For instance, following expressions such as p1/p2; p1*p2; p1/3; etc are not valid statements. Program 9.3.2 Write a program to illustrate the use of pointers in arithmetic operations. #include#include void main() { int A,B,*p1,*p2,x,y,z; A=20;B=10;p1=&A;p2=&B; x=*p1 * *p2-5; y=((10* (-(*p2)))/(*p1))+30; printf(“value of A = %d, and B = %d\n”,A,B); printf(“value of x = %d, and y= %d\n”, x,y);

189

School of Science and Technology

DCSA Program

*p2 = *p2+10; *p1 =*p2-3;z = *p1 * *p2-5; printf(“value of A = %d,and B = %d\n”, A,B);printf(“ value of z = %d\n”,z); getch(); } ………………………………………………………..……………………………………. Output value of A = 20, and B = 10 value of x = 195, and y= 25 value of A = 17, and B = 20 value of z =335

Study skills

1. Describe what is wrong in the following pointer declaration: void main(){ int x,y,p1p2;p1=&x; p2=*p2; } 2. Find the error(s) from the following code segments: void main(){ int *p1,*p2, x,y,z,mul,sum; x=p1-p2; y=p2/10; sum=sum+p2;mul=mul*p2; p2=&*x;z=*p1 + *p2++; }

Summary Summary In this lesson we have  Learned how variables are accessed by pointer.  Also understood how pointers are used in program and understood pointer expression. ASSIGNMENT 1. Write a program to determine the summation of three integers values using pointers ………………………………………………………………………………….. ……….…………………………………………………………………………. Assignment Assessment Write ‘T’ for true and ‘F’ for false for the following statements Assessment

1. Accessing a variable through the pointer we should follow three steps. 2. Like other variables, pointer variables can be used in expressions. 3. We cannot use pointers in division or multiplication.

Exercises

1. Explain how variables are accessed using pointer. 2. Write a program that determines summation, subtraction, multiplication and division using pointer variable.

190

School of Science and Technology

DCSA Program

UNITS TRUE / FALSE ANSWER Unit 4 :

Unit 6 : Unit 7:

Unit 9:

Lesson 2 : Lesson 3 : Lesson 4 : Lesson 5 : Lesson 1 : Lesson 7 : Lesson 8 : Lesson 9 : Lesson 2 : Lesson 3 :

1T, 2 F, 3T 1T, 2 T 1T, 2 F 1F, 2T, 3T, 4T 1T, 2T, 3T, 4F 1T, 2T, 4F 1F, 2T, 3T, 4F, 5F, 6T, 7T 1F, 2F, 3F, 4T, 5T 1T, 2T, 3F 1T, 2T, 3T UNITS MCQ ANSWER

Unit 1 : Unit 2 : Unit 3 : Unit 4 : Unit 6 : Unit 7 :

Unit 8 : Unit 9 :

191

Lesson 4 : Lesson 4 : Lesson 2 : Lesson 1 : Lesson 2 : Lesson 5 : Lesson 1 : Lesson 2 : Lesson 4 : Lesson 5 : Lesson 6 : Lesson 7 : Lesson 8 : Lesson 9 : Lesson 1 : Lesson 2 : Lesson 1 : Lesson 2 :

1 a, 2 b, 3 a, 4 b, 5 b 1 d, 2 c 1 c, 2 a, 3 a 1 c, 2 a 1 a, 2 a 1 a, 2 a, 3 c, 4 b 1 c, 2 a, 3 b, 4 a 1 a, 2 c 1 a, 2 b 1 a, 2 c 1 c, 2 d, 3 a, 4a 1 a, 2 c 1 b, 2 a, 3 c, 4 a 1 a, 2 a, 3 b, 4 c, 5 a 1 a, 2 b, 3 c, 4d 1 b, 2 d, 3 b, 4 a 1 a, 2 a, 3 b, 4 a, 5 a 1 a, 2 b, 3d