0% found this document useful (0 votes)
4 views

Module2 POPC

Chapter 9 of 'Principles of Programming Using C' introduces input/output statements in C, explaining streams, formatting functions like printf() and scanf(), and their syntax. It details how printf() displays information and formats output, while scanf() reads formatted data from the keyboard and stores it in variables. The chapter also covers operators in C, including arithmetic, relational, equality, and logical operators, along with their usage and examples.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Module2 POPC

Chapter 9 of 'Principles of Programming Using C' introduces input/output statements in C, explaining streams, formatting functions like printf() and scanf(), and their syntax. It details how printf() displays information and formats output, while scanf() reads formatted data from the keyboard and stores it in variables. The chapter also covers operators in C, including arithmetic, relational, equality, and logical operators, along with their usage and examples.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Principles of Programming Using C BPOPS103

Chapter 9
Introduction to C

9.14 Input/Output Statement in C:


9.14.1 Streams:
• A stream acts in two ways. It is the source of data as well as the destination of data.
• C programs input data and output data from a stream. Streams are associated with a physical
device such as the monitor or with a file stored on the secondary memory.
• In a text stream, sequence of characters is divided into lines with each line being terminated
with a newline character (\n). On the other hand, a binary stream contains data values using
their memory representation.
• Although, we can do input/output from the keyboard/monitor or from any file but in this
chapter we will assume that the source of data is the keyboard and destination of the data
is the monitor.

9.14.2 Formatting Input/Output:

• C programming supports two formatting functions printf() and scanf().


1. printf() → used to convert data stored in the program into text stream.
2. sacnf() → used to convert the text stream coming from keyboard to data values and
stores them in program variables.
9.14.3 printf() [Output Statement]:
• The printf function (stands for print formatting) is used to display information
required by the user and also prints the values of the variables.
• The printf function takes data values, converts them to a text stream using
formatting specifications in the control string and passes the resulting text stream
to the standard output.

BIT, Bangalore-04 Page 1


Principles of Programming Using C BPOPS103

• The syntax of printf() is as given below:


printf ("control string", variable list);
Control String: C string that contains the text that has to be written on to the
standard output device. As part of control string printf() the function can have as
many additional arguments (known as format specifiers) as specified in the
prototype.
The prototype of the control string can be given as follows.
%[flags][width][.precision][length modifier] type specifier
Note: Each control string must begin with a % sign, which specifies how the next
variable has be printed.
i. Flag: An optional argument which specifies output justification such as
numerical sign, trailing zeros or octal, decimal, or hexadecimal prefixes.
Flags used in C program

ii. Width: An optional argument which specifies the minimum number of


positions in the output. If data needs more space than specified, then printf
overrides the width specified by the user, and if the number of output
characters is smaller than the specified width, then the output would be right
justified with blank spaces to the left.
iii. Precision: An optional argument which specifies the maximum number of
characters to print.
Note: For floating point numbers, the precision flag specifies the number of
decimal places to be printed.
Format can be given as .m, where m specifies the number of decimal digits.
When no precision modifier is specified, printf prints six decimal positions.
When both width and precision fields are used, width must be large enough
to contain the integral value and the decimal point of a number.
Ex: %7.3f means print a floating point value of maximum 7 digits where 3
digits are allotted for the digits after the decimal point.
iv. Length Modifier:

BIT, Bangalore-04 Page 2


Principles of Programming Using C BPOPS103

v. Type specifiers: They are used to define the type and the interpretation of
the value of the corresponding argument.

BIT, Bangalore-04 Page 3


Principles of Programming Using C BPOPS103

BIT, Bangalore-04 Page 4


Principles of Programming Using C BPOPS103

Note: The minimum field width and precision specifiers are usually constants. However,
they may also be provided by arguments to printf(). This is done by using the * modifier
as shown in the printf statement below.
printf("%*.*#", 10, 4, 1234.34);
Here, the minimum field width is 10, the precision is 4, and the value to be displayed is
1234.34
Examples:
float a=98.765432;
printf(“\n %7.4f \n %7.2f \n %-7.2f \n %f \n %10.2e \n %11.4e \n %-10.2e \n
%e”, a, a, a, a, a, a, a, a);

BIT, Bangalore-04 Page 5


Principles of Programming Using C BPOPS103

Output:
98.7654
98.77
98.77
98.7654
9.88e+01
9.8765e+01
9.88e+01
9.876540e+0
char ch = ‘A’;
printf(“\n %c \n %3c \n %5c", ch, ch, ch);
Output:
A
A
A
printf(“\n This is \’so\’ beautiful”);
O/P: This is ‘so’ beautiful
printf(“\n a = |%-+7.2f| b = %07.2f c = %-0+8.2f", 1.2, 1.2, 1.2);
O/P: a= +1.20 b = 0001.20 c = 1.20

9.14.4 scanf() [Input statement]:


• The scanf() function stands for scan formatting and is used to read formatted data from the
keyboard.
• The scanf function takes a text stream from the keyboard, extracts and formats data from
the stream according to a format control string and then stores the data in specified program
variables,
• The syntax of the scanf() function can be given as:
scanf("control string", argl, arg2, arg3,……., argn);
Control string specifies the type and format of the data that has to be obtained from the
keyboard and stored in the memory locations pointed by arguments arg1, arg2,.., argn, i.e,,
the arguments are actually the variable addresses where each piece of data is to be stored.
The prototype of the control string can be given as:
%[*] [width] [modifier]type
Here * is an optional argument that suppresses assignment of the input field, ic., it indicates
that data should be read from the stream but ignored (not stored in memory location).
i. Width: an optional argument that specifies the maximum number of characters to
be read.
ii. Modifier: An optional argument that can be h, 1, or L for the data pointed by the
corresponding additional arguments. Modifier h is used for short int or unsigned
short int, l is used for long int, unsigned long int, or double values, Finally, L is
used for long double data values.
iii. Type: Specifies the type of data that has to be read. It als6 indicates how this data
is expected to be read from the user.
Note: a) The scan function ignores any blank spaces, tabs, and newlines entered by the user.
b) The function simply returns the number of input fields successfully scanned and
stored.

BIT, Bangalore-04 Page 6


Principles of Programming Using C BPOPS103

c) The address of the variable is denoted by an *&’ sign followed by the name of the
variable.
The rules to use a scanf function in C programs.
Rule 1: The scanf function works until
(a) the maximum number of characters has been processed,
(b) a white space character is encountered, or
(c) an error is detected.
Rule 2: Every variable that has to be processed must have a conversion specification associated
with it. Therefore, the following scanf statement will generate an error as num3 has no
conversion specification associated with it
scanf(“%d %d", &num1, &num2, &num3);
Rule 3: There must be a variable address for each conversion specification. Therefore, the
following scan statement will generate an error as no variable address is given for the third
conversion specification.
scanf("%d %d %d", &num1, &num2);
Rule 4: An error will be generated if the format string is ended with a white space character.
Rule 5: The data entered by the user must match the character specified in the control string
(except white space or a conversion specification), otherwise an error will be generated and
scanf will stop its processing.
Rule 6: Input data values must be separated by spaces.
Rule 7: Any unread data value will be considered as a part of the data input in the next call to
scanf.
Rule 8: When the field width specifier is used, it should be large enough to contain the input
data size.

BIT, Bangalore-04 Page 7


Principles of Programming Using C BPOPS103

Example-3:
Char ch;
scanf(%ch ", &ch); -> reads a single character

char str[10];
scanf("%s ", str); -> reads a string of length 10

The below table shows the scanf format codes commonly used:

Example:
The following code combines reading of variables of different data types in one single
statement
int num;
float frum;
char ch;
char str[10];
scanf ("%d %f %e %s", &num, &fnum, &ch, str);
The statement ignores the character variable and does not store it (as it is preceded by *)
scanf("%d %f %*c %s", &num, &fnum, &ch, str);

9.14.6 Detecting error during data input:


• When the scanf function completes reading all the data values, it returns the number of
values that are successfully read.
• This return value can be used to determine whether there was any error while reading the
input.
For example, the statement,
scanf("%d %f %c", &a, &b, &c); will return 3 if the user enters, say,
> 12 12.34 A

BIT, Bangalore-04 Page 8


Principles of Programming Using C BPOPS103

It will return 1 if the user enters erroneous data like


> 12 ABC 12.34
This is because a string was entered while the user was expecting a floating point value. So,
the scanf function reads only first data value correctly and then terminates as soon as it
encounters a mismatch between the type of data expected and the type of data entered.

9.15 Operators in C
An operator is a symbol that tells the compiler to perform specific mathematical, logical or
relational operations to be performed. The different operators supported in ‘C’ are:
1. Arithmetic Operators
2. Relational Operators
3. Equality Operators
4. Logical Operators
5. Unary Operators
6. Increment and Decrement
7. Conditional Operators
8. Bitwise Operators
9. Assignment Operators
10. Comma operators
11. sizeof operators.

1. Arithmetic Operators:
➢ The operators that are used to perform arithmetic operations such as addition,
subtraction, multiplication, division and modulus operations are called
Arithmetic operators.
➢ These operators perform operations on two operands and hence they are binary
operators.
consider three variables declared as
int a=9, b=3, result;
a and b on which the operator is applied are called operands. Arithmetic operators can
be any integer or floating point number.
The different arithmetic operators are:
Operator Name Result Syntax Example (b=5, c=2)
+ Addition Sum a=b+c a=7
- Subtraction Difference a=b-c a=3
* Multiplication Product a=b*c a = 10
/ Division Quotient a=b/c a=2
% Modulus Remainder a=b%c a=1

➢ The modulus operator(%) finds the remainder of an integer division.


This operator can be applied only to the integer operands and cannot be used
for float or double operands.
➢ While performing modulo division, the sign of the result is always the sign of

BIT, Bangalore-04 Page 9


Principles of Programming Using C BPOPS103

first operand(the dividend).


16%3=1 16%-3=1 -16%3=-1 -16%-3=-1
➢ All the arithmetic operators bind from left to right. The multiplication,
division and modulus operators have higher precedence over addition and
subtraction.
➢ BODMAS rule is followed to evaluate the expression Brackets, Orders,
Division, Multiplication, Addition and Subtraction.
3+4*7
=3+28
31
➢ Arithmetic Expression:
o An expression is a sequence of operands and operators which when
evaluated results in a single value.
o The expressions consisting of only arithmetic operators such as +,-,*, / and
% are called arithmetic expressions.
o The two types of arithmetic expressions are
▪ Additive Expressions: In an expression, if addition or subtraction
operations are performed, then the expression is called additive
expression. Ex: a+b, a-b.
▪ Multiplicative Expressions: in an expression, if multiplication, division
and modulus operations are performed, then the expression is called
multiplicative expression. Ex: a*b, a/b, a%b
2. Relational Operators:
➢ We often compare two quantities and depending on their relation take
certain decisions. For example, we might compare the age of two persons,
or the price of two items, and so on. These comparisons can be done with
the help of relational operators.
➢ These operators are also known as comparison operator.
➢ The output will be either 0 (False) or 1 (True).
➢ For example
a>b //If a is greater than b, then a>b returns 1 else a>b returns 0.
➢ The expression containing a relational operator is returned as a relational
expression.
➢ The 2 operands may be constants, variables or expressions.

Operator Name Syntax Example (b=5, c=2)


< Lesser than a=b<c a = 0 (False)
> Greater than a=b>c a = 1 (True)
<= Lesser than or Equal to a = b <= c a = 0 (False)
>= Greater than or Equal to a = b >= c a = 1 (True)
== Equal to a = b == c a = 0 (False)
!= Not equal to a = b != c a = 1 (True)

BIT, Bangalore-04 Page 10


Principles of Programming Using C BPOPS103

A program to illustrate the use of relational operators is as given below,


#include<stdio.h>
void main()
{
int a=50, b=10;
if(a>b) /*Condition to check if 50 is greater than 10*/
{
printf(“a is greater than b”);
}
}
Output:
a is greater than b
3. Equality Operators:
➢ C supports two kinds of equality operators to compare their operands for strict
equality or inequality.
➢ They are equal to(= =) and not equal to(!=) operators.
➢ The equality operators have lower precedence than the relational operators.
➢ The equal to (= =) operator returns True if both the operands have same value,
else it returns False.
➢ The not equal to (!=) operator returns True if both the operands have different
value else it returns False.
Operator Meaning
== Returns 1 if both operands are equal, 0 otherwise.
!= Returns 1 if operands do not have the same value, 0 otherwise.

4. Logical Operators: These are used to test more than one condition and make decision.
The differentlogical operators are: NOT, AND, OR
• Logical NOT (!) The output is true when input is false and vice versa. It
accepts only one input.
Input Output
X !X
0 1
1 0

➢ Logical AND (&&) The output is true only if both inputs are true. It accepts two or
moreinputs.

Input Output
X Y X && Y
0 0 0
0 1 0
1 0 0
1 1 1


BIT, Bangalore-04 Page 11
Principles of Programming Using C BPOPS103

➢ Logical OR (| |) The output is true only if any of its input is true. It accepts two or
more inputs.

Input Output
X Y X || Y
0 0 0
0 1 1
1 0 1
1 1 1
For example: int a=10, b;
b = !a; => result b = 0 (since a = 10 and !a = 0)
Let x=8, y=0; (x > 9) && (y + 1) => results in 0
(x > 9) || (y + 1) => results in 1

5. Unary Operators: There are 4 types:


a) Unary Plus Operator → Determines Sign
b) Unary Minus Operator
c) Increment (++)
d) Decrement (--)
Unary Minus Operator: When a operand is preceded by a minus sign, the unary operator
negates its value. For example: If a number is a Positive then it becomes negative when
preceded with a unary minus operator.
int a, b=10;
a= -(b);
then a holds -10

Increment (+ +): ++ is an increment operator.


➢ As the name indicates, increment means increase, i.e. this operator is used to increase
the value of a variable by 1.
➢ The increment operator is classified into 2 categories:
o Post increment Ex: b++
As the name indicates, post-increment means first use the value of variable and
then increase the value of variable by 1.
o Pre increment Ex: ++b
As the name indicates, pre-increment means first increase the value of variable by
1 and then use the updated value of variable.
For Example:1) if x is 10, then
z = x++; sets z to 10 and increase the value of x by 1
2) if x is 10, then
z = ++x; increase the value of x by 1 and assign the update value
to z, so z will be 11.

BIT, Bangalore-04 Page 12


Principles of Programming Using C BPOPS103

Decrement operator (- -): - - is a decrement operator.


➢ As the name indicates, decrement means decrease, i.e. this operator is used to
decrease the value of a variable by 1.
For Example: if b=5; => then, b-- or --b becomes 4
➢ Similar to increment operator, the decrement operator are classified into 2 types:
o Post decrement (b--)
o Pre decrement (--b)
For Example: if x is 10, then
z = x--; sets z to 10
but z = --x; sets z to 9

Pre-decrement Post- decrement


First value of the operand is decremented First value of the operand is used for
(subtracted) by 1 then, it is used for evaluation then, it is decremented (subtracted)
evaluation. by 1.
Ex: - -a Ex: a- -

6. Conditional Operator/ Ternary Operator (?:) It takes three arguments.


Expression1 ? Expression2 : Expression3
Where,
Expression1 = Condition
Expression2 = Statement followed if condition is true.
Expression3 = Statement followed if condition is false.

Ex: large = (4 > 2) ? 4: 2 # the condition 4>2 holds True hence the value 4 is assigned
to variable large so,
large = 4

7. Bitwise Operators: These works on bits and performs bit by bit operations.
The different types of bitwise operators are:
i. Bitwise NOT (~)
ii. Bitwise AND (&)
iii. Bitwise OR (|)
iv. Bitwise XOR (^)-> Output is True when odd number of 1’s are present.
v. Bitwise left shift (<<)
vi. Bitwise right shift (>>)
Bitwise AND (&) : The truth table is same as shown in logical AND operation. The
bitwise AND operator compares each bit of its first operand with the corresponding bit
of its second operand. If both bits are 1,the corresponding bit in result is 1 otherwise 0.
Example:
10101010 & 01010101 = 00000000
In a C program, the & operator is used as follows.
int a=10, b=20, c=0;
c = a&b;
BIT, Bangalore-04 Page 13
Principles of Programming Using C BPOPS103

Bitwise OR ( | ): The bitwise OR operator compares each bit of its first operand with
the corresponding bit of its second operand. If both bits are 0, the corresponding bit in
result is 0 otherwise 1.

Example:
10101010 | 01010101 = 11111111
In a C program, the & operator is used as follows.
int a=10, b=20, c=0;
c = a|b;

X Y X&Y X|Y
0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1

Bitwise XOR (^): The bitwise XOR operator compares each bit of its first operand
with the corresponding bit of its second operand. If one of the bit is 1, the corresponding
result bit is 1 otherwise 0.
Truth table for XOR
A B A^B
0 0 0
0 1 1
1 0 1
1 1 0
Example:
10101010 ^ 01010101 = 11111111
In a C program, the ^ operator is used as follows:
int a=10, b=20, c=0;
c = a^b;
Bitwise NOT (~): It is a unary operator, performs logical negation on each bit of the
operand.
Example: ~10101011 = 01010100
X ~X
0 1
1 0
Bitwise Left Shift (<<) Shift specified number of bits to left side.
X 0 1 0 0 0 1 1 0
X<<2 0 0 0 1 1 0 0 0

Bitwise Right Shift (>>) Shift specified number of bits to right side.
X 0 1 0 0 0 1 1 0
X>>2 0 0 0 1 0 0 0 1

BIT, Bangalore-04 Page 14


Principles of Programming Using C BPOPS103

8. Assignment Operators: These are used to assign the result or values to a variable. The
different types of assignment operators are:

Simple Assignment a = 10
Multiple Assignment a = b = c = 10

variable=expression
• Ex: 1. c=5 //5 is assigned to c
2. b=c; // c is assigned to b
3. 5=c; // Error! 5 is a constant
The operators such as + =, * = are called shorthand assignment operators.

Operator Example Same as


-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b
9. Comma Operator:
➢ It takes two operands It can be used as operator in expression and as separator in
declaringvariables.
➢ It works by evaluating the first and discarding its value, and then evaluates the
second and returns the value as a result of expression.
➢ It has lowest precedence. Ex:
int a=2, b=3, x=0
x = (++a, b+=a);
Now, the value of x=6.
10. sizeof Operator:

➢ It is used to determine the amount of memory space the variable/data type will take.
➢ It is a unary operator it can be applied to all the data types.

int a=10;
result = sizeof(a);
the result value will be 2. since integer requires 2 bytes of memory.
EXPRESSIONS
✓ It is combination of operands (variables, constants) and operators.
✓ Precedence: The order in which operators are evaluated is based on the priority
value.
✓ Associativity: It is the parsing direction used to evaluate an expression. It
can be left to right orright to left.
✓ Evaluation of expressions: Expressions are evaluated using an assignment
statement.
Ex: variable = expression
sum = a + b

BIT, Bangalore-04 Page 15


Principles of Programming Using C BPOPS103

✓ Following table provides the Precedence and Associativity of operators:

Operator Description Associativity Precedence(Rank)


() Function call
Left to right 1
[] Array element reference
+ Unary plus
- Unary minus
++ Increment
-- Decrement
! Logical negation
Right to left 2
~ Ones complement
* Pointer to reference
& Address
Sizeof Size of an object
(type) Type cast (conversion)
* Multiplication
/ Division Left to right 3
% Modulus
+ Addition
Left to right 4
- Subtraction
<< Left shift
Left to right 5
>> Right Shift
< Less than
<= Less than or equal to
Left to right 6
> Greater than
>= Greater than or equal to
== Equality
Left to right 7
|= Inequality
& Bitwise AND Left to right 8
^ Bitwise XOR Left to right 9
| Bitwise OR Left to right 10
&& Logical AND Left to right 11
|| Logical OR Left to right 12

BIT, Bangalore-04 Page 16


Principles of Programming Using C BPOPS103

?: Conditional expression Right to left 13


=
*= /= %=
+= -= &= Assignment operators Right to left
14
^= |=
<<= >>=

9.16: TYPE CONVERSION


➢ In C language, the programmer can instruct the compiler to convert the data from one
data type to another data type. Sometimes, the compiler itself will convert the data from
1 data type to another data type this process of converting the data from one data type to
another data type is called as type conversion.
⮚ It occurs when mixed data occurs.
⮚ Type conversion is performed by a compiler.
⮚ In type conversion, the destination data type can’t be smaller than the source data type.
⮚ Generally, takes place when in an expression more than one data type is present. In
such conditions type conversion (type promotion) takes place to avoid loss of data.
There are two types of Conversion:

i. Automatic Type Conversion (Implicit) Widening Conversion


➢ C can evaluate the expressions if and only if the data types of two operands are same. So,
if operands are of different type, C cannot evaluate, in such situation, to ensure that both
operands are of the same data type, C compiler converts the data type with a lower rank to
the data type with higher rank. This process of conversion of data from lower rank to
higher rank automatically by the C compiler is known as implicit conversion.

➢ It is clear from the above pyramid that the following relationship holds well:
sizeof(char) < sizeof(short) < sizeof(int)< ..........< sizeof(double)

BIT, Bangalore-04 Page 17


Principles of Programming Using C BPOPS103

➢ If one or parent type is same as other operand type, no conversion takes place and type of
result remains same as the operands stop dictating ie., int + int=int, float + float=float
➢ If one operand type is char and the other operand type is int, the operand with type char is
promoted to
➢ int(This is because int is up in the pyramid when compared to char )
➢ If one operand type is int and the other operand type is float, the operand with type int is
promoted to (This is because float is up in the pyramid when compared to int )
➢ The table shows the examples of implicit type conversions. In the table below, two
operands are added and the results are as shown.
1. Explain how the evaluation is done for the expression 4.0/3
float/int float

The second operand 3 which is of type int is promoted to float and becomes 3.0 and
then evaluation is done. So the result must be of type float.
Advantages and Disadvantages of Implicit Conversion:
Advantages:
➢ Compiler does conversion from lower rank to higher rank. So, programmer need not worry
about the conversion procedure or the syntax.
Disadvantages:
➢ Conversion from higher rank to lower rank is not performed automatically by the compiler.
ii. Type Casting /Manual Type Conversion (Explicit) Narrow Conversion
➢ The programmer can instruct the compiler to change the type of the operand from one data
type to another data type. This forcible conversion from one data type to another data type
is called as explicit type conversion.
➢ In typing casting, a data type is converted into another data type by the programmer using
the casting operator during the program design.
➢ Syntax/Declaration:-
(type)Expression
(int)9.4333
Where,
• type is the required type of the expression.
• expression can be an operand such as variables or a constant.
Example:
i = (int)8.999 8.999 is truncated to 8 and is stored in i. So, i=8
i =(int)5.99 / (int)2.4 5.99 is truncated to 5 and 2.4 is truncated to 2 which results in
5/2=2
So, i=2
BIT, Bangalore-04 Page 18
Principles of Programming Using C BPOPS103

Chapter 10
Decision Control and Looping Statements

10.1 Introduction to Decision Control Statements:


• The code in c program is executed sequentially from the first line of the program to its
last line, i.e., the second statement is executed after the first, the third statement is
executed after the second and so on.
• C support two types of decision control statements that can alter the flow of sequence of
instructions. These include conditional and unconditional branching.

Selection /branching
statements

Conditional Unconditional
type type

if If-else If-else Nested if Switch


ladder

10.2 Conditional Statements:


• The conditional branching statements help to jump from one part of the program to
another depending on whether a particular condition is satisfied or not.
• The decision control statement includes
1. if statement
2. if-else statement
3. if-else-if statement
4. if-else ladder
5. switch statement

1. if- statement:
The if statement is the simplest form of decision control statements that is frequently
used in decision making.
The general form of if statement is as shown below

BIT, Bangalore-04 Page 19


Principles of Programming Using C BPOPS103

Syntax: Flowchart for if statement:

if ( test Expression)
{
Statement1;
}
Statement2;

• The if structure may include one statement or n statements enclosed within


curly brackets.
• First the test expression is evaluated. If the test expression is true, the statement
of if block (statement 1 to n) are executed, otherwise these statements will be
skipped and the execution will jump to statement.
• The statement in an if construct is any valid c language statement and the test
expression is any valid C language expression that may include logical
operators. Note that there is no semicolon after the test expression. This is
because the condition and statement should be placed together as a single
statement.
Example:
#include<stdio.h>
int main()
{
/* local variable definition */
int a=10;
/* check the Boolean condition using if statement
if( a < 20 ) {
/* if condition is true then print the following */
printf("a is less than 20\n" );
}
printf("value of a is : %d\n", a);
return 0;
}

OUTPUT:
a is less than 20
value of a is 10
2. if-else statement:
• The if-else statement is an extension of simple if statement.
• The test expression is evaluated, if the result is true, the statement followed by
the expression is executed
• else if the expression is false, the statement is skipped by the compiler.

BIT, Bangalore-04 Page 20


Principles of Programming Using C BPOPS103

Syntax: Flowchart of if-else statement:

if (test expression) FALSE


{
Test
statement_block 1; Expressi
TRUE
} on
else Statement Block Statement Block 2
{ 1
statement_block 2;
}
statement x;
Statement x

• If the test Expression is true (or non-zero) then Statement1 will be executed; otherwise if
it is false (or zero),then Statement2 will be executed.
• In this case either true block or false block will be executed, but not both.
• In both the cases, the control is transferred subsequently to the Statement X.
Example:
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 100;
/* check the Boolean condition */
if( a < 20 )
{
/* if condition is true then print the following */
printf("a is less than 20\n" );
}
else
{
/* if condition is false then print the following */
printf("a is greater than 20\n" );
}
printf("value of a is : %d\n", a);
return 0;
}
OUTPUT:
a is greater than 20
value of a is 100

3. if-else-if statement:
• It is used to test additional conditions apart from the initial test expression.
• if-else-if construct is also known as Nested if construct.
• Depending on the expressions that have to be tested, the programmer can have
as many as else-if branches.

BIT, Bangalore-04 Page 21


Principles of Programming Using C BPOPS103

Syntax: Flowchart of if-else-if statement:

if (Expression1)
{
if(Expression2)
{
Statement1;
}
else
{
Statement2;
}
}
else if(Expression3)
{
Statement3;
}
else
{
Statement4;
}

• If Expression1 is true, check for Expression2, if it is also true then Statement1 is executed.
• If Expression1 is true, check for Expression2, if it is false then Statement2 is executed.
• If Expression1 is false, then Statement3 is executed.
• Once we start nesting if -else statements, we may encounter a classic problem known as
dangling else.
• This problem is created when no matching else for every if.
• C solution to this problem is a simple rule “always pair an else to most recent unpaired if in
the current block”.
• Solution to the dangling else problem, a compound statement.
• In compound statement, we simply enclose true actions in braces to make the second if a
compound statement.

Example:
#include <stdio.h>
void main()
{
int age;
printf("Please Enter Your Age Here:\n");
scanf("%d",&age);
if ( age < 18 )
{
printf("You are Minor.\n");

BIT, Bangalore-04 Page 22


Principles of Programming Using C BPOPS103

printf("Not Eligible to Work");


}
else
{
if (age >= 18 && age <= 60 )
{
printf("You are Eligible to Work \n");
printf("Please fill in your details and apply\n");
}
else
{
printf("You are too old to work as per the Government rules\n");
printf("Please Collect your pension! \n");
}
}
}
Dangling else problem:
• Once we start nesting if .. else statements, we may encounter a classic problem known as
dangling else.
• This problem is created when no matching else for every if statement.
• In such a case, solution to this problem is a simple rule “always pair an else to most recent
unpaired if in the current block”.
Example:
#include<stdio.h>
void main()
{
int a=10, b=5, c=7;
if(a>b)
if(a>c)
printf(“a is greater number”);
else
printf(“a is not greater number”);
}
• Solution to the dangling else problem, is compound statement.
• In compound statement, we simply enclose true actions in braces to make the second if a
compound
4. else-if ladder:
• There is another way of putting ifs together when multipath decisions are involved. A multi
path decision is a chain of ifs in which the statement associated with each else is an if.
• This construct is known as the else if ladder.
• The conditions are evaluated from the top (of the ladder), downwards. As soon as true
condition is found, the statement associated with it is executed and control transferred to the
Next statement skipping the rest of the ladder.
• When all conditions are false then the final else containing the default Statement4 will be
executed.
BIT, Bangalore-04 Page 23
Principles of Programming Using C BPOPS103

• It is not necessary that every if statement should have an else block as C supports simple if
statements. After the first test expression or the first if branch, the programmer can have as
many else-if branches as he wants depending on the expressions that have to be tested.

Syntax: Flowchart of if-else ladder:

if ( test expression 1)
{
statement block 1;
}
else if ( test expression 2)
{
statement block 2;
}
...........................
else if (test expression N)
{
statement block N;
}
else
{
Statement Block X;
}
Statement Y;

Example:
#include<stdio.h> void main( )
{
int a=20, b=5,c=3;
if((a>b) && (a>c))
printf(“A is greater\n”);
else if((b>a) && (b>c))
printf(“B is greater\n”);
else if((c>a) && (c>b))
printf(“C is greater\n”);

else
printf(“all are equal”);
}

Output:
A is greater
➢ Let us now summarize the rules for using if, if-else, and if-else-if statements.
Rule 1: The expression must be enclosed in parentheses.

BIT, Bangalore-04 Page 24


Principles of Programming Using C BPOPS103

Rule 2: No semicolon is placed after the if/if-else/ if-else-if statement. Semicolon is placed
only at the end of statements in the statement block.
Rule 3: A statement block begins and ends with a curly brace. No semicolon is placed after
the opening/closing braces.
Example program:
C- program to create result w.r.t., pass and fail, first class. Distinction, second class and
fail using else if ladder.
# include <stdio.h>
void main()
{
int m ;
printf(“ enter the marks:\n”) ;
scanf (“%d”, &m) ;
if (m<=34)
{
printf (“Fail”) ;
}
else if ( m>=35 && m<50 )
{
printf(“Pass”) ;
}
else if (m>=50 && m<60 )
{
printf(“Second Class”) ;
}
else if (m>=60) && m<70 )
{
printf(“First Class”);
}
else
printf(“Distinction”) ;
}

5. Switch Case Statement:


• C language provides a multi-way decision statement so that complex else-if statements
can be easily replaced by it. C language’s multi-way decision statement is called switch.

BIT, Bangalore-04 Page 25


Principles of Programming Using C BPOPS103

General syntax of switch statement is as follows


switch(choice)
{
case label1: block1;
break;
case label2: block2;
break;
case label3: block-3;
break;
default: default-block;
break;
}

Flowchart for switch statement is as follows:

• Here switch, case, break and default are built-in C language words.
• If the choice matches to label1 then block1 will be executed else if it evaluates to label2
then block2will be executed and so on.
• If choice does not matches with any case labels, then default block will be executed.
• The choice is an integer expression or characters.
• The label1, label2, label3,….are constants or constant expression evaluate to integer
constants.
• Each of these case labels should be unique within the switch statement. block1, block2,
block3, are statement lists and may contain zero or more statements.
• There is no need to put braces around these blocks. Note that case labels end with colon (:).

• Break statement at the end of each block signals end of a particular case and causes an exit
from switch statement.
• The default is an optional case when present, it will execute if the value of the choice
does not match with any of the case labels.

BIT, Bangalore-04 Page 26


Principles of Programming Using C BPOPS103

Example:
Label →Number Label → Character
#include<stdio.h> #include<stdio.h>
#include<stdlib.h> #include<stdlib.h>
void main( ) void main( )
{ {
int ch, a, b, res; int a, b, res;
float div; char ch;
printf(“Enter two numbers:\n”); floatdiv;
scanf(“%d %d”,&a,&b); printf(“Enter two numbers:\n”);
printf(“1.Addition\n 2.Subtraction\n scanf(“%d%d”,&a,&b);
3.Multiplication\n 4.Division\n printf(“a.Addition\n b.Subtraction\n
5.Remainder\n”); c.Multiplication\n d.Division\n
printf(“Enter your choice:\n”); e.Remainder\n”);
scanf(“%d”,&ch); printf(“Enter your choice:\n”);
switch(ch) scanf(“%c”,&ch);
{ switch(ch)
case 1: res=a+b; {
break; case ‘a’: res=a+b;
case 2: res=a-b; break;
break; case‘b’: res=a-b;
case 3: res=a*b; break;
break; case‘c’: res=a*b;
case 4: div=(float)a/b; break;
break; case ‘d’: div=(float)a/b;
case 5: res=a%b; break;
break; case ‘e’ : res=a%b;
default: printf(“Wrong break;
choice!!\n”); default: printf(“Wrong
} choice!!\n”);
printf(“Result=%d\n”,res); }
} printf(“Result=%d\n”,res);
}
➢ In this program if ch=1 case ‘1’ gets ➢ In this program if ch=’a’ case ‘a’ gets
executed and if ch=2, case ‘2’ gets executed executed and if ch=b, case ‘b’ gets executed
and so on and so on.

Advantage of using switch case statements:


• Easy to debug.
• Easy to read and understand.
• Ease of maintenance as compared with its equivalent if-else statements.
• Like if-else statements switch statements can also be nested.
• Executes faster than its equivalent if-else construct.

BIT, Bangalore-04 Page 27


Principles of Programming Using C BPOPS103

10.3 Iterative Statements:


Iterative statements are used to repeat the execution of a list of statements, depending on
the value of an integer expression.
C language supports 3 types of iterative statements also know as “looping statements”.
They are.
1. while loop
2. do-while loop
3. for loop

1. while loop:
• The while loop provides a mechanism to repeat one or more statements while a
particular condition is true.
Syntax: Flowchart for while loop:

Statement x;
while (condition)
{
statement-block;
}
Statement Y;

• In while loop the condition is tested before any of the statements in the statement block
is executed. If the condition is true, only the statements will be executed otherwise if
the condition is false, the control will jump to statement Y, which is the immediate
statement outside the while loop block.
• From the flow chart diagram, it is clear that we need to constantly update the condition
of the while loop.
• The while loop will execute as long as the condition is true
• Note that if the condition is never update and the condition never becomes false then
the computer will run into an infinite loop which is never desirable.
• A while loop is also referred to as a top-checking loop since the control condition is
placed as the first line of the code. If the control condition evaluates to false ,then the
statements enclosed in the loop are never executed.

BIT, Bangalore-04 Page 28


Principles of Programming Using C BPOPS103

Example:
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* while loop execution */
while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
}
return 0;
}

OUTPUT:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

BIT, Bangalore-04 Page 29


Principles of Programming Using C BPOPS103

2. do-while loop:
It is a post-test loop (also called exit controlled loop) it has two keywords do
and while.
Syntax: Flowchart of do-while loop:

Statement x;
do
{
statement_block;
} while (condition);
statement y;

• The do-while loop is similar to the while loop. The only difference is that in do-while
loop, the test condition is tested at the end of the loop. Now that the test condition is
tested at the end, this clearly means that the body of the loop gets executed at least once.
• Note that the test condition is enclosed in parentheses and followed by a semicolon.
The statement blocks are enclosed within curly brackets. The curly bracket is optional
if there is only one statement in the body of the do-while loop.
• The major disadvantage of using a do-while loop is that it always executes at least once,
even if the user enters some invalid data, the loop will execute. One complete execution
of the loop takes place before the first comparison is actually done.
Example:
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* do loop execution */
do
{
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );
return 0;
}

OUTPUT:
value of a: 10
value of a: 11

BIT, Bangalore-04 Page 30


Principles of Programming Using C BPOPS103

value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Difference between while and do-while loop:


While do… while
It is a pre test loop. It is a post test loop.
It is an entry controlled loop. It is an exit controlled loop.
The condition is at top. The condition is at bottom.
There is no semi colon at the end of while. The semi colon is compulsory at the end of while.
It is used when condition is important. It is used when process is important.
Here, the body of loop gets executed if and only if Here, the body of loop gets executed atleast once
condition is true. even if condition is false.
SYNTAX, FLOWCHART, EXAMPLE (Same as SYNTAX, FLOWCHART, EXAMPLE (Same as
in in
explanation) explanation)

3. for loop:
• Similar to the while and do-while loops, the for loop provides a mechanism to repeat a
task until a particular condition is true.
• For loop is usually known as determinate or definite loop because the programmer knows
exactly how many times the loop will repeat.
• The number of times the loop has to be executed can be determined mathematically by
checking the logic of the loop.
• When a for loop is used, the loop variable is initialized only once. With every iteration
of the loop, the value of the loop variable is updated and the condition is checked. If the
condition is true, the statement block of the loop is executed, else the statements
comprising the statement block of the for loop are skipped and the control jumps to the
immediate statement following the for loop body.
• In the syntax of for loop, initialization of the loop variable allows the programmer to give
it a value. Second, the condition specifies that while the condition expression is TRUE
the loop should continue to repeat itself. Every iteration of the loop must make the
condition near to approachable. So, with every iteration the loop variable must be
updated.

BIT, Bangalore-04 Page 31


Principles of Programming Using C BPOPS103

Syntax:

for (initialization; condition; increment/decrement/update);


{
Statement block;
}
Statement Y;

Flowchart of for loop:

Example:
#include <stdio.h>
int main ()
{
int a;
/* for loop execution */
for( a = 10; a < 20; a = a +1 )
{
printf("value of a: %d\n", a);
}
return 0;
}
OUTPUT:
value of a: 10
value of a: 11

BIT, Bangalore-04 Page 32


Principles of Programming Using C BPOPS103

value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Points to remember abut for loop


• There must be no semicolon after the for loop, if specified we may end up with some
unexpected results.
Example:
#include <stdio.h>
int main()
{
int i;
for (i=0;i<10;i++); //ending for loop with semicolon
printf(" %d", i);
return 0;
}
OUTPUT:
10
• Multiple initializations must be separated with comma operator.
Example:
#include<stdio.h>
int main()
{
int i, sum;
for(i=0, sum=0;i<10;i++) //multiple initialization statement
sum += i;
printf(" %d", sum);
return 0;
}
OUTPUT
45
• If there is no initialization to be done then the initialization statement can be skipped by
giving only semicolon.
Example: for(;i<10;i++) // initialization statement is skipped
• Multiple conditions in the test expression can be tested by using logical operators (&& or
||)
• If the loop controlling variable is updated within the statement block, then the third part
can be skipped.
Example:
#include <stdio.h>
int main()
{
BIT, Bangalore-04 Page 33
Principles of Programming Using C BPOPS103

int i=0;
for(;i<10;)
{
printf(" %d", i);
i=i+1;
}
return 0;
}
OUTPUT:
0123456789
• Multiple statements can be included in the third part of the for statement by using the
comma operator.
Example: for(i=0, j=l0; i<; i++, j--)
• The controlling variable can also be incremented / decremented by values other than 1.
Example:
#include<stdio.h>
int main()
{
int i, sum;
for(i=0;i<10;i+=2) //Increment is done by 2
printf(" %d", i);
return 0;
}
OUTPUT:
02468
• If the for loop contains nothing but two semicolons, that is no initialization, condition
testing and updating of the loop control variable then the for loop may become an infinite
loop.
Example:
#include<stdio.h>
int main()
{
int i=0, sum;
for( ; ; ) //print 0 infinitly
printf(" %d", i);
return 0;
}
• Never use floating point variable as a loop control variable. This is because floating point
values are just approximations and therefore may result in imprecise values and thus
inaccurate test for termination.

BIT, Bangalore-04 Page 34


Principles of Programming Using C BPOPS103

Selecting an appropriate loop:


• Loops can be entry controlled (also known as pre-test) or exit-controlled (also known as
post-test).
• In an entry-controlled loop, condition is tested before the loop starts, an exit-controlled
loop, on the other hand, tests the condition after the loop is executed.
• If the condition is not met in entry-controlled loop, then the loop will never execute, in case
of post-test, the body of the loop is executed unconditionally for the first time.
• If your requirement is to have a pre-test loop, then choose cither for loop or while loop, In
case, you need to have post-test loop then choose a do-while loop.

10.4: Nested Loops:


• Loop that can be placed inside other loops. Although this feature will work with any loop
such as while, do-while and for but it is most commonly used with the for loop, because it
this is easiest to control.
• A for loop can be used to control the number of times that a particular set of statements will
be executed. Another outer loop could be used to control the number of times that a whole
loop is repeated.
Syntax:
Syntax of nested for loop:

for ( init; condition; increment ) {

for ( init; condition; increment )


{statement(s);
}
statement(s);
}
Example1 : Write a program to print the following pattern.
Pass 1- 12345
Pass 2- 12345
Pass 3- 12345
Pass 4- 12345
Pass 5- 12345
#include <stdio.h>
int main()
{
int i, j;
for(i=1;i<=5;i++)
{
printf("\n Pass %d- “,i);
for(j=1;j<=5 ;j++)
printf(" %d", j)
}
return 0;
}
BIT, Bangalore-04 Page 35
Principles of Programming Using C BPOPS103

Example2: Write a program to print the following pattern,


1
12
123
1234
12345
#include <stdio.h>
int main()
{
int i, j;
for(i=1;i<=5;i++)
{
printf("\n");
for(j=1;j<=i;j++)
printf("%d", j) ;
}
return 0;
}

The syntax for a nested while loop statement


while(condition)
{ while(condition)

{
statement(s);
}
statement(s);
}

The syntax for a nested do...while loop statement


do {
statement(s);

do {
statement(s);
}while( condition );

}while( condition );

NOTE: A final note on loop nesting is that you can put any type of loop inside any other type
of loop

BIT, Bangalore-04 Page 36


Principles of Programming Using C BPOPS103

10.5: Break and Continue Statement:


1. Break:

• It terminates the execution of remaining iteration of loop.


• A break can appear in both switch and looping statements.
• In switch statement if the break statement is missing then every case from the matched
case label till the end of the switch, including the default is executed.

Syntax sample
while(condition) #include<stdio.h>
{ void main( )
Statements; {
if(condition) int i;
break; for(i=1; i<=5; i++)
Statements; {
} if(i==3)
Statement x; break;
printf(“%d”, i)
Or }
for( ) }
{
statements; OUTPUT 12
if (condition)
break;
statements;
}
Statement x;

BIT, Bangalore-04 Page 37


Principles of Programming Using C BPOPS103

2. Continue:
• It terminates only the current iteration of the loop.
• Similar to the break statement the continue statement can only appear in the body of a loop.
When the compiler encounters a continue statement then the rest of the statements in the
loop are skipped and the control is unconditionally transferred to the loop- continuation
portion of the nearest enclosing loop
Syntax Flowchart
#include<stdio.h>
while(condition) void main( )
{ {
Statements; int i;
if(condition) for(i=1; i<=5; i++)
continue; {
Statements; if(i==3)
} continue;
printf(“%d”, i)
Or }
for( ) }
{
statements; OUTPUT 1245
if (condition)
continue;
statements;
}

BIT, Bangalore-04 Page 38


Principles of Programming Using C BPOPS103

10.6 goto statement:


• The goto statement is used to transfer control to a specified label. However the label
must reside in the same function and can appear only before one statement in the same
function.
Syntax:
goto Label ;
• Here, label is an identifier that specifies the place where the branch is to be made. Label
can be any valid variable name that is followed by a colon (:). The label is placed
immediately before the statement where the control has to be transferred.
• The label can be placed anywhere in the program either before or after the goto
statement. Whenever the goto statement is encountered the control is immediately
transferred to the statements following the label. Therefore goto statement breaks the
normal sequential execution of the program.
Syntax Example
goto label; void main( )
{
statement1 int a=5,
b=7;
; goto end;
a=a+1;
statement2 b=b+1;
end: printf(“a=%d b=%d”, a,b);
; }

label: OUTPUT: 5 7

• If the label is placed after the goto statement , then it is called a forward jump and in
case it is located before the goto statement, it is said to be a backward jump

BIT, Bangalore-04 Page 39


Principles of Programming Using C BPOPS103

Example 1: C program to find only odd no in the given range n using continue
statement
#include<stdio.h>
void main( )
{
int i , n ;
printf(“Enter the range in which odd no are to be generated \n”) ;
scanf( “%d “ , &n) ;
for(i=1; i<=n; i++)
{
if ( i%2= = 0 )
continue;
printf(“%d ”, i) ;
}
}
OUTPUT:
Enter the range in which odd no are to be generated
10
13579

Example 2: C program to find factorial of a given no using goto statement

#include<stdio.h>
void main( )
{
int i=1, fact=1, n ,loop;
printf(“Enter the no for which fact is to be found \n”) ;
scanf( “%d“ , &n) ;

loop: fact = fact * i ;


i = i ++ ;
if ( i<= n )
goto loop;

printf( “Factorial of a given no=%d”, fact);


}
OUTPUT:
Enter the no for which fact is to be found
3
Factorial of a given no=6

BIT, Bangalore-04 Page 40


Principles of Programming Using C BPOPS103

Example Programs:
1. Write a C program to find sum of first N natural numbers using for, while and do-
while loop.
Hint: ( 1 + 2 + 3 + 4 + . . . . . . . . . . n )
a. for loop:
# include< stdio.h>
void main( )
{
int n, i, sum=0 ;
printf( “ Enter the total no of elements to be summed\n”) ;
scanf( “%d” , &n) ;
for (i=0 ; i<=n ; i++ )
sum = sum + i ;
printf ( “ The sum of first N natural no=%d” , sum) ;
}

b. while loop:
# include< stdio.h>
void main( )
{
int n , i=1 , sum=0 ;
printf( “ Enter the total no of elements to be summed\n”) ;
scanf( “%d” , &n) ;
while ( i<=n )
{
sum = sum + i ;
i++
}
printf ( “ The sum of first N natural no=%d” , sum) ;
}

c. do-while loop:
# include< stdio.h>
void main( )
{
int n , i=1, sum=0 ;
printf( “ Enter the total no of elements to be summed\n”) ;
scanf( “%d” , &n) ;
do
{
sum = sum + i ;
i = i+1 ;
} while ( i<=n ) ;
printf ( “ The sum of first N natural no=%d” , sum) ;
}

BIT, Bangalore-04 Page 41


Principles of Programming Using C BPOPS103

2. Write a C program to find sum of squares of N natural numbers using for loop.
Hint: ( 12+ 22 + 32 + 42 + ----------- + n2 )
# include< stdio.h>
void main( )
{
int n, i, sq_sum=0 ;
printf( “ Enter the total no of elements to be summed\n”) ;
scanf( “%d” , &n) ;
for (i=0 ; i<=n ; i++ )
sq_sum = sq_sum + i * i ;
printf ( “ The sum of first N natural no=%d” , sq_sum) ;
}

3. Write a C program to find sum of odd no. and even no. in first N natural no.
Hint: ( 1 + 3 + 5 + ----------- ) & ( 2 + 4 + 6 + )
# include< stdio.h>
void main()
{
int n, i, even_sum=0 , odd_sum=0 ;
printf( “ Enter the total no of elements to be summed\n”) ;
scanf( “%d” , &n) ;
for (i=1 ; i<=n ; i+=2 )
odd_sum = odd_sum + i ;
for (i=2 ; i<=n ; i+=2 )
even_sum = even_sum + i ;
printf ( “ The sum of odd no. in first N natural no=%d” , odd_sum) ;
printf ( “ The sum of even no. in first N natural no=%d” , even_sum) ;
}

4. Write a C program to find factorial of a given no. using for loop.


Hint: ( 5!= 1 * 2 * 3 * 4 * 5 = 120)
# include< stdio.h>
void main( )
{
int n, i , fact=1 ;
printf( “ Enter the total no of elements to be summed\n”) ;
scanf( “%d” , &n) ;
for (i=1 ; i<=n ; i++ )
fact = fact * i ;
printf ( “ The factorial of given no=%d” , fact) ;
}

Note: Implement above example programs in while, do-while loops.

BIT, Bangalore-04 Page 42

You might also like