L4_Control flow
L4_Control flow
• Using if statement, you can make your decision based on a condition. • Using if-else statement, you can make your decision based on a condition.
• If the condition is true (i.e. the value of the expression is non-zero or non- • If the condition is true (i.e. the value of the expression is non-zero or non-
null), the if statement will operate. null), the if statement will operate.
• If the condition is false (i.e. the value of the expression is zero or null), the • If the condition is false (i.e. the value of the expression is zero or null), the
compiler will bypass the if statement. else portion will operate.
Examples: Examples:
if(expression) statement 1; • if(expression)
if(expression) { statement 1; statement 2; } statement 1;
else statement 2;
• if (x == 2) x >>= 1; • if(expression)
• if (x == 2) x >>= 1; x <<= 1; statement 1;
• if (x == 2) { x >>= 1; x <<= 1; } else { statement 2; statement 3; }
• if (x == 2) x >>= 1; else x <<= 1;
• if (x == 2) { x >>= 1; x <<= 1; } else x = 0;
#include <stdio.h>
int main()
{ int i=5;
do To find nth term of a pascal triangle we use following formula.
{ printf("%d",i);
• Where n is row number and k is term of that row.
continue; //compiler will get stuck here
Step by step descriptive logic to print pascal triangle.
i++; }
• Input number of rows to print from user. Store it in a variable say num.
while(i<=10);
• To iterate through rows, run a loop from 0 to num, increment 1 in each iteration.
return 0; } The loop structure should look like for(n=0; n<num; n++).
• Inside the outer loop run another loop to print terms of a row. Initialize the loop
• Except looping, we cannot use continue keyword. from 0 that goes to n, increment 1 in each iteration.
• Inside the inner loop use formula term = fact(n) / (fact(k) * fact(n-k)); to print
current term of pascal triangle.
Example Example
Draw a Pascal’s triangle like the following one using C programming (for/while Draw a Pascal’s triangle like the following one using C programming (for/while
loop). loop).