0% found this document useful (0 votes)
2 views33 pages

Module 2 Pop Notes C Programming

The document provides an overview of operators in C programming, including arithmetic, relational, logical, assignment, bitwise, unary, and special operators. It also discusses expressions, type conversion, and decision-making statements such as if statements and switch statements. The content is structured to facilitate understanding of programming principles using C at the Bangalore Institute of Technology.

Uploaded by

nainsicse
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views33 pages

Module 2 Pop Notes C Programming

The document provides an overview of operators in C programming, including arithmetic, relational, logical, assignment, bitwise, unary, and special operators. It also discusses expressions, type conversion, and decision-making statements such as if statements and switch statements. The content is structured to facilitate understanding of programming principles using C at the Bangalore Institute of Technology.

Uploaded by

nainsicse
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

lOMoARcPSD|19762420

Module 2 pop notes - C programming

Computer Networks and security (Bangalore Institute of Technology)

Studocu is not sponsored or endorsed by any college or university


Downloaded by Anupama PV (anupamapolur3@[Link])
lOMoARcPSD|19762420

Principles of Programming Using C 22POP13/23

Module-2
Operators in C
An operator is a symbol that tells the compiler to perform specific mathematical and logical
functions. The different operators supported in ‘C’ are:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
6. Unary Operators ฀ Increment and Decrement
7. Ternary/ Conditional Operator
8. Special Operators

1. Arithmetic Operators: 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

2. Relational Operators: These are used to compare two quantities. The output will be either 0 (False) or 1
(True). The different relational operators are:

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)

3. Logical Operators: These are used to test more than one condition and make decision. The different
logical 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

[Link] H G,BIT Page 1

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C 22POP13/23

✓ Logical AND (&&) The output is true only if both inputs are true. It accepts two or more
inputs.
Input Output
X Y X && Y
0 0 0
0 1 0
1 0 0
1 1 1

✓ 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

4. 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
Shorthand Assignment a += 10 ฀ a = a + 10
Multiple Assignment a = b = c = 10

5. 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 NOT (~)

X ~X
0 1
1 0

[Link] H G,BIT Page 2

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C 22POP13/23

✓ Bitwise AND (&), Bitwise OR (|),Bitwise XOR (^)

X Y X&Y X|Y X^Y


0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 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

6. Unary Operators: There are 4 types:

✓ Unary Plus Operator Determines Sign


✓ Unary Minus Operator
✓ Increment (++)
✓ Decrement (--)

✓ Increment (+ +): It adds one to the operand.

Pre-increment Post-increment
First value of the operand is incremented First value of the operand is used for evaluation
then, it is incremented (added) by 1.
(added) by 1 then, it is used for evaluation.
Ex: ++a Ex: a++

[Link] H G,BIT Page 3

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C 22POP13/23

✓ Decrement (- -): It subtracts one from the operand.

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- -

7. 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 ฀ large = 4

8. Special Operator/ Special Symbols


a. Comma Operator: It can be used as operator in expression and as separator in declaring
variables.
b. Sizeof Operator: It is used to determine the size of variable or value in bytes.
c. Address Operator: It is used to find the address of the operators.

5. 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 or
right to left.
✓ Evaluation of expressions: Expressions are evaluated using an assignment statement.
✓ Ex: variable = expression

sum = a + b
✓ Following table provides the Precedence and Associativity of operators:

[Link] H G,BIT Page 4

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C 22POP13/23

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
?: Conditional expression Right to left 13

[Link] H G,BIT Page 5

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C 22POP13/23

=
*= /= %=
+= -= &= Assignment operators Right to left 14
^= |=
<<= >>=
, Comma operator Left to right 15

TYPE CONVERSION

⮚ Converting the value of one data type to another 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.
⮚ Conversion at Compile time
⮚ 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


✓ Here, the operand/ variables of smaller data type is automatically converted to data type of
larger size.
✓ char ฀ int ฀ long int ฀ float ฀ double ฀ long double
✓ Ex: int a = 5;
float b=25,c;
c=a/b;
printf(“%f” , c);

ii. Type Casting /Manual Type Conversion (Explicit) Narrow Conversion

✓ In typing casting, a data type is converted into another data type by the programmer using
the casting operator during the program design.
✓ In typing casting, the destination data type may be smaller than the source data type when
converting the data type to another data type, that’s why it is also called narrowing
conversion.
✓ It is a forced conversion used to convert operand/ variables of larger data type to smaller size
or vice versa.

[Link] H G,BIT Page 6

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C 22POP13/23

Syntax/Declaration:-
destination_datatype = (target_datatype) variable;
( ): is a casting operator.

✓ Ex: int a = 7, c;
float b = 4.0;
b = a % (int) b; printf(“%d” , c);

Decision Making and Branching


Set of instructions or commands given to the computer to perform a specified task can be called as statement.
Basically there are two types of statements in normal executions.

1) Sequentially Executable Statement


2) Non Sequentially Executable Statement

Sequentially Executable Statement:-

These ate the statements in which all the commands or instructions are executed in linear order without
any branching.

Ex:- Area of triangle, Area of a circle etc..

Following typical C code for area of triangle when 3 sides are given:

Scanf(“%d%d%d”, &a,&b,&c);
S=(a+b+c)/2.0;
Area= sqrt ((s*(s-a)*(s-b)*(s-c));
Printf(“Area=%d”, area);

Non-Sequentially Executable statement :


There are the statements in which some statements will alter the flow of execution of a program from one
part to another part with in the program. These are also known as Control statements, or branching
statements.
Ex: Finding the biggest of three numbers.
Checking whether the given no is Odd or Even
Checking whether the given no is +ve or _ve no. etc..

Following is the typical C code to check whether the number is odd or even:

#include<stdio.h>
int main()

[Link] H G,BIT Page 7

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C 22POP13/23

{
scanf(“%d”, &n);
if (n%2= = 0)
printf (“%d is even”, n)
else
printf(“%d is odd:,n);
}

These non sequential or branching statements are again classified into two types:

❖ Condition branching statements


❖ Uncondition branching statements

Decision Making/ Conditional branching statements


✓ The basic decision statement in the computer is the two way selection.
✓ The decision is described to the computer as conditional statement that can be answered TRUE or FALSE.
✓ If the answer is TRUE, one or more action statements are executed.
✓ If answer is FALSE, the different action or set of actions are executed.
✓ Regardless of which set of actions is executed, the program continues with next statement.

✓ C language provides following two-way selection statements:

1. if statement
2. if – else statement
3. Nested if else statement
4. Cascaded if else (also called else-if ladder)
Multi-way Selection statement
5. Switch statement

1. if statement: The general form of simple if statements is shown below.

if (Expression)
{
Statement1;
}
Statement2;

✓ The Expression is evaluated first, if the value of Expression is true (or non zero) then Statement1 will be
executed; otherwise if it is false (or zero), then Statement1 will be skipped and the execution will jump to the
Statement2.

[Link] H G,BIT Page 8

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C 22POP13/23

✓ Remember when condition is true, both the Statement1 and Statement2 are executed in sequence. This is
illustrated in Figure1.
Note: Statement1 can be single statement or group of statements.

Expression True

False Statement1

Statement2

Figure 1: Flow chart of if statement

Example:
#include<stdio.h>
void main( )
{
int a=20, b=11;
if (a >b)
{
printf(“A is greater\n”);
}
}

Output: A is greater

2. if..else statement: The if..else statement is an extension of simple if statement.

if (Expression)
{
Statement1; true-block
}
else
{
Statement2; true-block
}
Statement3;

✓ If the 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.
✓ This is illustrated in Figure 2. In both the cases, the control is transferred subsequently to the Statement3.

[Link] H G,BIT Page 9

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C 22POP13/23

Fals Tru
Expression

Statement2 Statement1

Statement3

Figure 2: Flow chart of if-else statement

Example:
void main( )
{
int a=10, b=11;
if (a >b)
{
printf(“A is greater\n”);
}
else
{
printf(“B is greater”);
}
}

Output: B is greater

3. Nested if .. else statement: When a series of decisions are involved, we have to use more than one
if..else statement in nested form as shown below in the general syntax.

if (Expression1)
{
if(Expression2)
{
Statement1;
}
else
{
Statement2;
}
}

[Link] H G,BIT Page 10

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C

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.

Figure 3: Flow chart of Nested if-else statement

Example1:
#include<stdio.h>
void main( )
{
int a = 20, b=15, c=3;
if(a>b)
{
if(a>c)
{
printf(“A is greater\n”);
}
else
Downloaded by Anupama PV (anupamapolur3@[Link])
Prof. Sunanda H G Page 11
lOMoARcPSD|19762420

Principles of Programming Using C

{
printf(“C is greater\n”);
}
}
else
{
if(b>c)
{
printf(“B is greater\n”);
}
else
{
printf(“C is greater\n”);
}
}
Output: A is greater

Example2:

# include <stdio.h>
# include<conio.h>
void main()
{
int marks;
printf(“ enter the marks of the subject:\n”);
scanf (“%d”, &marks);

if (m>=40)
{
if (m>=60)
printf(“ first class”);
else
printf (“ second class”);
}
else

printf (“Fail”);
}

4. else if ladder or cascaded if else: 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. It takes the following form.

[Link] H G,BIT Page 12

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C

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

✓ 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 .

Figure 4: Flow chart of else if ladder statement

[Link] H G,BIT Page 13

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C

Example1:

#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\n”);
}
Output: A is greater

Example2:

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>
# include<conio.h>
Void main()
{
int m ;
clrscr();
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”) ;

[Link] H G,BIT Page 14

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C

5. Switch 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.
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;
✓ 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 block2
will be executed and so on.
✓ If choice does not matches with any case labels, then default block will be executed.

Figure 5: Flow chart of switch case statement


✓ 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.

[Link] H G,BIT Page 15

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C

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; float
printf(“Enter two numbers:\n”); div;
scanf(“%d%d”,&a,&b); printf(“Enter two numbers:\n”);
printf(“[Link]\n [Link]\n scanf(“%d%d”,&a,&b);
[Link]\n [Link]\n [Link]\n”); printf(“[Link]\n [Link]\n
printf(“Enter your choice:\n”); [Link]\n [Link]\n [Link]\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; case
break; ‘b’: res=a-b;
case 3: res=a*b; break; case
break; ‘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 choice!!\n”); break;
} default: printf(“Wrong choice!!\n”);
printf(“Result=%d\n”,res); }
} printf(“Result=%d\n”,res);
}

In this program if ch=1 case ‘1’ gets executed and if ch=2, case ‘2’ gets executed and so on.

Prof. Sunanda H G Page 16

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C

Unconditional branching statements: These are the statements in which alters the flow of
execution of a program from one part to another part unconditionally There are 4 types of
unconditional branching statements.
1) goto Statement
2) break Statement
3) continue Statement
4) return Statement
1. goto Statement: It is a simple unconditional branching statement used to transfer the flow of
execution from one part to another part without any test condition but just with a label name. (it is
also known as jump statement, here the control will jump to the specified label in the program.)
Syntax:
goto Label ;

✓ A label is a valid variable name. But many programmers avoid the usage of goto statement
because it results in unstructured programming.
✓ Label need not be declared and must be followed by colon.
✓ Label should be used along with a statement to which control is transferred.
✓ Label can be anywhere in the program either before or after the goto label.
.
Syntax Example
goto label; void main( )
{
statement1 int a=5,
b=7; goto
; end; a=a+1;
b=b+1;
statement2 end: printf(“a=%d b=%d”, a,b);
}
;

label:
✓ Here control jumps to label skipping statement1 and statement2 without verifying any
condition tha t is the reason we call it unconditional Forward jumping statement.
✓ If label appear before goto then it jumps backward repeating the statements between label
and goto label called Backward jump

Prof. Sunanda H G Page 17

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C

2. break Statement: It is an another simple unconditional branching statement used to come out
of the particular control structure (if or switch or loop ) without any test condition.
Syntax:
break ;

✓ It terminates the execution of remaining iteration of loop.


✓ A break can appear in both switch and looping statements.

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

OUTPUT 12

3. continue Statement: continue is an unconditional branching statement used to bypass or skip


certain statements in either conditional branching or looping structure.

Syntax:
continue ;

✓ It terminates only the current iteration of the loop.


✓ Continue can appear in looping statements.

Prof. Sunanda H G Page 18

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C

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)
}
}

OUTPUT 1245

[Link] statement: return is also an unconditional branching statement generally used with
function programs.

Syntax :
return ;

Demonstration program on unconditional branching statements:

/* C program to find factorial of a given no using goto statement:*/

#include<stdio.h>
#include<conio.h>

void main( )
{
int i=1, fact=1, n ,loop;
clrscr( ) ;

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);


getch( ) ;

Prof. Sunanda H G Page 19

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C

/* C program to find only odd no in the given range n using continue statement:*/

#include<stdio.h>
#include<conio.h>

void main( )
{
int i , n ,
clrscr( ) ;

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\n”, i) ;
}
getch( );
}
………………………………………………………………………………………………

Looping /Iterative/repetitive Statements:

Definition of Loop: It is a programming structure used to repeatedly carry out a particular


instruction/statement until a condition is true. Each single repetition of the loop is known as an iteration
of the loop.

Three important components of any loop are:

1. Initialization (example: ctr=1, i=0 etc)


2. Test Condition (example: ctr<=500, i != 0 etc)
3. Updating loop control values (example: ctr=ctr+1, i =i-1)

The language C provides 3 types of looping statements:


1. for loop statement
2. while loop statement
3. do-while loop statement

Prof. Sunanda H G Page 20

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C

[Link] loop statement: It is the popular loop statement used to execute the statements repeatedly
for a specified number of times. Here user will know in advance, how many times the set of
statements with in loop will be executed. This is the simple loop can be used for almost all type of
iterative statements.

Syntax:
for ( Initial Condn ; Test Condn ; Modifying Value )
{
Statement 1;
Statement 2;
------------ n;
}

Where for is a key word, initial condition is the beginning loop index should be terminated by the
symbol semicolon. Test condition determines how many times loop should be repeated, and this
also should be terminated by semicolon. Modifying value represents the step value either in
increment or decrement order.
Statements 1 to n are known as body of the loop, these statements will be repeatedly executed as
long as the test condition is true. These statements should be enclosed with two flower brackets.
Note: Like if and switch statements for statements should not be ended with semicolon.

Flowchart of for loop:

for(Initialization;Condition;modify value False


True
Statement 1;
Statement 2;
----------- n;

Next stmt.

Note: In for loops whether both i++ or ++i operations will be treated as pre-increment only.

Prof. Sunanda H G Page 21

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C

Ex 1. Write a C program to find sum of first N natural numbers using for loop.

Hint: ( 1 + 2 + 3 + 4 + . . . . . . . . . . n )

Solution: / * C program to find sum of first N natural numbers */

# include< stdio.h>
# include< conio.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) ;

}
Ex 2. Write a C program to find sum of squares of N natural numbers using for loop.
Hint: ( 1 2 + 2 2 + 3 2 + 4 2 + ----------- n2 )

Solution: / * C program to find sum of squares of first N natural numbers */

# 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) ;

Prof. Sunanda H G Page 22

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C

Ex 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 + ------------ )

Solution: / * C program to find odd sum and even sum of first N natural numbers */
# 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) ;
}

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


Hint: ( 5!= 1 * 2 * 3 * 4 * 5 = 120)

Solution: / * C program to find factorial of a given number */


# 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) ;


}

Prof. Sunanda H G Page 23

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C

[Link] loop statement: It is an another form of loop statement used to execute the statements
repeatedly for a specified number of times. Here user will not know exactly how many times a set
of statements are to be repeated. Loop execution depends on the test condition which checked at
the beginning of the loop. Hence it is also known as pre-tested or entry controlled loop.

Syntax :

while (Test Condition)


{
Statement 1;
Statement 2;
------------ n;
}

Where while is a key word, Test condition determines how many times loop should be repeated,
this looping statement does not include initial condition and modifying value with in the loop
statement instead they are either in the body of the loop or outside the loop.
Here also the statements followed by while will be repeatedly executed as long as the test condition
is true. These statements should be enclosed with two flower brackets.

Note: Like if and for statements while also should not be ended with semicolon.

Initial condition

while (Test Condition ) False


True
Statement 1;
Statement 2;
Modifying val;
----------- n;

Next stmt.

Prof. Sunanda H G Page 24

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C

** Here modifying value is included in the body of the statement itself, and initial
Condition will be outside the while.

Ex 1: Write a C program to find sum of first N natural numbers using while loop.
Hint: ( 1 + 2 + 3 + 4 + -----------n )
Solution: / * C program to find sum of first N natural numbers using 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 = i++
}

printf ( “ The sum of first N natural no=%d” , sum) ;

Ex 2. Write a C pgm to find sum of squares of N natural numbers using while loop.
Hint: ( 1 2 + 2 2 + 3 2 + 4 2 + ----------- n2 )
Solution: / * C program to find sum of squares of first N natural numbers */

# include< stdio.h>
# include< conio.h>
void main( )
{
int n, i=1, sq_sum=0 ;
clrscr( ) ;
printf( “ Enter the total no of elements to be summed\n”) ;
scanf( “%d” , &n) ;

while ( i<=n )
{
sq_sum = sq_sum + i * i ;
i = i++ ;
}
Prof. Sunanda H G Page 25

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C

printf ( “ The sum of first N natural no=%d” , sq_sum) ;


getch( );
}

Ex 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 + ------------ )

Solution: / * C program to find odd sum and even sum of first N natural numbers */
# include< stdio.h>
# include< conio.h>
void main( )
{
int n, i =1, j=2, even_sum=0 , odd_sum=0 ;
printf( “ Enter the total no of elements to be summed\n”) ;
scanf( “%d” , &n) ;
while ( i<=n )
{
odd_sum = odd_sum + i ;
i=i+2;
}
while (j<=n )
{
even_sum = even_sum + j ;
j=j+2;
}
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) ;

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


Hint: ( 5!= 1 * 2 * 3 * 4 * 5 = 120)

Solution: / * C program to find factorial of a given number */


# include< stdio.h>
void main( )
{
int n, i , fact=1 ;
clrscr( ) ;
printf( “ Enter the total no of elements to be summed\n”) ;
scanf( “%d” , &n) ;
while ( i<=n )
{
fact = fact * i ;
Prof. Sunanda H G Page 26

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C

i = i++ ;
}
printf ( “ The factorial of given no=%d” , fact) ;
}

3. do while loop statement: It is a repetitive statement used to execute set of statements depending
on the condition which is checked at the end of loop structure.( opposite to while statement) Hence
it is also referred as post tested or exit control loop. Here the statements followed by while will
be executed at least once irrespective of the test condition.
Syntax:
do
{
Statement 1;
Statement 2;
------------ n;
while (Test Condition) ;

Where do is a key word, the statements followed by do will be executed at least once irrespective
of the test condition. Here also the statements below do should be enclosed with in two flower
brackets.
Note: Most importantly while statement should end with semicolon.
Flow chart:
loop:
do

Statement 1;
Statement 2;
Modifying val;
----------- n;

while (Condition) False

True

Next executing stmt.

Prof. Sunanda H G Page 27

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C

Ex: 1 Ex 1: Write a C pgm to find sum of first N natural numbers using do-while
Hint: ( 1 + 2 + 3 + 4 + -----------n )

Solution: / * C program to find sum of first N natural numbers using 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++ ;
} while ( i<=n ) ;

printf ( “ The sum of first N natural no=%d” , sum) ;


}

Ex 2 : Write a C pgm to display the string BIT n times using do-while loop
Solution: / * C program to find sum of first N natural numbers using do while loop*/

# include< stdio.h>
# include< conio.h>
void main()
{
int n , i=1;
printf( “ Enter the no of times the string is to be printed \n”) ;
scanf( “%d” , &n) ;

do
{
Printf(“ BIT\n”);
i = i++ ;
} while ( i<=n ) ;

printf ( “ Bangalore-60) ;

Prof. Sunanda H G Page 28

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C

Differentiate between while and do-while loop:

while is a looping structure in which do while is a looping structure in which


condition is checked at the beginning. test condition is checked at the last.

It is an entry controlled loop It is an exit controlled loop.


This is also called as pre tested loop. This is also called as post tested loop.

Statements after while will be executed Statements after do will be executed at least
only when the test condn. is true. once irrespective of the test condition.

while loop is widely used in pgms do while is rarely used looping structure.
when compared do while.
There is no semi colon at the end of while The semi colon is compulsory at the end of while.

Syntax: Syntax:
while (Test Condition) do
{ {
Statement 1; Statement 1;
Statement 2; Statement 2;
------------ n; ------------ n;
} } while (Test condition) ;

Example: (Give any ex pgm ) Example: (Give any ex pgm.)

Nested for loops:


✓ A for loop inside a for loop is called Nested for loop.

Example:

for(i=0; i<2; i++)


{
for(j=0; j<2; j++)
{
scanf(“%d”, &a[i][j])
}
}

Note: If updation is not present in loops then, it will execute infinite times.
If initialization is not given then, program prints nothing.

Prof. Sunanda H G Page 29

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C

Pascal's triangle:

Pascal triangle is one of the classic example taught to engineering students. It has many
interpretations. One of the famous one is its use with binomial equations.

All values outside the triangle are considered zero (0). The first row is 0 1 0 whereas only 1 acquire
a space in pascal's triangle, 0s are invisible. Second row is acquired by adding (0+1) and (1+0).
The output is sandwiched between two zeroes. The process continues till the required level is
achieved.

Prof. Sunanda H G Page 30

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C

Pascal's triangle can be derived using binomial theorem. We can use combinations and factorials
to achieve this.

Algorithm

Assuming that we're well aware of factorials, we shall look into the core concept of drawing a
pascal triangle in step-by-step fashion −

Implementation

#include <stdio.h>
int main()
{
int rows, num = 1, space, i, j;
printf("Enter number of rows: ");//number of rows for generating pascal triangle
scanf("%d",&rows);

for(i=0; i<rows; i++) // outer loop for displaying rows


{
for(space=1; space <= rows-i; space++) // space for every row
printf(" ");

for(j=0; j <= i; j++) // inner loop for displaying the nuum


{
if (j==0 || i==0) // outer loop value or inner-loop value is "0 " it prints 1
num = 1;
else
num = num*(i-j+1)/j; //calculate the coefficient

printf("%4d", num);
}
printf("\n");
}

Prof. Sunanda H G Page 31

Downloaded by Anupama PV (anupamapolur3@[Link])


lOMoARcPSD|19762420

Principles of Programming Using C

return 0;
}

The output should look like this −

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

Prof. Sunanda H G Page 32

Downloaded by Anupama PV (anupamapolur3@[Link])

You might also like