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

CSE 109 Computer Programming: Introduction To Control Statements

Here are the key steps of a for loop in C: 1. Initialization: The initialization step is executed once before entering the loop. It is usually used to declare and initialize the loop counter variable. 2. Conditional test: At the start of each iteration, the conditional expression is evaluated. If it evaluates to true, the body of the loop is executed. If false, the execution jumps to the statement after the for loop. 3. Body of the loop: One or more statements that need to be executed repeatedly as long as the conditional test is true. 4. Increment/decrement: At the end of each iteration, the increment/decrement expression is executed before re-evaluating the conditional test

Uploaded by

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

CSE 109 Computer Programming: Introduction To Control Statements

Here are the key steps of a for loop in C: 1. Initialization: The initialization step is executed once before entering the loop. It is usually used to declare and initialize the loop counter variable. 2. Conditional test: At the start of each iteration, the conditional expression is evaluated. If it evaluates to true, the body of the loop is executed. If false, the execution jumps to the statement after the for loop. 3. Body of the loop: One or more statements that need to be executed repeatedly as long as the conditional test is true. 4. Increment/decrement: At the end of each iteration, the increment/decrement expression is executed before re-evaluating the conditional test

Uploaded by

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

CSE 109

Computer Programming
Introduction to Control Statements
Prepared by
Johra Muhammad Moosa
Assistant Professor
CSE, BUET

Modified by
Madhusudan Basak
Assistant Professor
CSE, BUET
if statement

num>= num is
true
0 positive

false
if statement
• Selection statement/conditional statement
• Operation governed by outcome of a conditional test
• if(expression) statement;
– expression:
• any valid C expression
– If expression is true statement will be executed
– If expression is false statement will be bypassed
– true: any nonzero value
– false: zero
– if(num+1) printf(“nonzero");//num!=-1 statement will execute
– Normally expression consists of relational & logical operator
true, false
– true: any nonzero value
– false: zero
if statement
#include<stdio.h>
int main(void)
{
int num;
scanf("%d", &num);
if(num>=0) printf("num is positive");//if(num>-1)
return 0;
}
if statement
• Common programming error:
– Placing ; (semicolon) immediately after condition in if
• if(expression); statement;
– Confusing equality operator (==) with assignment operator
(=)
• if(a=b)
• if(a=5)
• if(9=5)
– left operand must be l-value
• if(9+5)
if statement
#include<stdio.h>
int main(void)
{
int num;
scanf("%d", &num);
if(num>=0) printf("num is positive");//if(num>-1)
if(num<0) printf("num is negative");
return 0;
}
if-else statement
• if(expression) statement1;
else statement2;
– If expression is true statement1 will be evaluated and statement2
will be skipped
– If expression is false statement1 will be bypassed and statement2
will be executed
– Under no circumstances both the statements will execute
– Two-way decision path
if-else statement

num>= true num is


0 positive

false
num is
negative
Notice indentation if-else statement
#include<stdio.h>
int main(void)
{
if(num>-1)
int num;
scanf("%d", &num); Condition gives same result
if(num>=0)
printf("num is positive");
else
printf("num is negative");
return 0;
}
if-else statement
• else part is optional
• The else is associated with closest else-less if
• if(n>0)
if(a>b) z=a; Even though the else is
else z=b; indented with the first if, by
• Braces must be used to force association with therulefirst
it will be associated with
• if(n>0) the nearest if
{
if(a>b) z=a;
}
else z=b;
if-else statement
• else part is optional
• The else is associated with closest else-less if
• if(n>0)
if(a>b) z=a;
else z=b; Even though the else is
indented with the first if, by
• Where else will be associated is shown by indentation
rule it will be associated with
• Braces must be used to force association with the first
• if(n>0) the nearest if
{
if(a>b) z=a;
}
else z=b;
Nested if (section 3.2)
#include<stdio.h> else
int main(void) {
{ if(id<61)
int id; printf("B1\n");
printf("Please enter last 3 digits else
of your id:\n"); printf("B2\n");
scanf("%d", &id); }
printf("You are in "); return 0;
if(id%2) }
{
if(id<60)
printf("A1\n");
else
printf("A2\n");
}

Homework: do this example for your department


blocks of code

• Surround the statements in a block with opening and


ending curly braces.
• One indivisible logical unit
• Can be used anywhere a single statement may
• Multiple statements
• Common programming error:
– Forgetting braces of compound statements/blocks
blocks of code
• if(expression) {
statement1;
statement2;

statementN;
}
else {
statement1;
statement2;

statementN;
}
• If expression is true all the statements with if will be executed
• If expression is false all the statements with else will be executed
Example
Declare variable in
#include<stdio.h> else the beginning of a
int main( ) { block
{ int a, b, c;
int numOfArg, sum; scanf("%d %d %d", &a, &b
scanf("%d", &numOfArg); &c);
if(numOfArg==2) sum=a+b+c;
{ }
int a, b; printf("The sum is %d\n",
scanf("%d %d", &a, &b); sum);
sum=a+b; return 0;
} }
if-else if statement
• if(expression)
statement;
else if (expression)
statement;
else if (expression)
statement;
else
statement;
if-else if statement
• Multi-way decision
• expressions are evaluated in order
• If the expression of any if is true
– the statement associated with it is executed
• Multiple statements can be associated using curly braces
– the whole chain is terminated
• If none of the expressions are true
– else part is executed
– Handles none of the above/ default case
– Optional
if-else if statement
#include<stdio.h> …
int main( )

{
int num; …
scanf("%d", &num); else
if(num>=80)
printf("0.0");
printf("5.0\n");
else if(num>=75) return 0;
printf("4.75\n"); }
else if(num>=70)
printf("4.50\n");
if-else if statement
#include<stdio.h> else if(numOfArg==3)
int main( ) {
{ int a, b, c;
int numOfArg, sum; scanf("%d %d %d", &a, &b,
scanf("%d", &numOfArg); &c);
if(numOfArg==2) sum=a+b+c;
{ }
int a, b; printf("The sum is %d\n", sum);
scanf("%d %d", &a, &b); return 0;
sum=a+b; }
}
Use of logical operator
#include<stdio.h>
int main( ){ Carefully note that, you
char ch; cannot write such condition as
scanf("%c", &ch); following
if(ch>='A' && ch<='Z') ‘A’ <= ch <= ‘Z’ (This is
wrong in C code)
printf("%c\n", ch+('a'-'A'));
So, if you want to write
else if(ch>='a' && ch<='z') anything like 70<=n<=80, you
printf("%c\n", ch-('a'-'A')); have to write it as n>=70 &&
else n<=80 in C
printf("Invalid\n");
return 0;
}
Example
• Find maximum of three numbers
• Find second maximum of three numbers
• Find minimum of four numbers
switch case
switch (expression) {
case constant: statements
case constant: statements
default: statements
}
• Use of break
switch case
An Example
switch case properties
1. The expression used in switch must be integral type ( int, char and enum).
Any other type of expression is not allowed.
Output
switch case properties
2. All the statements following a matching case execute until a break
statement is reached.
Output
switch case properties
3. The default block can be placed anywhere. The position of default doesn’t
matter, it is still executed if no match found.
Output
switch case properties
4. The integral expressions used in labels must be constant expressions.
Output
switch case properties
5. The statements written above/below cases are never executed. After the
switch statement, the control transfers to the matching case, the statements
written before/after case are not executed.
Output
switch case properties
6. integral expressions used in labels can be an expression of constants.
Output
switch case properties
7. Two case labels cannot have same value.
Output
What is the output of the following code?
Output
for loop
• Allows one or more statements to be repeated
• for (initialization; conditional-test; increment) statement;
• Most flexible loop
for loop
• for (initialization; conditional-test; increment) statement;
• initialization:
– Give an initial value to the variable that controls the loop
– loop-control variable
– Executed only once
– Before the loop begins
for loop
• for (initialization; conditional-test; increment) statement;
• conditional-test:
– Tests the loop-control variable against a target value
– If true the loop repeats
• statement is executed
– If false the loop stops
• Next line of code following the loop will be executed
for loop
• for (initialization; conditional-test; increment) statement;
• increment:
– Executed at the bottom of the loop
Programming Jokes!
for loop
for(i=1; i<3; i++)
printf("%d\n", i); Initialization part is
1. i is initialized to 1 executed only once
for loop
for(i=1; i<3; i++)
printf("%d\n", i);
2. Conditional test i<3 is true as i is 1, so the loop executes
for loop
for(i=1; i<3; i++)
printf("%d\n", i);
3. The value of i will be printed, which is 1
for loop
for(i=1; i<3; i++)
printf("%d\n", i);
3. The value of i will be incremented, so now i is 2.
for loop
for(i=1; i<3; i++)
printf("%d\n", i);
4. Conditional test i<3 is true as i is 2, so the loop executes
for loop
for(i=1; i<3; i++)
printf("%d\n", i);
5. The value of i will be printed, which is 2
for loop
for(i=1; i<3; i++)
printf("%d\n", i);
6. The value of i will be incremented, so now i is 3.
for loop
for(i=1; i<3; i++)
printf("%d\n", i);
7. Conditional test i<3 is false as i is 3, so the loop stops
for loop
• for loop can run negatively
• decrement can be used instead of increment
– for(i=20; i>0; i--) ...
• Can be incremented or decremented by more than one
– for(i=1; i<100; i+=5)
for loop
– All of the following loops will print 1 to 99
– for(i=1; i<100; i++)
printf("%d\n", i);
– for(i=1; i<=99; i++)
printf("%d\n", i);
– for(i=0; i<99; i++)
printf("%d\n", i+1);
– for(i=0; i<=98; i++)
printf("%d\n", i+1);
– So selection of initial value and loop control condition is important
for loop
Single Statement Block of Statements
for(i=1; i<100; i++) sum=0;
prod=1;
printf("%d\n", i); for(i=1; i<5; i++)
• Prints 1 to 99 {
sum+=i;
for(i=100; i<100; i++) prod*=i;
printf("%d\n", i); }
printf("sum, prod is %d,
• This loop will not execute %d\n", sum, prod);
for loop
GCD of two numbers:
for loop
Nth Fibonacci number:
Nested for loop
Nested for loop
Nested for loop
Loop variation
• for( ; ; ){}
• for(ch=getchar(); ch!=‘q’; ch=getchar()) {}
• for(i=0; i<n; )
{
i++;
}
Practice Problems
• 1+2N+3N+4N+5N+…+NN
• 1+22+33+44+55+…+NN
• Sine, Cos series
Practice Problems
• Given a number as input write to program to calculate the number of
digits.
• Given a number as input write to program to calculate the sum of it’s
digits.
• Write a program to find gcd of two given numbers
• Write a program to find xm where x and m are inputs
• Write a program to convert a decimal number to a binary number
• Write a program to expand shorthand notation like a-z
while loop
• while(expression) statement;
• for(initialization; conditional-test; increment) statement;
• initialization;
while(conditional-test)
{
statement;
increment;
}
while loop

for while
while loop
• Common error
– Forgetting to increment
• Normally used when increment is not needed
– while(ch!=‘q’)
{

ch=getchar();
}
do while loop
• for(initialization; conditional-test; increment) statement;
• initialization;
do
{
statement;
increment;
} while(conditional-test);
do while loop
• Test is at the bottom
• Will execute at least once
• do
{

ch=getchar();
} while(ch!=‘q’);
• Common error
– Forgetting the semicolon (;) after while
while loop

for do while
for loop

This will show 1 as


prime. Change the
code so that it will
print “not prime”
for 1.
while loop

This will show 1 as


prime. Change the
code so that it will
print “not prime”
for 1.
do while loop

Iit will show that 2 is not


prime

Also, this code will


show 1 as prime.
Change the code so
that it will print
“not prime” for 1.
Use of break
Use of continue
Input characters
• getche()/getch()/getchar can be used
• getchar()
– Compiler dependent
– waits for carriage return
– Read only one char
– Other input and carriage return will be in buffer
– Subsequent input (e.g, scanf) will consume them.
– Defined in stdio.h
• getche()/getch()
– Return immediately after a key is pressed
– Defined in conio.h
Symbolic Constant
• A name that substitutes for a sequence of characters
• #define name replacement
• Any occurrence of name (not in quotes and not part of another name) will
be replaced by corresponding replacement
• #define PI 3.141593
• #define TRUE 1
• #define FALSE 0
Short Circuit Evaluation
if(a!=0 && num/a)
{
}

• If first operand of ‘&&’ is zero, the 2nd operand is not evaluated


• If first operand of ‘||’ is nonzero, the 2nd operand is not evaluated
Conditional Expressions (sec 11.7)
• Uses ternary operator “?:”
• expression1?expression2:expression3;
• z= (a>b)? a: b; /* z=max(a,b);*/
• Can be used anywhere an expression can be
Conditional Expressions (sec 11.7)
Reference
• TEACH YOURSELF C by Herbert Schildt (3rd Edition)
– Chapter 2 (2.1-2.5)
– Chapter 3 (3.1-3.9)
– Chapter 11 (11.7)

• https://www.geeksforgeeks.org/interesting-facts-about-switch-statement-in
-c/
Thank You 

You might also like