Introduction to Computers and
Programming (CSE 101)
Dr. Ruhul Amin,
Asst. prof., CSE
ICP-PART-5
Contd..
if(a>b) main(){
float a=0.5, b=0.7;
if(b>c) if(b<= 0.7)
s1 if(a<0.5)
printf(“IIIT”);
else s2
else
s2 will be executed if printf(“NR”);
else
printf(“CSE”); }
Output:
(a>b) Output:
(b<=c) NR
Contd.
int a=5,b=6; Main()
if(a=b) printf(“IIITNR”); { int a=10;
if(5==6)printf(“CSE”) printf(“%d”, 1+a++);
Output: Output:
IIITNR 11
CSE
Contd.
int main() { int main() {
if(printf("IIITNR")){ int i=107, x=5;
printf("CSE"); }} printf((x>7?”%d”: “%c”, i))
}
OUTPUT:
OUTPUT:
IIITNR
k
CSE
Contd.
a=5,b=6,c=7 Output:
if(a>b) if(a>b){
if(c>b) if(c>b) { printf(“ONE”);
{ else if(c==a)
printf(“ONE”); printf(“TWO”);
else else printf(“THREE”);}
if(c==a) printf(“TWO”); else printf(“FOUR”);
else printf(“THREE”); }
else printf(“FOUR”); FOUR
}
Contd.
#define print(int) printf(“%d”, int) OUTPUT:
main(){ 1
int x=2,y=1,z=9; 1
x= x&&y||z;print(x); 2
print(x||!y&&z); 0
X=y=1; 3
Z=x++ -1 print(x);print(z); 0
z+= -x++ + ++y print(x);print(z);
Motivation-Control statements
So far, the instructions were executed in the same
order in which they appeared within the program
Each instruction was executed only once.
a realistic C program may require that a logical test
be carried out at some particular point within the
program and group of instructions be executed
repeatedly
Control Statements
What do they do?
– Allow different sets of instructions to be executed
depending on the outcome of a logical test.
Whether TRUE or FALSE.
This is called branching.
Some applications may also require that a set of instructions
be executed repeatedly , possibly again based on some
condition.
– This is called looping.
How do we specify the conditions?
Using relational operators.
– Four relation operators: <, <=, >, >=
– Two equality operators: ==, !=
Using logical operators / connectives.
– Two logical connectives: &&, | |
– Unary negation operator: !
Examples
count <= 100
(math+phys+chem)/3 >= 60
(gender=’M’) && (age>=21)
(marks>=80) && (marks<90)
(balance>5000) || (no_of_trans>25)
!(grade=‘A’)
!((x>20) && (y<16)
The conditional operator ? : also makes use of an expression that is
either true or false
– status = (balance == 0) ? 'C' : '0'
The conditions evaluate to …
Zero
–Indicates FALSE.
Non-zero
– Indicates TRUE.
– Typically the condition TRUE is represented by
the value ‘1’.
Statements
[Link] statement
[Link]-else statement
[Link]-else-if statement
[Link] statement
Branching: The if Statement
Diamond symbol (decision symbol) - indicates decision is to
be made.
– Contains an expression that can be TRUE or FALSE.
– Test the condition, and follow appropriate path.
Single-entry / single-exit structure.
General syntax:
– if (condition) { …….. }
– If there is a single statement in the block, the braces can be omitted.
Branching: The if Statement
Syntax of if statement
if(test expression/condition)
{
Statement 1;
Statement 2;
…………….
Statement n
}
Statement x;
Example:
Ex-1:
if (grade>=60)
{
printf(“Passed \n”);
printf(“Good luck\n”);
}
Ex-2: Ex-3:
if (x <= 3.0)
if( x <0) printf("%f”, x ) ; {
y = 3 * pow(x, 2 ) ;
p r i n t f ( "%f\n", y) ;
}
Example
#include <stdio.h>
main()
{
int a,b,c;
scanf (“%d %d %d”, &a, &b, &c);
if ((a>=b) && (a>=c))
printf (“\n The largest number is: %d”, a);
if ((b>=a) && (b>=c))
printf (“\n The largest number is: %d”, b);
if ((c>=a) && (c>=b))
printf (“\n The largest number is: %d”, c);
}
Simple if
Branching: The if-else Statement
Also a single-entry / single-exit structure.
Allows us to specify two alternate blocks of statements, one of
which is executed depending on the outcome of the condition.
General syntax:
if (condition) { …… block 1 ……. }
else { …….. block 2 …….. }
If a block contains a single statement, the braces can be deleted.
Branching: The if-else Statement
if(test expression/condition)
{
Statement 1;
Statement 2;
…………….
Statement n;
}
else
{
Statement 1;
Statement 2;
…………….
Statement n;
}
Statement x;
Example:
if ( grade >= 60 )
printf ("Passed\n");
else
printf ("Failed\n");
If the expression has a nonzero value (i.e., if expression
is true), then statement1 will be executed. Otherwise
(i.e., if expression is false), statement 2will be executed.
Contd.
EX-2
if (x <= 3)
y = 3 * pow(x, 2 ) ;
EX-3
else
i f ( circle ) {
y = 2 * pow(x - 3 ) , 2 ) ;
scanf("%f", &radius);
printf ("%f\nu, balance) ;
area = 3.14159 * radius * radius;
p r i n t f ( " A r e a of c i r c l e = %fn”,area);
else {
scanf ( "%f %f”, &length, &width) ;
area = length * width;
printf ( " A r e a of rectangle = %f*,area);
}
If-else
Nesting of if-else Structures
It is possible to nest if-else statements, one within another.
All if statements may not be having the “else” part.
Nesting of if-else Structures
if(test expression/condition)
{
Statement block 1;
}
else if(test expression/condition)
{
Statement block 1;
}
else if(test expression/condition)
{
Statement block 1;
}
Else
{
Statement block 1;
}
Statement x;
Program Exercise
Write a program in C to find the smallest value among five
numbers using multiple if-else if required
Nested if
Program Exercise
1. Write a program to enter the marks of a student in four subjects.
Then, calculate the total, average and display the grade obtain
by the student. If the student scores average is greater than 75
percent, then the grade is distinction. If average is 60>= and
<75, then the grade is first division. If average is 50<= and <60,
then the grade is second division. If average is 40>= and <50,
then the grade is third division, else the grade is fail.
2. Write a program to test whether an entered number is divisible
by 3 or not.
3. Write a program to test whether an entered number is divisible
by 5 and 7 or not.
THE switch STATEMENT
The switch statement causes a particular group of statements
to be chosen from several available groups.
The selection is based upon the current value of an expression
which is included within the switch statement.
Syntax:
switch (expression) statement
where expression results in an integer value
– Note that expression may also be of type char, since individual
characters have equivalent integer values.
For each alternative, the first statement within the
group must be preceded by one or more case labels
Contd.
The keyword break should be included at the end of
each case statement.
In general, whenever a break statement is
encountered in C, it interrupts the normal flow of
control. In the switch statement, it causes an exit
from the switch.
The default clause is optional. The right brace at the
end marks the end of switch statement.
Switch Case
Simplified version of if-else block that evaluates only one variable.
Break and default keywords is used.
Syntax of Switch case
switch(variable)
{
Case 1:
Statement block;
break;
Case 2:
Statement block;
break;
……….
default:
Statement block;
break;
}
Statement x;
Example:
Syntax: switch (choice =toupper(getchar())) {
switch (integer expression) { case ‘R’ :
case constant1: printf("RED") ;
statement1; break;
break; case ‘W’:
case constant2: printf("WH1TE");
statement2; break;
break; case ‘B’ :
... printf(''BLUE");
default: break;
statement; default :
} printf("ERR0R");
Contd.
Example:
#include <stdio.h>
int main ()
{ int value; case 4:
switch(value) printf(“Value is 4 \n” );
{
break;
case 1:
printf(“Value is 1 \n” ); default :
break; printf(“Value is other than 1,2,3,4 \n” );
case 2: }
printf(“Value is 2 \n” );
return 0;
break;
case 3: }
printf(“Value is 3 \n” );
break;
Contd.
Advantages of switch case
1. Easy to debug (bugs means errors)
2. Easy to read and understand
3. Easy maintenance as compared to if-else
statement
4. Switch case statement can also be nested like if-
else
5. Execute faster than if-else statements
Note: Debugging is the process to detect and solve the errors.
Program Example of switch case
# include <stdio.h>
void main() {
char operator;
float firstNumber,secondNumber;
printf("Enter an operator (+, -, *,): ");
scanf("%c", &operator);
printf("Enter two operands: ");
scanf("%f %f",&fNum, &sNum);
switch(operator)
{
case '+':
printf("%f %f %f",fNum, sNum, fNum + sNum);
break;
Contd..
case '-':
printf("%f %f %f",fNum, sNum, fNum - sNum);
break;
case '*':
printf("%f %f %f",fNum, sNum, fNum * sNum);
break;
case '/':
printf("%f %f %f",fNum, sNum, fNum / sNum);
break;
// operator doesn't match any case constant (+, -, *, /)
default:
printf("Error! operator is not correct");
}
Exercise
Write a program to enter a number from 1-7 and display the corresponding day
of the week using switch case statement.
Some interesting fact about switch
case
The expression used in switch must be integral type ( int, char and
enum).
Some interesting fact about switch
case
All the statements following a matching case execute until a break
statement is reached.
Some interesting fact about switch
case
The default block can be placed anywhere.
Some interesting fact about switch
case
The statements written above cases are never executed
Some interesting fact about switch
case
Two case labels cannot have same value
Types of Repeated Execution
Loop: Group of instructions that are executed repeatedly while
some condition remains true.
Counter-controlled repetition:
– Definite repetition – know how many times loop will
execute.
– Control variable used to count repetitions.
Sentinel-controlled repetition:
– Indefinite repetition.
– Used when number of repetitions not known.
– Sentinel value indicates “end of data”.
Counter-controlled Repetition
Counter-controlled repetition requires:
– name of a control variable (or loop counter).
– initial value of the control variable.
– condition that tests for the final value of the control
variable (i.e., whether looping should continue).
– increment ( or decrement) by which the control variable
is modified each time through the loop.
– Example:
int count;
for( count=1; count<=100; count++)
printf("%d",count);
Counter Controlled Loop
Read 5 integers and display the value of their summation
Sentinel-controlled repetition
The type of loop where the number of execution of
the loop is unknown, is termed by sentinel
controlled loop.
do
{
printf(“Input a number.\n”);
scanf("%d", &num);
}
While(num>0)
LOOPING: THE while STATEMENT
The “while” statement is used to carry out looping
operations, in which a group of statements is executed
repeatedly, as long as some condition remains satisfied.
The while statement is typically used or sentinel-controlled repetition.
Contd.
Examples on while
int digit = 0; int weight=100;
while ( digit <= 9) while ( weight > 65 )
printf (“%d \n”, digit++) {
printf ("Go, exercise, ");
printf ("then come back. \n");
printf ("Enter your weight:");
scanf ("%d", &weight);
}
Example: Sum of N Natural
Numbers
main () {
int N, count, sum;
scanf (“%d”, &N) ;
sum = 0; count = 1;
while (count <= N)
{
sum = sum + count;
count = count + 1;
}
printf (“Sum=%d\n”, sum);
}
while
do-while Statement
Similar to “while”, with the difference that the check for continuation is
made at the end of each pass.
– The statement will be executed repeatedly, as long as the value of
expression is true
– Loop body is executed at least once.
– The statement can be either simple or compound,
Syntax:
do
{
statement_to_repeat
} while (condition );
Contd..
Single-entry /single-exit structure
do-while :: Examples
Ex-1
int digit = 0;
do Ex-2:
printf (“%d \n”, digit++); int weight;
while (digit <= 9); do {
printf ("Go, exercise, ");
printf ("then come back. \n");
printf ("Enter your weight: ");
scanf ("%d", &weight);
} while (weight > 65 ) ;
Consecutive Integer Quantities
0to 9
WHILE DO-WHILE
#include <stdio.h> #include <stdio.h>
main( ) { main( ) {
int digit = 0; int digit = 0;
while (digit<= 9) do
{ {
printf("%d\n", digit) ; printf('%d\n", digit++);
++digit; while (digit <= 9);
} }
while Vs do while
Contd.
for Statement
The “for” statement is the most commonly used looping
structure in C.
General syntax:
for (expression1; expression2; expression3)
statement-to-repeat;
for (expression1; expression2; expression3)
{
statement_1;
:
statement_N;
}
How it works?
“expression1” is used to initialize some variable (called index)
that controls the looping action.
“expression2” represents a condition that must be true for the
loop to continue.
“expression3” is used to alter the value of the index initially
assigned by “expression1”.
Contd.
Typically,
– expression 1 is an assignment expression
– expression 2 is a logical expression
– expression 3 is a unary expression or an assignment
expression.
When the for statement is executed,
– expression 2 is evaluated and tested at the beginning of
each pass through the loop
– expression 3 is evaluated at the end of each pass.
for statement is equivalent using while
expression 1;
while (expression 2)
{
statement
expression 3;
}
while loops are generally used when the number of passes is
not known in advance,
for loops are generally used when the number of passes is
known in advance.
Contd..
Single-entry /single-exit structure
Contd.
From a syntactic standpoint all three expressions need not be
included in the for statement.
Though the semicolons must be present.
The consequences of an omission should be clearly understood
– The first and third expressions may be omitted if other
means are provided for initializing the index and or altering
the index.
– If the second expression is omitted, however, it will be
assumed to have a permanent value of 1.
Thus,the loop will continue indefinitely unless it is terminated by
some other means such as a break or a return statement
Some Observations on for
Arithmetic expressions
– Initialization, loop-continuation, and increment can contain
arithmetic expressions.
– Ex1: for (k=x; k <= 4*x*y; k += y/x)
"Increment" may be negative (decrement)
– Ex-2: for (digit=9; digit>=0; digit--)
If loop continuation condition initially false:
– Body of for structure not performed.
– Control proceeds with statement after for structure.
A common mistake (; at the end)
int fact = 1, i; int fact = 1, i;
for ( i=1; i<=10; i++) for ( i=1; i<=10; i++);
fact = fact * i; fact = fact * i;
printf (“%d \n”, fact); printf (“%d \n”, fact);
Loop body will execute only once!
Contd.
Exercise
#include<stdio.h>
void main(){
int m=5,n=10,q=20;
if(q/n*m)
printf(“Hai");
else
printf(" WELCOME");
printf(" TO IIITNR");
}
Specifying “Infinite Loop”
while (1) { for (; ;) {
Statements Statements
} }
do {
Statements
} while (1);
Contd.
#include<stdio.h> #include<stdio.h>
main(){ void main(){
int a=1,b=2;
int a=1;
if(++a||++b)
if(a--)
printf("%d %d",a,b);
else {
printf(“IIITNR”); printf(“HAI");
} --a;
printf("%d",x);
OUTPUT: } else
22 printf("%d",x); OUTPUT:
} HAI -1
Contd.
int x, y = 2, z, a; #include<stdio.h>
int main(){
x=(y*=2) + (z=a=y); int i=2,j=2;
printf (‘%d’,x); while(i+1?--i:j++)
printf("%d",i);
return 0;
Output: }
8 Output:
1
Contd.
#include<stdio.h> #include<stdio.h>
int main(){ int main(){
int x=011,i;
int i,j;
for(i=0;i<x;i+=3){
printf("Start "); i=j=2,3;
continue; while(--i&&j++)
printf("End"); printf("%d %d",i,j);
} return 0;
return 0;
OUTPUT: }
}
OUTPUT:
Start Start Start
13
Examples on for
Ex-1 Ex-2
int fact = 1, i, N; int sum = 0, N, count;
scanf (“%d”, &N); scanf (“%d”, &N);
for (i=1; i<=N; i++) for (i=1; i<=N, i++)
fact = fact * i; sum = sum + i * i;
printf (“%d \n”, fact); printf (“%d \n”, sum);
Consecutive Integer Quantities
0 to 9
#include <stdio.h> #include <stdio.h>
main() main()
{ {
int digit ; int digit=0 ;
for(digit= 0; digit<= 9; ++digit) for(; digit<= 9; )
printf(“% d \ n”, digit) ; printf(“% d \ n”, digit++) ;
} }
Nested Loop
Nested loops consist of an outer loop with one
or more inner loops.
e.g.,
for (i=1;i<=100;i++){
for(j=1;j<=50;j++){
…
}
}
The above loop will run for 100*50 iterations.
Nested Loop
Nested loops consist of an outer loop with one
or more inner loops.
e.g.,
for (i=1;i<=100;i++)
{
for(j=1;j<=50;j++)
{
… Inner loop Outer loop
}
}
The above loop will run for 100*50 iterations.
Program Example
Print the following pattern
*****
*****
*****
*****
*****
Program code
int main()
{
int i,j;
for(i=1;i<=5;i++)
{
printf(“\n”);
for(j=1;j<=5;j++)
{
printf(“*”);
}
}
return 0;
}
Program example
Print the following pattern
*
**
***
****
*****
Program code
int main()
{
int i,j;
for(i=1;i<=5;i++)
{
printf(“\n”);
for(j=1;j<=i;j++)
{
printf(“*”);
}
}
return 0;
}
Program Example
Print the following pattern
1
12
123
1234
12345
Program code
int main()
{
int i,j;
for(i=1;i<=5;i++)
{
printf(“\n”);
for(j=1;j<=i;j++)
{
printf(“%d”, j);
}
}
return 0;
}
Program Example
Print the following pattern
1
22
333
4444
55555
Program code
int main()
{
int i,j;
for(i=1;i<=5;i++)
{
printf(“\n”);
for(j=1;j<=i;j++)
{
printf(“%d”,i);
}
}
return 0;
}
Program Example
Print the following pattern
0
12
345
6789
10 11 12 13 14
Program code
int main()
{
int i,j, val=0;
for(i=1;i<=5;i++)
{
printf(“\n”);
for(j=1;j<=i;j++)
{
printf(“\d”, val);
Val++;
}
}
return 0;
}
Program example
Print the following pattern
1
12
123
1234
12345
Program code
int main()
{
int i,j,k;
for(i=5;i>0;i--)
{
for(j=1;j<=i-1;j++)
{
printf(“ ”);
}
for(k=1; k<=6-j;k++)
{
printf(“%d”,k);
}
printf(“\n”);
}
return 0;
}
Exercise
1
121
12312
1234123
123451234
A
AB
ABC
ABCD
ABCDE
ABCDEF
Exercise
Write a program to generate Fibonacci series upto the given number.
Write a program to enter a binary number and calculate decimal equivalent of this
number
Contd.
#define ROWS 3
#define COLS 5
for (row=1; row<=ROWS; row++)
{
for (col=1; col<=COLS; col++)
{
Output:
printf(“*”);
*****
}
*****
printf(“\n”);
*****
}
Contd..
#define ROWS 5
int row, col;
for (row=1; row<=ROWS; row++)
{
for (col=1; col<=row; col++)
{ Output:
printf(“* ”); *
} **
***
printf(“\n”);
****
} *****
The comma operator
Several statements separated by commas in place of “expression1”,
“expression2”, and “expression3”.
Ex-1:
for (fact=1, i=1; i<=10; i++)
fact = fact * i;
Ex-2:
for (sum=0, i=1; i<=N, i++)
sum = sum + i*i;
Exercise
main( )
for(i=1; i<4; i++)
{
printf(“%d”,(i%2) ? i : 2*i); int i=4, z=12;
Output: if(i=5 || z>50)
printf(“hello”);
143 else
main() printf(“hye”);
{ }
int i = 1; Output:
do
{ printf(“%d”, i); Output: hello
} while(i--);
} 10
Contd.
for (x=1, y=5; x+y<=10; x++)
{
printf(“%d%d”, x,y);
y++;
}
Output:
15
26
37
THE break STATEMENT
Break out of the loop { }
The break statement is written simply as break;
can use with
while
do while
for
switch
does not work with
if
else
Causes immediate exit from a while, do/while, for or switch structure.
Program execution continues with the first statement after the structure.
THE break STATEMENT
Read the integers until user enters the negative number
or number of integers reaches to 15
for(i=0;i<15;i++)
{
scanf(“%d”, &n);
{
If(n<0)
{
break;}
}
}
An example with “break”
Example:
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
printf("\nComing out of for loop when i = 5");
break;
}
printf("%d ",i);
01234
} Coming out of for loop when i = 5
The “continue” Statement
Skips the remaining statements in the body of a while, for or
do/while structure.
– Proceeds with the next iteration of the loop.
It is written simply as continue;
continue can be used in while, do while, for loop
while and do/while
– Loop-continuation test is evaluated immediately after the
continue statement is executed.
The “continue” Statement working
Read 15 positive number from user and
print sum of it using continue
for(i=0;I<15;i++)
{ printf(“enter number”);
scanf(“%d”, &n);
if(n<0)
continue;
sum=sum+n;
}
printf(“%d”,sum);
An example with “break” and
“continue”
Contd.
Break and continue
goto
The goto statement is used to alter the normal sequence of
program execution by transferring control to some other part
of the program.
Syntax:
goto label;
where label is an identifier that is used to label the target
statement to which control will be transferred
Example:
scanf ( "%d", &x) ;
while (x <= 100) {
.....
if ( x < 0) goto errorcheck;
.....
scanf ( "%fI" , &x) ; /* error detection routine */
} errorcheck: {
printf("ERROR - NEGATIVE VALUE
FOR X " ) ;
}
Contd.
Contd.
Branching around statements can be accomplished
with the i f - else statement.
jumping to the end of a loop can be carried out with
the continue statement.
jumping out of a loop is easily accomplished using
the break statement.
Test
#include estdio. h> #include estdio. h>
main ( ) main ( )
{ Output:
{ Output:
int i = 0, x = 0; int i = 0, x = 0; 1
while (i < 20) { 0 do{
2
if (i % 5 == 0) {
if (i % 5 == 0) { 5 3
x += i; x ++;
printf("%d ", x);
15 printf("%d ", x); 4
} 30 }
++i; x=4
++i ; X=30
printf('\nx = %d", x); }while(i<20);
} printf('\nx = %d", x);
}
Contd.
main() main()
{
{ Output:
int i=0,x=0; 1
int i=0,x=0; for(i=1;i<10;++i) 0
for(i=1;i<10;i*=2) If(i%2==1) 3
x+=i; 2
x++; else 7
printf(“%d”,x); x--; 6
} printf(“%d”.x); 13
continue;
printf(“x=%d”,x); Output: 12
} 21
} 1234 printf(“ x=%d”,x); X=21
}
X=4
Contd.
main()
{ Output:
int i,j,kx=0; 0
for(i=0;i<5;++i)
for(j=0;j<i;++j)
0
{ 2
k=(i+j-1); 4
if(k%2==0) 5
x+=k;
else
9
if(k%3==0) 10
X+=k-2; 14
Printf(“%d”,x); 14
}
Printf((“x=%d”,x);
20
} X=20