Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
35 views

Module 2 Notes of POP

Branching and looping in C

Uploaded by

karanthvishnu1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Module 2 Notes of POP

Branching and looping in C

Uploaded by

karanthvishnu1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

C programming for Problem Solving - 18CPS13/23

Programming in C and Data Structures (18CPS13/23)


Module 2
Branching and Looping

Topics:
Two way selection (if, if-else, nested if-else, cascaded if-else),switch statement, ternary operator? Go to,
Loops (For, while-do,do-while) in C, break and continue, Programming examples andexercises.
Course Outcome:
Understand the basic principles of Programming in C language.

Selection statements are those in which the statements are executed depending upon the condition.
If the condition is true, a true block is executed, otherwise the false block is executed. A block is a set of
statements enclosed within a pair of { }.
In selection statements, relational and logical operators are used.
Examples
Original expression Simplified expression
!(x<y) x>=y
!(x<=y) x>y
!(x>y) x<=y
!(x>=y) x<y
!(x==y) x!=y
!(x!=y) x==y

Decision making statements


• Two way Selection
 Simple if statement
 if – else statement
 if - else ladder
 Nested if statement
• Multi way selection
 switch statement

Simple if statement

Syntax : Working :
if( (condition) If condition is true
{ True block
true block +
} statement x
statement x; If condition isfalse
statement x
C programming for Problem Solving - 18CPS13/23

It is basically a two way decision statement and it is used in conjunction with an expression. It is used to
execute a set of statements if the condition is true. If the condition is false it skips executing those set of
statements.

Example Output
int a, b, c; Run 1
printf(“Enter a & b\n”); Enter a & b
3 15
scanf(“%d %d”, &a, &b);
18 21
if(a<=b) End of program
{
b+ = 3; Run 2
c = a + b; Enter a & b
printf(“%d “%d”, b, c); 13 5
} End of program
printf(“\nEnd of program”);

Example Output
int a, b, c; Run 1
printf(“Enter a and b\n”); Enter a and b
55
scanf(“%f %f”, &a, &b);
a& b equal
if(a>=b) End
printf(“a & b equal\n”);
if(a>b+5) Run 2
printf(“a grater than b\n”); Enter a and b
printf(“End”); 10 3
a& b equal
a greater than b
End
C programming for Problem Solving - 18CPS13/23

if – else statement
It is an extension of if statement. It is used to execute one among the two set of statements at a time. If
condition is true it executes the true block otherwise it executes the false block. The syntax and flow diagram
is shown below

Syntax : Working :
if( (condition) If condition is true
{ True block + statement x
true block If condition is false
} False block + statement x
else
{
false block
}
statement x;

Note :
A pair of { } is not necessary when a true or false block has only one statement.
Example:
int a=56, b=89, c=12, d=44;
int a=56, b=89, c=12, d=44;
if(a>=b) if(a>=b)
{
c = c * 5;
c = c * 5; Can be written as else
}
d = d%2 ;
else
printf(“End of program”);
{
d = d%2 ;
}
printf(“End of program”);
Statement x
Programming in C &Data Structures - 15PCD13/23

Examples
Output
1. int a = 15, b = 10, c;
16 11
if(a<=b) End of program
{
b+ = 3;
c = a + b;
printf(“%d “%d”, b, c);
}
else
{
a++;
b++;
printf(“%d %d”,a,b);
}
printf(“\nEnd of program”);

2. float a, b, c; Output
printf(“Enter a and b\n”); Execution 1
scanf(“%f %f”, &a, &b); Enter a and b
if(b==0) 12
printf(“Invalid value of b\n”); 5
c=2.4
else
Execution 2
{
Enter a and b
c = a/b;
12
printf(“c=%f”,c); 0
} Invalid value of b

3. float a, b, c; Output
printf(“Enter a and b\n”); Execution 1
scanf(“%f %f”, &a, &b); Enter a and b
12
if(b==0)
5
printf(“Invalid value of b\n”);
c=2.4
else Execution 2
c = a/b; Enter a and b
printf(“c=%f”,c); 12
0
Statement x Invalid value of b
c=garbage value
C programming for Problem Solving - 18CPS13/23

4. Input an integer and check whether it is odd or even


void main()
{
int n;
printf(“Enter an integer”);
scanf(“%d”, &n);
if(n%2 = = 0)
printf(“The number is even”);
else
printf(“The number is odd”);
}

if – else ladder

Syntax : Working :

if( (condition 1) if condition1 is true


{ True block1 + statement x
true block 1
} else if condition2 is true
else if(condition 2)
True block2 + statement x
{
true block 2 else if condition3 is true
}
else if(condition 3) True block3 + statement x
{
---
true block 3
} ---
---
--- else if condition n is true
else if(condition n)
True block n + statement x
{
else
true block n
} false block + statement x
else
{
false block
}
statement x;

This is another way of putting ifs together when multipath decisions are involved. A multipath decision is a
chain of ifs in which the statement associated with each else is an if.
C programming for Problem Solving - 18CPS13/23

Examples :
1. Input an integer and check whether it is 0 or +ve or –ve
void main()
{
int n;
printf(“Enter an integer\n”);
scanf(“%d”, &n);
if(n==0)
printf(“The number is 0”);
else if(n>0)
printf(“The number is +ve”);
elseprintf(“The number is –ve”);
}

2. Input a character and print whether it is uppercase letter or lowercase letter or digit or any other
character.
void main()
{
charch;
printf(“Enter a character\n”);
scanf(“%c”, &ch);
if(ch>=’a’ &&ch<=’z’)
printf(“It is an upper case letter”);
else if(ch>=’a’ &&ch<=’z’)
printf(“It is a lower case letter”);
else if(ch>=’0’ &&ch<=’7’)
printf(“It is a digit”);
elseprintf(“It is a special symbol”);
}
C programming for Problem Solving - 18CPS13/23

3. Input an integer m. If m is 10, square it and print it. If m is 9, read new value for m and print it. If m is
2 or 3, multiply m by 5 and print it. If m is any other value, increment m by 1 and print it.
void main()
{
int m;
printf(“Enter an integer\n”);
scanf(“%d”, &m);
if(m = = 10)
printf(“square is %d”, m*m);
else if (m = = 9)
{
printf(“Enter new value of m\n”);
scanf(“%d”, &m);
printf(“m= %d”, m);
}
else if(m = =2 || m = = 3)
printf(“%d”, m*5);
elseprintf(“%d”, ++m);
}

4. Input income and find the tax amount according to the following conditions.
Income tax
<=10000 2%
<=20000 5%
<=30000 7%
<=50000 10%
>50000 15%

void main()
{
float income, tax;
printf(“Enter income\n”);
scanf(“%f”, &income);
if(income<=10000)
tax = 0.02 * income;
else if(income<=20000)
tax = 0.05 * income;
else if(income <=30000)
tax = 0.07 * income;
else if (income<=50000)
tax = 0.1 * income;
else
tax = 0.15 * income;
C programming for Problem Solving - 18CPS13/23

printf(“tax = %f”, tax);


}

5. Input marks and find the grade according to the following conditions
marks grade
75 – 100 A
60 – 74 B
50 – 59 C
40 – 49 D
<40 E

void main()
{
int marks;
char grade;
printf(“Enter marks\n”);
scanf(“%d”, &marks);
if(marks>=75 && marks <=100)
grade = ‘A’;
else if(marks>=60 && marks <75)
grade = ‘B’;
else if(marks>=50 && marks <60)
grade = ‘C’;
else if(marks>=40 && marks <50)
grade = ‘D’;
else
grade = ‘E’;
printf(“The grade is %c”, grade);
}

6. Input 2 operands and an operator (+ , - , * , /) and find corresponding value.


void main()
{
float a, b, c;
char op;
printf(“Enter an expression (operand operator operand - Ex : 7 * 6 )\n”);
scanf(“%f%c%f”, &a, &op,&b);
if(op = = ‘ + ’)
{
c = a + b;
printf(“Sum = %f”, c);
}
else if(op = = ‘ - ’)
C programming for Problem Solving - 18CPS13/23

{
c = a - b;
printf(“Difference = %f”, c);
}
else if(op = = ‘ * ’)
{
c = a * b;
printf(“Product = %f”, c);
}
else if(op = = ‘ / ’ && b!=0)
{
c = a / b;
printf(“Quotient = %f”, c);
}
else
printf(“Invalid operator”);
}

Nested if – else statement


When a series of decisions are involved we may have to use more than one if else statement in nested form.
The nested if else statements are multi decision statements which consists of if else control statements within
another if or else section

Use of one if within another if statement is called as nested if statement.


C programming for Problem Solving - 18CPS13/23

Syntax : Working :
if (condition 1) If condition 1 is true
{ Check condition 11
if(condition 11)
If condition 1 is false
{
true block 11 Check condition 22
}
else Condition 1 is true
{ If condition 11 is true
false block 11 True block 11 + statement x
} If condition 11 is false
}
False block 11 + statement x
else
{
if(condition 22) Condition 1 is false
{ If condition 22 is true
true block 22 True block 22 + statement x
} If condition 22 is false
else
False block 22 + statement x
{
false block 22
}
}
statement x ;

1. Input 3 numbers and find the smallest among them.


void main()
{ int a, b, c, s;
printf(“Enter 3 numbers\n”);
scanf(“%d %d %d “, &a, &b, &c)
if(a<b)
{ if(a<c)
s = a;
else
s = c;
}
else
{
if(b<c)
s = b;
else
s = c;
}
printf(“The smallest number is %d”, s);
}
C programming for Problem Solving - 18CPS13/23

2. Input 3 numbers and find the largest among them.


void main()
{
int a, b, c, large;
printf(“Enter 3 numbers\n”);
scanf(“%d %d %d “, &a, &b, &c)
if(a>b)
{ if(a>c)
large = a;
else
large = c;
}
else
{
if(b>c)
large = b;
else
large = c;
}
printf(“The largest number is %d”, large);
}

Multi way selection - Switch statement


Syntax :
switch( expression) Working :
{ A switch statement checks the value of an
case constant 1 : expression against many cases. If any of
statements the case values is matching with the value
break; of the switch expression, the block of
Statements under case value are executed.
case constant 2 : Break is a keyword used along with each
statements case to come out of the switch after the
break; execution of the statements of the
Corresponding case. If the switch
case constant 3 : expression value is not matching with any
statements of the case values, the control is
break; transferred to the default case and the
statements under default case are
--- executed.
---
default :
false statements
break;

37
C programming for Problem Solving - 18CPS13/23

}Statement x;
Examples

1. int x = 1, y = 12, z =4;


switch(x) Working :
{ The value of x is compared with case
case 0 : values.
x = 2; Since x = 1, case 1 is matching and the
y = 3; statements for that case are executed.
break; Hence x = 4 , y++ ----> y = y+1
case 1 : x = 4 , y = 13
x = 4;
y++; Output :
break; 4 13 4
default :
y = 3;
z = 7;
}
printf(“%d %d %d”, x, y, z);

2. Rewrite the following code using Using switch


switch statement switch ( ch )
if (ch = = ‘E’) {
count1++; case ‘E’ :
else count1 ++;
if(ch = = ‘A’) break;
count2 ++; case ‘A’ :
else count 2 ++;
break;
if(ch = = ‘I’)
case ‘I’ :
count3 ++;
count3 ++;
else
break;
printf(“Error”); default :
printf(“Error”);
}

3. Rewrite the following code using if else statement


int a = 1, b = 0; Using if else
switch (++a) int a = 1, b =0;
{
++a;
case 1:
if (a = = 1)
b= a + 10;
b= a + 10;
break;
case 2 : else if (a = = 2)
b = a * 5; b = a * 5;
break; else if (a = = 3)
case 3 : b = a – 2;
b = a – 2; else

printf(“Invalid value”);
printf(%d %d”, a, b); 37
C programming for Problem Solving - 18CPS13/23

break;
default :
printf(“Invalid value”);
}
printf(%d %d”, a, b);

Input an integer between 1 and 7 and print the corresponding day of the week. If it is not between 1 and 7,
display suitable message
void main()
{ int a;
printf(“Enter an integer(1 - 7)\n”);
scanf(“%d”, &a);
switch(a)
{
case 1 :
printf(“Sunday”);
break;
case 2 :
printf(“Monday”);
break;
case 3 :
printf(“Tuesday”);
break;
case 4 :
printf(“Wednesday”);
break;
case 5 :
printf(“Thursday”);
break;
case 6 :
printf(“Friday”);
break;
case 7 :
printf(“Saturday”);
break;
default :
printf(“Invalid number”);
}
}

Simulate a calculator using switch statement.


void main()
{
float a, b, c;
char op ;
printf(“Enter an expression (a + b)\n”);
scanf(“%f %c %f” , &a, &op, &b);
switch(op)
{
case ‘+’ :
C programming for Problem Solving - 18CPS13/23

c = a + b;
printf(“sum = %f “, c);
break;
case ‘-’ :
c = a - b;
printf(“Difference = %f “, c);
break;
case ‘*’ :
c = a * b;
printf(“Product = %f “, c);
break;
case ‘/’ :
if(b==0)
{
printf(“ b cannot be 0”);
exit(0);
}
c = a / b;
printf(“Quotient = %f “, c);
break;
default :
printf(“Invalid operator”);
}
}

Rules of switch statement


1. Expression that follows the keyword switch must be an integral type (int / char).
2. Constant values can be only int / char.
3. No two case labels have same values.
4. It cannot be used for range of values.
5. Values cannot be compared with relational or logical operators. It works only for = = operator.
6. default case is optional.

Examples of switch statement without break for case values


Give the output for the following Working :
charch; If ch is ‘A’,
switch(ch) Case ‘A’ is matching and the statements for case ‘A’ are
{ executed. Since case ‘A’ is not ended by break statement, the
statements under the next case are also evaluated. Hence all
the case values are executed till a break statement is
encountered.
The output would be
Grade A
Grade B If ch is ‘C’,
case ‘C’ and default
If ch is ‘H’, case are evaluated.
default case is evaluated. The output would be
The output would be Grade C
Grade F Grade F
ase ‘A’:
printf(“Grade A\n”); case ‘B’ :
printf(“Grade B\n”); break;
case ‘C’:
printf(“Grade C\n”); default :
printf(“Grade ‘F\n”);
}

rogramming for Problem Solving - 18CPS13/23

Give the output for the following Working


int x = 0, y = 1, z = 1; x is 0 and matching with case 0.
switch (x) Hence x = 2 , y =3
{ Since there is no break statement after case 0,
case 0 : Case 1 statements are also executed.
x = 2; Hence x = 4 and y remains as 3
y = 3; So
X = 4 , y = 3 and z = 1
case 1 :
x = 4; Output
break; 431
default :
x = 1;
y = 3;
}
printf(“%d %d %d”, x, y , z);

Give the output for the following Working


int x = 1, y = 0, z = 1; x is 1 and matching with case 1.
switch (x) Hence
{ case 0 : x+ = 2 ------------> x = x + 2------ > x = 1 + 2 = 3
x++ ; z++ ----------------> z = z + 1 -----> = 1 + 1 = 2
y++ ; Since there is no break statement after case 1,
break; Case 2 statements are also executed.
case 1 : Hence
x+= 2; z = z * 3----- > z = 2 * 3 = 6
z++; y - - ----------> y = y – 1 -----> y = 0 – 1 = -1
case 2 :
z * = 3 ; y--; So
break; x = 3 , y = -1 and z =6
default :
x = x + 10; Output
y * = 2; 3 -1 6
}
printf(“%d %d %d”, x, y , z);
Rewrite the following code using switch statement
if (ch = = ‘E’ | | ch = = ‘e’) count1++;
else if(ch = = ‘A’ | | ch = = ‘a’) count2 ++;
else if(ch = = ‘I’ | | ch = = ‘i’) count3 ++;
else
printf(“Error”);
Using switch
switch ( ch )
{
case ‘E’ : case ‘e’ : count1 ++;
break;
case ‘A’ : case ‘a’: count 2 ++; break;
case ‘I’ : case ‘i’: count3 ++; break;
default :
printf(“Error”);
}
C programming for Problem Solving - 18CPS13/23

Differences between if else ladder and switch statement


S.N If – else ladder Switch statement

Each test condition is checked for true The control is transferred to the
1 value. If true, statement block is particular case value. It does not check
executed. each and every case value.
Expression that follows the keyword Expression that follows the keyword
2 ifcan be of any data type. switch must be an integral type (int /
char).

Values used for comparison can be of Constant values given in casecan be only
3 any data type. int / char.

If else can be used for a range of switch cannot be used for range of
4 values (using relational and logical values.
operators)
Ex : if(a>=7 && a<=10)
Values can be compared with any Values cannot be compared with
5 type of operator. relational or logical operators. It works
only for = = operator.
37 Page 16 of
C programming for Problem Solving - 18CPS13/23

Repetition (Looping)
Definition
To repeat the instruction set many number of times, looping statements are used.

Types of loops
• Pretest loop (Entry controlled loop)
• Posttest loop (Exit controlled loop)

Pre test loop Post test loop

In each iteration In each iteration


Control expression tested The loop instructions are executed, then
• If true, loop instructions are executed the control expression is tested.
• If false, loop terminates. • If true, new iteration
• If false the loop terminates.
Minimum no. of iterations is 0. Minimum no. of iterations is 1.

Pretest loops Posttest loop


• while loop • do – while loop
• for loop
Also called as entry controlled loop. Also called as exit controlled loop.

Loops in C
• while - pre test
• for - pre test
• do while - post test

Page 17 of
37
C programming for Problem Solving - 18CPS13/23

While loop

Syntax :
Initialization
while(test condition)
{
statement block
updation
}
Statement x;

Working :

1. Initialization is done with one or more variables.


2. The test condition is checked.
If true
• Statement block and updations are executed
• The control is transferred again to test condition, goto step 2
If false
Goto step 3
3. Statement x is executed

Examples

1. Write a program to generate the numbers from 1 to 20


while has 3 parts
• Initialization (start value)
• Test condition (final value)
• Updation (common difference)

void main()
{
int a = 1; // initialization
while(a<=20) // condition
C programming for Problem Solving - 18CPS13/23

{
printf(“%d “, a);
a = a + 1; // updation
}
}

2. Write a program to generate the following series


50 51 52 --- 100
void main()
{
int a = 50;
while(a<=100)
printf(“%d “, a++);
}

3. Write a program to generate the following


2 4 6 8 ---- 200
void main()
{
int a = 2;
while(a<=200)
{
printf(“%d “, a);
a = a + 2;
}
}

4. Write a program to generate the following


100 99 98 97 ---- 1
void main()
{
int a = 100;
while(a>=1)
{
printf(“%d “, a);
a = a - 1;
}
}

5. Write a program to generate the following


10 20 30 40 ---- 100
void main()
{
int a = 10;
C programming for Problem Solving - 18CPS13/23

while(a<=100)
{
printf(“%d “, a);
a = a + 10;
}
}

6. Write a program to find the sum of the following


Sum = 1 + 2 + 3 + - - - + 100
void main()
{
int a = 1, sum = 0;
while(a<=100)
{
sum = sum + a;
a = a + 1;
}
printf(“sum = %d “, sum);
}

7. Find the output for the following code

void main() Output


{ 2 3
int a = 2, sum = 0; 5 4
while(a<=6) 9 5
{ 14 6
sum = sum + a; 20 7
a = a + 1; sum = 20
printf(%d %d\n”, sum, a); a=7
}
printf(“sum = %d\n”, sum);
printf(“a = %d“, a);
}

8. Write a program to find the sum of the following


Sum = 1 + 3 + 5 + ------- + 101
void main()
{
int a = 1, sum = 0;
while(a<=101)
{
sum = sum + a;
a = a + 2;
C programming for Problem Solving - 18CPS13/23

}
printf(“sum = %d “, sum);
}
9. Write a program to find the sum of the following
Sum = 1 + 2 + 3 + - - - + n
void main()
{
int a = 1, sum = 0, n;
printf(“Enter n\n”);
scanf(“%d”, &n);
while(a<=n)
{
sum = sum + a;
a = a + 1;
}
printf(“sum = %d “, sum);
}

10. Write a program to find the sum of the following


Sum = 1 + 1/2 + 1/3 + - - - + 1/50
void main()
{
float a = 1, sum = 0;
while(a<=50)
{
sum = sum + 1/a;
a = a + 1;
}
printf(“sum = %d “, sum);
}

11. Write a program to find the product of the following


result = 1 * 2 * 3 * 4 --------- * 10
void main()
{
longint a = 1, result = 1;
while(a<=10)
{
result = result * a;
a = a + 1;
}
printf(“result = %ld “, result);
}
C programming for Problem Solving - 18CPS13/23

12. Write a program to find the factorial of a number n.


void main()
{
int n, a = 1;
longint fact = 1;
printf(“Enter a number \n”);
scanf(“%d”, &n);
if(n<0)
{
printf(“Invalid value”);
exit(0);
}
while(a<=n)
{
fact = fact * a;
a = a + 1;
}
printf(“factorial = %ld “, fact);
}

13. Write a program to input a binary number and find its equivalent decimal.
void main()
{
intnum, dec=0, rem, i=0;
printf(“Enter a binary number \n”);
scanf(“%d”, &num);
while (num !=0)
{
rem = num % 10;
if(rem!=0 && rem!=1)
{
printf(“Not a binary number”);
exit(0);
}
dec = dec + rem * pow(2,i);
i++;
num = num/10;
}
printf(“The decimal equivalent is %d “, dec);
}

14. Write a program to input a decimal number and find its equivalent binary.
void main()
{
intnum, bin=0, rem, i=0;
printf(“Enter a decimal number \n”);
scanf(“%d”, &num);
while (num !=0)
C programming for Problem Solving - 18CPS13/23

{ rem = num % 2;
bin = bin + rem * pow(10,i);
i++;
num = num/2;
}
printf(“The binary equivalent is %d “, bin);
}

15. Write a program to input an integer and add the digits.


Ex : n = 3512 sum = 3 + 5 + 1 + 2 = 11
void main()
{ intnum, sum=0, rem;
printf(“Enter an integer\n”);
scanf(“%d”, &num);
while (num !=0)
{ rem = num % 10;
sum = sum + rem;
num = num / 10;
}
printf(“Sum of digits = %d”, sum);
}

for loop

Syntax :
for(Initialization; test condition; updation)
{
statement block
}
Statement x;
C programming for Problem Solving - 18CPS13/23

Working :

1. Initilaization only once at the beginning of for loop.


2. The test condition is checked.
If true
• Statement block and updations are executed
• The control is transferred again to test condition, goto step 2
If false
Goto step 3
while loop for loop

Preferred when the exact number of Preferred when exact number of iterations
iterations are not known. are known.
3. Statement x is executed

Difference between for and while loops

Examples

1. Write a for loop to generate the following series


50 51 52 --- 100
void main()
{
int a;
for(a = 50; a<=100 ; a++)
printf(“%d “, a);
}

2. Write a for loop to generate the following


2 4 6 8 ---- 200
void main()
{
int a;
for(a=2 ; a<=200; a = a+2)
printf(“%d “, a);
}

3. Write a for loop to generate the following


3 6 9 ---- 300
void main()
C programming for Problem Solving - 18CPS13/23

{
inti=3;
for(; i<=300; i = i+3)
printf(“%d “, i);
}

4. Write a for loop to find the sum of the following


Sum = 1 + 2 + 3 + - - - + 100
void main()
{
int a, sum ;
for(a=1, sum=0;a<=100;++a)
sum = sum + a;
printf(“sum = %d “, sum);
}
Statement x

5. Write a for loop to find the sum of the series


Sum = 12 + 22 + 32 + 42+ ------- + n2
void main()
{
inti,n, sum=0;
printf(“Enter no. of terms\n”);
scanf(“%d”, &n);
for(i=1 ; i<=n; i++)
sum+ = i*i;
printf(“Sum=%d “, sum);
}

6. Write a for loop to find the sum of even numbers and odd numbers from 1 to 100.
void main()
{
inti, odd, even;
for(i=1, odd=0, even=0 ; i<=100; i++)
{
if(i%2==1) odd+=i;
else even+=i;
}
printf(“Odd=%d Even=%d“, odd, even);
}

7. Write a for loop to find the factorial of a number n.


void main()
{
int n, i;
longint fact;
printf(“Enter a number \n”);
scanf(“%d”, &n);
C programming for Problem Solving - 18CPS13/23

if(n<0)
{
printf(“Invalid value”);
exit(0);
}
for(i=1; fact=1; i<=n;i++)
fact* = i;
printf(“factorial = %ld “, fact);
}

8. Write a for loop to find the multiplication table of a number.


void main()
{
inti, n, result;
printf(“Enter a number \n”);
scanf(“%d”, &n);

for(i=1; i<=10;i++)
{
result = n * i;
printf(“%d * %d = %d\n”, n, i, result);
}
}

9. Write a for loop generate the fibonacci series


0 1 1 2 3 5 8 ---------- n

void main()
{ inti, n, first=0, second=1, third;
printf(“Enter the limit for fibonacci series\n”);
scanf(“%d”, &n);
printf(“Fibonacci series\n”);
printf(“0 1\t”);
for(i=3; i<=n;i++)
{
third = first + second;
printf(“%d\t”, third);
first = second;
second = third;
}
}
C programming for Problem Solving - 18CPS13/23

Nested for loop


Use of one for loop within another is called as nesting of for loop.
C programming for Problem Solving - 18CPS13/23

i for loop is executed thrice (3 times) ----- > from i = 1 to i = 3


j for loop is a nested loop. j for loop is executed twice (2 times) for each i for loop.
So, total no. of iterations = 3 * 2 = 6 times.

itha S, Dept of CSE, GAT


C programming for Problem Solving - 18CPS13/23

More examples on nested for loop

1. Output
inti , j; 1 1
for(i=1;i<=3;i++) 2 2
{ 3 3
for(j=1;j<=2;j++)
printf(“%d\t”, i) ;
printf(“\n”);
}

2. Output
inti , j , a = 10; 10 11 12
for(i=1;i<=4;i++) 13 14 15
{ 16 17 18
for(j=1;j<=3;j++) 19 20 21
printf(“%d\t”, a++);
printf(“\n”);
}

3. Output
inti , j ; 1
for(i=1;i<=4;i++) 1 2
{ 1 2 3
for(j=1;j< = i; j++) 1 2 3 4
printf(“%d\t”, j);
printf(“\n”);
}
C programming for Problem Solving - 18CPS13/23

4. inti , j ;
Write a nested for loopto generate the for(i=1;i<=4;i++)
following pattern {
* for(j=1;j< = i; j++)
* * printf(“*\t”);
* * * printf(“\n”);
* * * * }
inti , j ; Output
for(i=5;i>=1;i--)
{ 1 2 3 4 5
for(j=1;j< = i; j++) 1 2 3 4
printf(“%d\t”, j); 1 2 3
printf(“\n”); 1 2
} 1

do - while loop

Syntax :
Initialization
do
{
statement block
updation
} while(test condition) ;
Statement x;

Example

inti = 1; Output
do
{ 1 2 3 4 5 6 7 8 9 10
printf(“%d “, i);
i++;
}while(i<=10);

Comparison between while and do-while


inti = 1 ; inti = 1 ;
while(i>10) do
{ {
printf(“%d”, i); printf(“%d”, i);
i++; i++;
}
mitha S, Dept of CSE, GAT } while(i>10) ;
printf(“\nThank you”); printf(“\nThank you”);
C programming for Problem Solving - 18CPS13/23

Output
Thank you

S.N While Do - while


1 Pretest (entry controlled) loop Posttest (exit controlled) loop
2 Condition is checked first and if is true, Statement block is executed first. Then
statement block is executed. the condition is checked and if it is true,
loop continues.
3 Minimum no. of iterations is 0. Minimum no. of iterations is 1.
4 Syntax Syntax

5 Flowchart Flowchart
6 Example with output Example with output

Looping Applications
Summation
o to find the sum of numbers by taking initial value of the result as 0.
Powers
o to find the product of numbers by taking initial value of the result as 1.
Smallest and largest numbers

Other statements related to looping

• break
• continue
• goto

break
Used to break (exit) the loop – without executing statements which are after break statement.
Can be used with switch, for, while and do – while statements.
Programming in C &Data Structures - 15PCD13/23

Example for break statement

inti; Output
float a, b, c; Enter a and b
for(i=1;i<=4;i++) 52
{ c = 2.5
printf(“Enter a and b\n”); Enter a and b
scanf(“%f %f”, &a, &b); 15 3
if(b==0) c=5
{ Enter a and b
printf(“Invalid b\n”); 3 0
break; Invalid b
} Thank you
else
{
c = a/b;
printf(“c = %f\n”,c);
}
}
printf(“\nThank you”);

continue
Used to continue with the next iteration of the loop without executing statements which are after
continue.
Can be used with for, while and do – while statements.
Example for continue statement
inti; Output
float a, b, c; Enter a and b
52
for(i=1;i<=4;i++) c = 2.5
{ Enter a and b
printf(“Enter a and b\n”); 15 3
scanf(“%f %f”, &a, &b); c=5
if(b==0) Enter a and b
{ 30
printf(“Invalid b\n”); Invalid b
continue; Enter a and b
} 15 4

c = a/b;
C programming for Problem Solving - 18CPS13/23

goto
Used to perform a transfer of control from one statement to another in a program.

Example for goto statement

int a=1; Output :


st :
printf(“%d “, a); 1 2 3 4 5
a++; Thank you
if(a<=5)
gotost;
printf(“\nThank you”);

Rewrite the while code using goto Using goto statement


statement
inti = 50, sum=0; inti = 50, sum=0;
do st:
{ sum+=i;
sum+=i; i = i – 5;
i = i – 5; if(i>=0)
} while(i>=0); gotost;
printf(“sum=%d”, sum); printf(“sum=%d”, sum);

1. Write a program to generate prime numbers from 1 to n.


void main()
{
int n, i, j, c;
printf("Enter Range To Print Prime Numbers\n");
scanf("%d", &n);
printf("Prime Numbers are\n");
for(i=1;i<=n;i++)
{
c=0;
C programming for Problem Solving - 18CPS13/23

for(j=1;j<=i;j++)
{
if(i%j==0)
c++;
}
if(c==2)
printf("%d ",i);
}
}

2. For the given value of x and n, write a C program to evaluate the series
y = 1 + x + x2 + x3 + -------- + xn
#include<stdio.h>
#include<math.h>
void main()
{ float x, y;
inti, n;
printf(“Enter x and n values\n”);
scanf(“%f%d”, &x, &n);
for(i=0,y=0;i<=n;i++)
y = y + pow(x,i);
printf(“y = %f “, y);
}

3. Write a C program to find GCD of two non – zero integer numbers. If the first number is less than the
second, then the program must exchange the two numbers before computing the GCD.
#include<stdio.h>
void main( )
{
int num1,num2,num,den,rem,gcd;
printf("Enter two non-zero integers\n");
scanf("%d%d",&num1,&num2);
if(num1!=num2)
{
if(num1>num2)
{ num=num1;
den=num2;
}
else
{ num = num2;
den=num1;
}
rem=num%den;
while(rem!=0)
{
num=den;
den=rem;
rem=num%den;
}
gcd=den;
C programming for Problem Solving - 18CPS13/23

}
else
gcd=num1;
printf("\nGCDof given integers = %d", gcd);
}

4. Write a C program that will read the value of x and evaluate the following.
y = 1 + x when n = 1
y = 1 + xn when n = 2
y = 1 + nx otherwise
using (i) else if statement (ii) switch statement

else if statement switch statement


#include<stdio.h> #include<stdio.h>
#include<math.h> #include<math.h>
void main() void main()
{ {
float x, y; float x, y;
int n; int n;
printf(“Enter values of x and n\n”); printf(“Enter values of x and n\n”);
scanf(“%f %d”, &x, &n); scanf(“%f %d”, &x, &n);
if(n==1) switch(n)
y = 1 + x; {
else if(n==2) case 1 :
y = 1 + pow(x, n); y = 1 + x;
else break;
y = 1 + n*x; case 2 :
printf(“y = %f”, y); y = 1 + pow(x, n);
} break;
default :
y = 1 + n*x;
}
printf(“y = %f”, y);
}

5. Write a program to compute the value of Euler’s number e , that is used as the base of natural
logarithm. Use the following formula. Use while statement.

#include<stdio.h>
void main()
{
float e=1.0 , acc = 0.0001, term=1.0;
inti = 1, den=1;
while(term>acc)
{
term = 1/den;
e+ = term ;
i++;
den = den * i ;
C programming for Problem Solving - 18CPS13/23

}
printf(“e = %f”, e);
}

6. Write a C program using switch statement to perform the following operations between two
variables. The operations are 1 – addition, 2 – subtraction, 3 – multiplication , 4 – division. Print
error message for default statement.
#include<stdio.h>
#include<math.h>
void main()
{ float a, b, c ;
int n;
printf(“Enter 2 numbers\n”);
scanf(“%f%f”, &a, &b);
printf(“1. addition\n2. subtraction\n3. multiplication\n4. division\n”);
printf(“enter choice\n”);
scanf(“%d”, &n);
switch(n)
{
case 1 :
c = a + b;
printf(“sum = %f”, c);
break;
case 2 :
c = a - b;
printf(“difference = %f”, c);
break;
case 3 :
c = a * b;
printf(“product = %f”, c);
break;
case 4 :
if(b==0)
exit(0);
c = a / b;
printf(“quotient = %f”, c);
break;
default :
printf(“Invalid choice”);
}
}
C programming for Problem Solving - 18CPS13/23

Question paper questions

1. What is two way selection statement? Explain if, it-else, nested if else and cascaded if else with
examples and syntax
2. Write a program that takes three coefficients (a, b, and c) of a quadratic equation: (ax2 + bx + c) as
input and compute all possible roots and print them with appropriate messages.
3. Explain switch statement with an example.
4. What is a loop? Explain the different loops in C language.
5. Show how break and continue statements are used in a C program, with example.
6. What are different types of conditional decision making statements? Explain each with examples.
7. Write a C program to simulate simple calculator that performs arithmetic operations using switch
statement. Error message should be displayed, if any attempt is made to divide by zero.
8. List four differences between while loop and do-while loop along with syntax and example.
9. Design and develop a C program to reverse a given four digit integer number and check whether it is a
palindrome or not.
10. Explain the, syntax of do-while statement. Write a C program to find the factorial of number using do-
while, where the number n is entered by user.
11. What is two way selection statement? Explain if, if else, and cascaded if-else with examples.
12. Write a C program that takes from user an arithmetic operator ('+', '-','*' or '/') and two operands.
Perform the corresponding arithmetic operation on the operands using switch statement
13. Explain the ELSE - IF ladder with syntax & example.
14. List the types of loops. Explain the working of any one type of loop with syntax and example.
15. Write a program to read a year as input and find whether it is a LEAP YEAR or not.
16. Explain SWITCH statement with syntax and example.
17. Differentiate between while and do - WHILE loops.
18. Write a program to find reverse of a number and check whether it is a palindrome or not.

You might also like