0% found this document useful (0 votes)
54 views100 pages

L10-L13-Decision Making, Branching and Looping

Uploaded by

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

L10-L13-Decision Making, Branching and Looping

Uploaded by

Rugved Joshi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 100

Decision Making,

Branching & Switch


L10- L11
Objectives

• To learn and appreciate the following concepts

• The if Statement
• The if-else Statement
• Nested if Statements
• The else if Ladder
• The switch Statement

11/06/2023 CSE 1001 Department of CSE 2


Outcome
• At the end of session student will be able to learn and
understand
• The if Statement
• The if-else Statement
• Nested if Statements
• The else if Ladder
• The switch Statement

11/06/2023 CSE 1001 Department of CSE 3


Control Structures
A control structure refers to the order of executing the program
statements.
The following three approaches can be chosen depending on the problem
statement:

Sequential (Serial)
 In a Sequential approach, all the statements are executed in the same
order as it is written.

Selectional (Decision Making and Branching)


 In a Selectional approach, based on some conditions, different set of
statements are executed.

Iterational (Repetition)
 In an Iterational approach certain statements are executed repeatedly.

CSE 1001 Department of CSE 4


11/06/2023
DECISION MAKING AND BRANCHING
C++ decision making and branching statements are:

1. if statement
2. switch statement

CSE 1001 Department of CSE 5


11/06/2023
Different forms of if statement
1. Simple if statement.

2. if…else statement.

3. Nested if…else statement.

4. else if ladder.

11/06/2023 CSE 1001 Department of CSE 6


Simple if Statement

General form of the simplest if statement:

if (test Expression)
{ If expression is true
statement-block; (non-zero), executes
} statement.
next_statement;It gives you the choice
of executing
statement or skipping
it.

11/06/2023 CSE 1001 Department of CSE 7


if Statement- explanation
 (test Expression) is first evaluated.

 If TRUE (non-zero), the ‘if’ statement block is executed.

 If FALSE (zero) the next statement following the if statement block is


executed.

 So, during the execution, based on some condition, some


code will not be executed (skipped).

For example: bonus = 0;


if (hours > 70)
bonus = 10000;
salary= salary + bonus;

11/06/2023 CSE 1001 Department of CSE 8


Flow chart of simple if
Entry

11/06/2023 CSE 1001 Department of CSE 9


Find out whether a number is even or odd.
#include <stdio.h>
int main()
{
int x;
printf(“input an integer\n”);
scanf(“%d”,&x);
if ((x % 2) == 0)
{
printf(“It is an even number\n”);
}
if ((x%2) == 1)
{
printf(“It is an odd number\n”);
}
return 0;
10
} 11/06/2023 CSE 1001 Department of CSE
Example - if
// Program to calculate the absolute value of an integer

int main ()
{
int number;
printf(“Type in your number: “);
scanf(“%d”,&number);
if ( number < 0 )
number = -number;
printf(“The absolute value is”);
printf(“%d”,number);
return 0;
}

11/06/2023 CSE 1001 Department of CSE 11


The if-else statement

if (test expression )
{
statement _block1 if-else
} statement:
else enables you to
{ choose between
statement _block2 two statements
}
Next_statement

11/06/2023 CSE 1001 Department of CSE 12


if-else statement
Explanation:
1.First ,the (test expression) is evaluated.

2.If it evaluates to non-zero (TRUE), statement_1 is executed,


otherwise, if it evaluates to zero (FALSE), statement_2 is executed.

3.They are mutually exclusive, meaning, either statement_1 is


executed or statement_2, but not both.

4.If the statements_ 1 and statements_ 2 take the form of block ,


they must be put in curly braces.

Example: if(job_code == 1)
rate = 7.00;
else
rate = 10.00;
prinf(“%d”,rate);
11/06/2023 CSE 1001 Department of CSE 13
The if-else statement

yes no
expression

Program statement 1 Program statement 2

Next _statement

11/06/2023 CSE 1001 Department of CSE 14


Find out whether a number is even or odd.
#include <stdio.h>
int main()
{
int x;
printf(“Input an integer\n”);
scanf(“%d”,&x);
if ((x % 2) == 0)
{
printf(“It is an even number\n”);
}
else
{
printf(“It is an odd number\n”);}
return 0;
11/06/2023
} CSE 1001 Department of CSE 15
WAP to find largest of 2 numbers

#include<stdio.h>
int main()
{
int a, b;
printf(“Enter 2 numbers\n”);
scanf(“%d %d”,&a,&b);
if(a > b)
a;
printf(“Large is %d\t“,a);
else
else
cout<<"large is "<<fb;
printf(“Large is %d\t“,b);
return 0;
}

11/06/2023 CSE 1001 Department of CSE 16


Attention on if-else syntax !
if ( expression )
program
statement 1
In C++, the ; is
else part (end) of a
program statement !
statement 2
if ( remainder == 0 )
printf("The number is even.\n“);
else
printf(“The number is odd.\n“);

Syntactically OK (void
statement on if) but a
semantic error !
if ( x == 0 );
printf(“The number is zero.\n“);

11/06/2023 CSE 1001 Department of CSE 17


Example: determine if a year is a leap
year
#include<stdio.h>
int main() A leap year is
{ exactly divisible
int year; by 4 except for
printf(“Enter the year“);
century years
scanf(“%d”,&year);
if(year%4 == 0) (years ending
{ with 00). The
if( year%100 == 0) century year is
{ a leap year only
if ( year%400 == 0) if it is perfectly
printf("%d is a leap year",year); divisible by 400.
else
printf("%d is not a leap year",year);
} else printf("%d is a leap year",year);
} else printf("%d is not a leap year",year);
return 0;
}
11/06/2023 CSE 1001 Department of CSE 18
Testing for character ranges
Output:
enter a
#include<stdio.h> character:
int main() C
{ uppercase char
char ch; special char
printf(“enter a character\n”);
scanf(“%c”,&ch); enter a
if (ch >= 'a' && ch <= 'z') character:
printf(“lowercase char\n“); j
if (ch >= ‘A' && ch <= ‘Z') lowercase char
printf(“uppercase char\n“); special char
if (ch >= ‘0' && ch <= ‘9')
enter a
printf(“digit char\n“);
character:
else
5
printf(“ special char\n”);
digit char
return 0;
}
11/06/2023 CSE 1001 Department of CSE 19
Testing for ranges

if (x >= 5 && x <= 10)


printf(“in range“);

if (5 <= x <= 10)


printf(“in range“);

11/06/2023 CSE 1001 Department of CSE 20


Testing for ranges

if (x >= 5 && x <= 10)


printf(“in range“);

if (5 <= x <= 10)


printf(“in range“);

Syntactically correct, but semantically an error !!!

Because the order of evaluation for the <= operator is left-to-right, the
test expression is interpreted as follows:
(5<= x) <= 10
The subexpression 5 <= x either has the value 1 (for true) or 0 (for
false). Either value is less than 10, so the whole expression is always
true, regardless of x !

11/06/2023 CSE 1001 Department of CSE 21


Nested if-else Statement

11/06/2023 CSE 1001 Department of CSE 22


If-else nesting -Explanation
1. The if-else constructs can be nested (placed one within another)
to any depth.
2. In this nested form, expression_1 is evaluated.
 If it is zero (FALSE-F), statement_4 is executed and the entire
nested if statement is terminated;
 If not (TRUE-T), control goes to the second if (within the first if)
and expression_2 is evaluated. If it is zero, statement_3 is
executed;
 If not, control goes to the third if (within the second if) and
expression_3 is evaluated.
 If it is zero, statement_2 is executed;
 If not, statement_1 is executed. The statement_1 (inner most)
will only be executed if all the if statement is true.

11/06/2023 CSE 1001 Department of CSE 23


Smallest among three numbers
if (a < b)
#include <stdio.h> { if (a < c)
int main() { smallest = a; }
{ else
int a, b, c, smallest; { smallest = c; }
}
else
printf(“Enter a, b & c\n“);
{ if (b < c)
scanf(“%d %d %d, &a,&b,&c); { smallest = b; }
else
{ smallest = c; }
}
printf(“Smallest is %d“,smallest);
return 0;
}
11/06/2023 CSE 1001 Department of CSE 24
Nested if statements

if (number > 5)
if (number < 10)
printf(“1111\n“);
else printf(“2222\n“);
Rule: an else
goes with the
if (number > 5) {
most recent if,
if (number < 10)
unless braces
printf(“1111\n“);
indicate
}
otherwise
else printf(“2222\n“);

11/06/2023 CSE 1001 Department of CSE 25


The else-if ladder
if (Expression_1 )
{
statement _block1
}
else if (Expression_2)
{
statement _block2
}
…….
else if (Expression_n)
{
statement _blockn
}
else
{
last_statement
}

Next_statement
11/06/2023 CSE 1001 Department of CSE 26
else if ladder -Explanation
 expression_1 is first evaluated. If it is TRUE, statement_1 is
executed and the whole statement terminated and the
next_statement is executed.
 On the other hand, if expression_1 is FALSE, control passes to the
else if part and expression_2 is evaluated.
 If it is TRUE, statement_2 is executed and the whole system is
terminated.
 If it is False, other else if parts (if any) are tested in a similar way.
 Finally, if expression_n is True, statement_n is executed; if not,
last_statement is executed.
 Note that only one of the statements will be executed others will be
skipped.
 The statement_n’s could also be a block of statement and must be
put in curly braces.

11/06/2023 CSE 1001 Department of CSE 27


else-if ladder Flow of control

True False
Condition-1

True False
statement-1 Condition-2

True False

statement-2 Condition-3

True False
statement-3
Condition-n

statement-n

default statement

next statement

11/06/2023 CSE 1001 Department of CSE 28


Testing for character ranges
#include<stdio.h>
int main()
{
char ch;
printf(“enter a character\n”);
scanf(“%c”,&ch);
if (ch >= 'a' && ch <= 'z')
printf(“lowercase char\n“);
else if (ch >= ‘A' && ch <= ‘Z')
printf(“uppercase char\n“);
else if (ch >= ‘0' && ch <= ‘9')
printf(“digit char\n“);
else
printf(“ special char\n”);
return 0;
}
11/06/2023 CSE 1001 Department of CSE 29
WAP using else-if ladder to calculate grade for the
marks entered
int main() {
char cgrade;
int imarks;
printf("enter marks“);
For inputs
scanf(“%d”,&imarks); imarks= 46
if(imarks>79)
if(imarks>79)
grade = D
imarks= 64
cgradecgrade
= 'A'; = 'A'; grade = B
else ifelse if (imarks>59)
(imarks>59)
cgradecgrade
= 'B'; = 'B';
else if (imarks>49)
else cgrade
if (imarks>49)
= 'C';
else if (imarks>39) cgrade = 'C';
else cgrade
if (imarks>39)
= 'D';
else cgrade = 'D';
cgrade = 'F';
else
cgrade = 'F';
printf(“Grade :%c\n”,cgrade);
11/06/2023 return 0; CSE 1001 Department of CSE 30

}
Example: else-if
// Program to implement the sign function

#include <stdio.h>
int main ( )
{
int number, sign;
printf("Please type in a number: “);
scanf(“%d”,&number);
if ( number < 0 )
sign = -1;
else if ( number == 0 )
sign = 0;
else // Must be positive
sign = 1;
printf(“Sign = %d“,sign);
return 0;
}
11/06/2023 CSE 1001 Department of CSE 31
Example – multiple choices
/* Program to evaluate simple expressions of the form number operator number */
#include <stdio.h>
int main ( )
{
float value1, value2,result;
char operator;
printf("Type in your expression.\n“);
scanf(“%f %c %f”, &value1,&operator,&value2);
if ( operator == '+' )
{result=value1+value2;
printf(“%f”,result);}
else if ( operator == '-' )
{result=value1-value2;
printf(“%f”,result);}
else if ( operator == '*' )
{result=value1*value2;
printf(“%f”,result);}
else if ( operator == '/' )
{result=value1/value2;
printf(“%f”,result);}
else
printf("Unknown operator.\n“);
11/06/2023
return 0; CSE 1001 Department of CSE 32
}
Problem…

11/06/2023 CSE 1001 Department of CSE 33


Find the roots of Quadratic equation using if-else statement

else if (disc==0)
#include<stdio.h> {
int main() printf(“Real & equal roots“);
{ re=-b / (2*a);
float a,b,c,root1,root2,re,im, disc;
scanf(“%f %f %f”,&a,&b,&c); printf(“Root1 and root2 are
disc=b*b-4*a*c; %.21f”,re);
}
if (disc<0)
{ else /*disc > 0 */
printf("imaginary roots\n“); {
re= - b / (2*a); printf(“Real & distinct roots“);
im = pow(fabs(disc),0.5)/(2*a); printf(“Roots are“);
printf(“root1=%.21f+%.21fi and
root2 =%.21f-%.2fi”, re,im,re,im); root1=(-b + sqrt(disc))/(2*a);
} root2=(-b - sqrt(disc))/(2*a);
printf(“Root1 = %.21f and root2 =
%.21f”,root1,root2);
}
return 0;
}
11/06/2023 CSE 1001 Department of CSE 34
The switch Statement

 Switch is multiple–branching statement where based on a


condition, the control is transferred to one of the many possible
points.

 Enables the program to execute different statements based on


an expression that can have more than two values. Also called
multiple choice statements.

11/06/2023 CSE 1001 Department of CSE 35


The switch statement
switch ( expression )
{ The expression is
case value1: successively compared
program statement against the values value1,
program statement value2, ..., valuen. If a case is
... found whose value is equal
break; to the value of expression,
case value2: the program statements that
program statement follow the case are executed.
program statement
...
break;
case value n: The switch test expression must be one
program statement with an integer value (including type
program statement
char) (No float !).
...
break; The case values must be integer-type
default: constants or integer constant
program statement expressions (You can't use a variable for
program statement a case label !)
...
}
11/06/2023 CSE 1001 Department of CSE 36
switch- control flow

11/06/2023 CSE 1001 Department of CSE 37


switch- example 1
#include<stdio.h>
int main()
{
int choice;
printf(“Enter your choice: 1-yes, 2-no\n”);
scanf(“%d”,&choice);
switch(choice)
{
case 1: printf(“YESSSSSSS……”);
break;
case 2: printf(“NOOOOOO……”);
break;
default: printf(“DEFAULT CASE…….”);
} printf(“The choice is %d”,choice);
return 0;
}
11/06/2023 CSE 1001 Department of CSE 38
switch- example 2
scanf(“%d”,&mark);

case 50:
switch (mark)
grade=‘C’
{
break;
case 100: case 40:
case 90: grade=‘D’
case 80: grade=‘A’; break;
break;
default: grade=‘F’;
case 70: break;
case 60: }
scanf(“%c”,&grade);
grade=‘B’;
break;

11/06/2023 CSE 1001 Department of CSE 39


An Example – switch case
char ch;
scanf)(“%c”,&ch;

switch(ch)
{
case ‘a’ : printf(“Vowel”);
break;
case ‘e’ : printf(“Vowel”);
break;
case ‘i’ : printf(“Vowel”);
break;
case ‘o’ : printf(“Vowel”);
break;
case ‘u’ : printf(“Vowel”);
break;
default: printf(“Not a Vowel”); }

11/06/2023 CSE 1001 Department of CSE 40


An Example – switch case
char ch;
scanf(“%c”,&ch);

switch(ch)
{
case ‘a’
case ‘e’
case ‘i’ :
case ‘o’ :
case ‘u’ : printf(“Vowel”);
break;
default: printf(“Not a Vowel”);
}

11/06/2023 CSE 1001 Department of CSE 41


Example - switch
/* Program to evaluate simple expressions case ‘*':
of the form value operator value */ result=value1*value2;
#include <stdio.h> printf(“%f”,result);
int main (void) break;
{ float value1, value2; case ‘/':
char operator; if ( value2 == 0 )
Int result; printf(“Division by zero.\
printf("Type in your expression.\n“); n“);
scanf(“%f %c %f”, else result=value1 / value2;
&value1,&operator,&value2); printf(“%f”,result);
switch (operator) break;
{case '+': default;
result=value1+value2; printf(“Unknown Operator”);
printf(“%f”,result); }
break; return 0;
case '-':
result=value1-value2; }
printf(“%f”,result);
break;
11/06/2023 CSE 1001 Department of CSE 42
What is the output of the following code snippet?

int iNum = 2;
switch(iNum)
{
case 1:
printf(“ONE”);
break;
case 2:
printf(“TWO”);
break;
case 3:
printf(“THREE”);
break;
default:
printf(“INVALID”);
break;
}

11/06/2023 CSE 1001 Department of CSE 43


What is the output of the following code snippet?

iNum = 2;
switch(iNum)
{
default:
printf(“INVALID”);
case 1:
printf(“ONE”);
case 2:
printf(“TWO”);
break;
case 3:
printf(“THREE”;)
}

11/06/2023 CSE 1001 Department of CSE 44


What is the output of the following code snippet?

switch (iDepartmentCode)
{
case 110 : printf(“HRD ”);
case 115 : printf(“IVS ”);
case 125 : printf(“E&R ”);
case 135 : printf(“CCD ”);
} IVS E&R CCD

Assume iDepartmentCode is 115


find the output ?

11/06/2023 CSE 1001 Department of CSE 45


What is the output of the following code snippet?
int iNum = 2;
switch(iNum)
{
case 1.5:
printf(“ONE AND HALF”);
break;
case 2:
printf(“TWO”);
case ‘A’ :
printf(“A character”);
}

11/06/2023 CSE 1001 Department of CSE 46


Problem: Find the roots of Quadratic equation using switch statement
#include<stdio.h>
int main()
{
Int d;
float a,b,c,root1,root2,re,im, disc;
printf(“Enter the values of a, b & c:“);
scanf(“%f %f %f”,&a,&b,&c);
disc=b*b-4*a*c;
printf("\nDiscriminant= %f“,disc);

if(disc<0) d=1;
if(disc==0) d=2;
if(disc>0) d=3;
switch(d)
{
case 1:
printf("imaginary roots\n“);
re= - b / (2*a);
im = pow(fabs(disc),0.5)/(2*a);
printf(“root1=%.21f+%.21fi and root2 =%.21f-%.2fi”, re,im,re,im);
break;

11/06/2023 CSE 1001 Department of CSE 47


case 2:
printf(“Real & equal roots“);
re=-b / (2*a);
printf(“Root1 and root2 are %.21f”,re);
break;
case 3:
printf(“Real & distinct roots“);
printf(“Roots are“);
root1=(-b + sqrt(disc))/(2*a);
root2=(-b - sqrt(disc))/(2*a);
printf(“Root1 = %.21f and root2 =%.21f”,root1,root2);
break;
} // end of switch
return 0;
} //End of Program

11/06/2023 CSE 1001 Department of CSE 48


Some guidelines for writing switch case statements

(1) Order the cases alphabetically or numerically – improves


readability.
(2) Put the normal cases first ; put the exceptional cases later.
(3) Order cases by frequency:-put the most frequently executed
cases first and the least frequently used cases later.
(4) Use default case to detect errors and unexpected cases [user
friendly messages].

11/06/2023 CSE 1001 Department of CSE 49


Flow of control in various control structures

11/06/2023 CSE 1001 Department of CSE 50


• Summary
• The if Statement
• The if-else Statement
• Nested if Statements
• The else if Ladder
• The switch Statement

11/06/2023 CSE 1001 Department of CSE 51


Loop Control Structures

L12-L13
O b j e c ti v e s
• To learn and appreciate the following concepts

• The for Statement


• Nested for Loops
• for Loop Variants
• The while Statement
• The do Statement
• The break Statement
• The continue Statement
• Typedef and Enum

11/06/2023 CSE 1001 Department of CSE 53


• At the end of session student will be able to learn and understand
• The for Statement
• Nested for Loops
• for Loop Variants
• The while Statement
• The do Statement
• The break Statement
• The continue Statement
• Typedef and Enum

11/06/2023 CSE 1001 Department of CSE 54


Controlling the program flow
• Forms of controlling the program
flow:
– Executing a sequence of statements
– Using a test to decide between
alternative sequences (branching) Statement1
Statement2
– Repeating a sequence of statements Statement3
(until some condition is met) Statement4
(looping) Statement5
Statement6
Statement7
Statement8

11/06/2023 CSE 1001 Department of CSE 55


Program Looping
• A set of statements that executes repetitively for a number of
times.
• Simple example: displaying a message 100 times:

printf(hello !\n”);
printf(hello !\n”)
printf(hello !\n”)

Repeat 100 times
printf(hello !\n”)
printf(hello !\n”)
printf(hello !\n”)

Program looping: enables you to develop concise programs containing


repetitive processes that could otherwise require many lines of code !

11/06/2023 CSE 1001 Department of CSE 56


The need for program looping

Example problem: computing triangular numbers.


(The n-th triangular number is the sum of the integers from 1 through
n)
#include <stdio.h>
int main (void)
{
int triangularNumber;
triangularNumber = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8;
printf(“The eighth triangular number is
%d“,triangularNumber);
return 0;
}

What if we have to compute the 200-th (1000-th, etc) triangular number ?

We have 3 different statements for looping.


11/06/2023 CSE 1001 Department of CSE 57
Iterative (loop) control structures
 Three kinds of loop control structures:
 while
 do while
 for

11/06/2023 CSE 1001 Department of CSE 58


Iterative (loop) control structures
 Each loop control structure will have
 Program loop: body of loop.
 control statement  tests certain conditions & then directs repeated
execution of statements within the body of loop.

 Two types: Based on position of control statement.

1) Entry controlled loop: control is tested before the start of the loop. If
false, body will not be executed.

2) Exit controlled loop: test is performed at the end of the body. i.e. body
of loop executed at least once.

11/06/2023 CSE 1001 Department of CSE 59


Entry Controlled & Exit controlled loops
Entry
Entry

Test False
Body of
Condition
The loop

True

Body of
True
The loop Test
Condition

False

11/06/2023 CSE 1001 Department of CSE 60


Example – 200th triangular number
Statement before triangularNumber = 0
loop

init_expression n=1

no
loop_condition n<=200

yes
triangularNumber =
Statement(s) triangularNumber + n

loop_expression n=n+1

Statement after loop Print triangularNumber

11/06/2023 CSE 1001 Department of CSE 61


while-statement
General format:

while (test expression)


{
Note: braces optional if
body of the loop only one statement.
}

Entry controlled loop statement.


Test condition is evaluated & if it is true, then body of the loop is executed.
This is repeated until the test condition becomes false, & control transferred
out of the loop.
Body of loop is not executed if the condition is false at the very first attempt.
While loop can be nested.

11/06/2023 CSE 1001 Department of CSE 62


The while statement

while ( expression )
program statement Loop with the
test in the
beginning !
statement before loop Body might
never be
executed !

3 1 Loop_expression 4
No
yes
2 statement (s)

Next statement

11/06/2023 CSE 1001 Department of CSE 63


Finding sum of natural numbers up to 100

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


int main() int main()
{
{ int n;
int n; int sum;
int sum; sum=0; //initialize
sum=0; //initialize sum sum
n=1;
while (n < 100)
for(n = 1; n < 100; n=n + 1) {
{ sum= sum + n;
sum=sum + n; n = n + 1;
} }
printf(“%d”,sum);
printf(“%d”,sum); return 0;
return 0; }
}

11/06/2023 CSE 1001 Department of CSE 64


Program to reverse the digits of a number
#include <stdio.h>
int main()
{
int number, rev=0, right_digit;

printf(“Enter your number.\n“);


scanf(“%d”,&number);

while ( number != 0 )
{
right_digit = number % 10;
rev=rev*10 + right_digit;
number = number / 10;
}
printf(“The reversed number is %d“, rev);
return 0;
}
11/06/2023 CSE 1001 Department of CSE 65
The do – while statement
General form:
do
{
body of the loop
}
while(test condition);

Exit controlled loop. At the end of the loop, the test condition is evaluated.
After do statement, program executes the body of the Loop.
Then, the condition is tested, if it is true, body of the loop is executed once again
& this process continues as long as the condition is true.
Body of the loop is executed at least once.
do-while loop can be nested.

11/06/2023 CSE 1001 Department of CSE 66


The do statement
do
program
statement
while Loop with the
( loop_expression ); test at the end !
Body is
executed at least
once !
3 1 Statement(s)

yes
loop_expression
2
No

Next statement 4

11/06/2023 CSE 1001 Department of CSE 67


Example: Finding sum of natural numbers
up to 100

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


int main() int main()
{
{
int n;
int n; int sum =0;
int sum=0;
n=1;
n=1; while (n<=100)
dodo {
{{ sum=sum+n;
sum = sum + n; n = n +1;
sum = sum + counter; }
n = n +1;
} counter
while (n=<counter
=100); +1;}} printf(“%d”,sum);
} while (counter < 100); return 0;
printf(“%d”,sum); }
return 0;
11/06/2023
} CSE 1001 Department of CSE 68
Program to reverse the digits of a number

#include <stdio.h>
int main()
{
int number, rev=0, right_digit;

printf(“Enter your number.\n“);


scanf(“%d”,&number);

do
{
right_digit = number % 10;
rev=rev*10 + right_digit;
number = number / 10;
}
while ( number != 0 );

printf(“The reversed number is %d“,rev);


return 0;
}
11/06/2023 CSE 1001 Department of CSE 69
The ‘for’ loop
for ( init_expression; loop_condition; loop_expression )
{ program statement(s)
}

1 init_expression

no
5 2 loop_condition

yes

3 Program statement

4 Loop expression

Next Statement

11/06/2023 CSE 1001 Department of CSE 70


How for works
• The execution of a for statement proceeds as follows:
1. The initial expression is evaluated first. This expression usually sets a
variable that will be used inside the loop, generally referred to as an
index variable, to some initial value.
2. The looping condition is evaluated. If the condition is not satisfied (the
expression is false – has value 0), the loop is immediately terminated.
Execution continues with the program statement that immediately
follows the loop.
3. The program statement that constitutes the body of the loop is executed.
4. The looping expression is evaluated. This expression is generally used to
change the value of the index variable
5. Return to step 2.

11/06/2023 CSE 1001 Department of CSE 71


The for statement
sum = 0;

no

1 2 5 4
for ( n = 1; nyes
<= 200; n = n + 1 );
{ 3 sum = sum + n; }

Next Statement
for ( init_expression; loop_condition; loop_expression )
{ program statement(s)
}

11/06/2023 CSE 1001 Department of CSE 72


Finding sum of natural numbers up to 100

#include <stdio.h>
int main()
{
int n;
int sum;
sum=0; //initialize sum

for(n = 1; n <=100; n=n + 1)


{
sum=sum + n;
}
printf(“%d”,sum);
return 0;
}

11/06/2023 CSE 1001 Department of CSE 73


Infinite loops
• It’s the task of the programmer to design correctly the algorithms so
that loops end at some moment !
// Program to count 1+2+3+4+5
#include <stdio.h>
int main()
{
What is wrong here ?
int i, n = 5, sum =0; Does the loop end?
for ( i = 1; i <= n; n = n + 1 )
{
sum = sum + i;
printf(“%d”,sum);
}
return 0;
}

11/06/2023 CSE 1001 Department of CSE 74


Example – for with a body of 2 statements

// Program to generate a table of triangular numbers

#include <stdio.h>
int main()
{
int n, triangularNumber=0;

printf(“TABLE OF TRIANGULAR NUMBERS\n\n“);


printf(“Sum from 1 to n\n“);

for ( n = 1; n <= 10; n++ )


{
triangularNumber += n;
printf(“The %d th triangular number is %d\
n”,n,triangularNumber);
}
return 0;
}

11/06/2023 CSE 1001 Department of CSE 75


Nesting of for loop
One for statement can be nested within another for statement.

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


{ …..
….
for (j=0; j < n;++j)
{
Statement S;
} // end of inner ‘for’ statement
}// end of outer ‘for’ statement

11/06/2023 CSE 1001 Department of CSE 76


Nested loops
#include <stdio.h>
int main()
{
int n, number, triangularNumber=0, counter;

for ( counter = 1; counter <= 5; counter++ )


{
printf(“What triangular number do you want? “);
scanf(“%d”,&number);

for ( n = 1; n <= number; n++ )


triangularNumber = triangularNumber + n;

printf(“The %d th triangular number is %d:”,n-1,triangularNumber);


}
return 0;
} Remember indentations!

11/06/2023 CSE 1001 Department of CSE 77


Example: Multiplication table for ‘n’ tables up to ‘k’ terms

scanf(“%d %d”,&n,&k);
Enter n & k values: 3 5
The table for 3 X 5 is
for (i=1; i<=k; i++) 1 * 1= 1 2 * 1= 2 3 * 1= 3
{ 1 * 2= 2 2 * 2= 4 3 * 2= 6
1 * 3= 3 2 * 3= 6 3 * 3= 9
for (j=1; j<=n; j++) 1 * 4= 4 2 * 4= 8 3 * 4= 12
{ 1 * 5= 5 2 * 5= 10 3 * 5= 15
prod = i * j;
printf(“%d * %d = %d\t”, j,i,prod);
}
printf(“\n”);
}

11/06/2023 CSE 1001 Department of CSE 78


for loop variants
• Multiple expressions (comma between…)
for(i=0 , j=10 ; i<j ; i++ , j--)

• Omitting fields (semicolon have to be still…)


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

• Declaring variables
for(int i=0 ; i=10 ; i++ )

11/06/2023 CSE 1001 Department of CSE 79


Which loop to choose ?
• Criteria: category of looping
• Entry-controlled loop -> for, while
• Exit-controlledloop -> do

• Criteria: Number of repetitions:


• Indefinite loops ->while
• Counting loops -> for

• You can actually rewrite any while as a for and vice versa !

11/06/2023 CSE 1001 Department of CSE 80


The break Statement
• Used in order to immediately exit from a loop

• After a break, following statements in the loop body are


skipped and execution continues with the first statement after
the loop

• If a break is executed from within nested loops, only the


innermost loop is terminated

11/06/2023 CSE 1001 Department of CSE 81


Exiting a loop with break statement

while (……….) do
{……. {…….
………… …………
If(condition) If(condition)
break; break;
……… ………
Exit Exit
From ………. From ……….
loop loop
} // end of while } while(…);
………… //next ………….. // next

statement statement

11/06/2023 CSE 1001 Department of CSE 82


Exiting a loop with break statement

for (……….)
for {…….
{……. for(……..)

………… { ………
If(condition)
If(condition)
break;
break;
… stmts of inner loop;
Exit
……… } // inner for loop ends
From
loop ………. Exit ….stmts of outer loop;
From
} inner } // outer for loop ends
……next Stmts; loop …… next Stmts;

11/06/2023 CSE 1001 Department of CSE 83


Check whether given number is prime or not

int j, prime=1;
scanf(“%d”,&N);
for( int j=2; j<N; j++ )
{
if( (N % j) == 0)
{
prime=0;
break; /* break out of for loop */
}
}
if (prime == 1)
printf(“%d is a prime no”,N);
else
printf(“%d is a not a prime no”,N);

11/06/2023 CSE 1001 Department of CSE 84


Program to generate prime numbers between given 2 limits

scanf(“%d %d”,&m,&n);

for( int i=m; i<=n; i++)


{
int prime=1;
for( int j=2; j<i; j++ )
{
if( i % j == 0)
{
prime=0;
break; /* break out of inner loop */
}
}
if (prime == 1) printf(“%d\t”,i);
}
11/06/2023 CSE 1001 Department of CSE 85
Skipping a part of loop-continue statement
Skip a part of the body of the loop under certain conditions is done using continue
statement.

As the name implies, continue causes the loop to be continued with next iteration,
after skipping rest of the body of the loop.
while (……….) do
{ {
Statement-1; Statement-1;
Statement-2; Statement-2;

If(condition) If(condition)
continue; continue;

Statement-3; Statement-3;
Statement-4; Statement-4;
} } while(…);

Next_statement Next_statement

11/06/2023 CSE 1001 Department of CSE 86


Skipping a part of loop - example

for(i=10; i<=15; i++ )


{
if(i==13 || i==14)
continue;
10 11 12 15

printf(“%d\t”,i);
}

11/06/2023 CSE 1001 Department of CSE 87


Skipping a part of loop

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


{
for ( j = 1 ; j <= 2 ; j++ )
{
if ( i == j ) 1 2
continue ; 2 1

printf(“\n %d\t %d\n”,i, j);


}
}

11/06/2023 CSE 1001 Department of CSE 88


User defined Type declarations
 typedef
 Type definition - lets you define your own identifiers.

 enum
 Enumerated data type - a type with restricted set of values.

11/06/2023 CSE 1001 Department of CSE 89


User defined Type Declaration
 typedef type identifier;
The “type” refers to an existing data type and “identifier” refers to the
new name given to the data type.

 After the declaration as follows:


typedef int marks;
typedef float units;
we can use these to declare variables as shown
marks m1,m2 ; //m1 & m2are declared as integer variables
units u1, u2; //u1 & u2 are declared as floating point variables
The main advantage of typedef is that we can create meaningful data type
names for increasing the readability of the program.

11/06/2023 CSE 1001 Department of CSE 90


User defined Type Declaration - enum
enum identifier { value1, value2,..,valuen };

• Here, identifier is the name of enumerated data type or tag.


And value1, value2,....,valueN are values of type identifier.

• By default, value1 will be equal to 0, value2 will be 1 and so on but,


the programmer can change the default value.

enum card {club, diamonds, hearts, spades};

enum card {club=0, diamonds=10, hearts=20, spades=3};

11/06/2023 CSE 1001 Department of CSE 91


enum week { Monday =1, Tuesday,
Wednesday, Thursday,
Friday, Saturday, case Friday:
Sunday}; printf(“ Friday”);
printf( “ Enter n >1 &<7 and 0 for Exit“);
break;
scanf(“\d”,&n);
case Saturday:
switch(n) printf(“Saturday“);
{ break;

case Monday: case Sunday:


printf(“Monday”);
printf(“Sunday“);
break;
break;
case Tuesday: case 0:
printf(“Tuesday” ); exit(0);
break;
default:
case Wednesday: printf("\nInvalid
printf(“Wednesday”);
Entry. Enter 0-7.“);
break;

case Thursday: }
printf(“ Thursday“);
break;

CSE 1001 Department of CSE 92


11/06/2023
Program to find the factorial of a number
#include <stdio.h>
int main( )
{
int num, count, fact=1;

printf(“Enter a value for num : “);


scanf(“%d”,&num);

for(count = 1; count<=num; count ++)


fact = fact * count;
printf(“Factorial of %d is %d“,num,fact);

return 0;
}

11/06/2023 CSE 1001 Department of CSE 93


Algorithm and Program for Fibonacci series

#include<stdio.h>
Algorithm : Fibonocci Series
int main()
Step 1 : Input Limit {
Step 2: First0,Second1 int first=0, second=1;
Step 3: print First int limit, next;
Step 4: WHILE Second < Limit
begin scanf(“%d”,&limit);
Print Second printf(“%d”,first);
Next First +
Second while(second < limit)
FirstSecond {
Second printf(“%d”,second);
Next next = first + second;
first = second;
end
second = next;
Step 5:[End of Algorithm] }
Stop return 0;
}
11/06/2023 CSE 1001 Department of CSE 94
Example: Convert binary to decimal
dec = bd*2n + bd*2n-1 + … + bd*21 + bd*20
e.g.-given n=101  1*22 + 0*21 + 1*20 = 5
-----------------------------------------------------------

int n, p=0, sum=0, k;


printf(“Enter a binary number : “);
scanf(“%d”,&n);

do {
k=n%10; // binary number in n
sum= sum + k * pow(2,p);//decimal number in sum
p++;
n= n/10;
} while (n!=0);

printf(“Decimal Equivalent = %d“,sum);

11/06/2023 CSE 1001 Department of CSE 96


Count the even and odd digits in a given ‘n’ digit number

scanf(“%d”,&num);
while(num > 0)
{
rem=num%10; e.g.- num = 31467
num =num/10; OUTPUT
if(rem%2==0) 2 even & 3 odd
ecnt++; digits
else
ocnt++;
}

printf(“%d even & %d odd digits”,ecnt,ocnt);

11/06/2023 CSE 1001 Department of CSE 97


Check for palindrome

Palindrome (number)
n = num; e.g.- 121
while(num>0)
{
dig = num % 10;
rev = rev * 10 + dig;
num = num / 10;
}
if (n == rev)
printf(“\n\t GIVEN NO IS A PALINDROME“);
else
printf(“\n\t GIVEN NO NOT A PALINDROME“);

11/06/2023 CSE 1001 Department of CSE 98


Armstrong nos for a given limit ‘n’

scanf(“%d”,&lim); Armstrong Number


e.g. - 371
for(n=1;n<lim;n++)
∑ (cubes of digits )= number
{
sum = 0; 33 + 73 + 13 = 371
num = n;
while(num>0)
{
dig = num%10;
sum = sum+pow(dig,3);
num = num/10;
}
if(sum == n)
printf(“%d\n\t”,n);
}

11/06/2023 CSE 1001 Department of CSE 99


Tutorial Problems
• Write a C program to print all natural numbers from n-0 in reverse using
while loop
• Write a C program to count number of digits in any number
• Write a C program to find last and first digit of any number
• Write a C program to enter any number and print all its factors
• Write a C program to find LCM of two numbers
• Write a C program to convert Binary to Octal number

11/06/2023 CSE 1001 Department of CSE


100
• Summary
• The for Statement
• Nested for Loops
• for Loop Variants
• The while Statement
• The do Statement
• The break Statement
• The continue Statement
• Typedef and Enum

11/06/2023 CSE 1001 Department of CSE 101

You might also like