C Program chapitre 2
C Program chapitre 2
By
Pr, PhD Adekunlé Akim SALAMI
Electrical Engineer
Example
Let’s write a program for dividing two integers.
But, if we divide a number by 0, program execution will
stop as its undefined behavior.
Here, we must decide and restrict the execution of
dividing code, if the divisor is zero.
scanf("%d%d",&number1,&number2);
if(number2 != 0)
printf("number1 / number2 = %d\n",number1/number2);
return 0;
}
A. Akim SALAMI, EPL-UL 2022-2023 6
B. Flow Control
If statement
Statements under if executes only, if the given condition is true.
Otherwise those statements will not be part of program.
#include<stdio.h>
int main()
{
int number1,number2;
scanf("%d%d",&number1,&number2);
if(number2 != 0)
printf("number1 / number2 = %d\n",number1/number2);
return 0;
}
A. Akim SALAMI, EPL-UL 2022-2023 7
B. Flow Control
If else statement
Statements under if executes only, when the given condition is true.
Otherwise, the statements under else will be executed.
#include<stdio.h>
int main()
{
int number1,number2;
scanf("%d%d",&number1,&number2);
if(number2 != 0)
printf("number1 / number2 = %d\n",number1/number2);
return 0;
}
A. Akim SALAMI, EPL-UL 2022-2023 8
B. Flow Control
If else statement
Statements under if executes only, when the given condition is true.
Otherwise, the statements under else will be executed.
#include<stdio.h>
int main()
{
int num;
scanf("%d",&num);
if(num == 0)
printf("Zero");
else
printf("Non-zero");
return 0;
}
A. Akim SALAMI, EPL-UL 2022-2023 9
B. Flow Control
Ternary operator
We can use ternary operator instead of if..else statement. It will take three arguments.
First argument is comparison statement.
Second argument will be executed, if the comparison becomes true.
Third argument will be executed, if the comparison becomes false.
#include<stdio.h>
int main()
{
int num;
scanf("%d",&num);
return 0;
switch(choice)
{
case 1:
//statement
break;
case 2:
//statement
break;
default:
//statement
}
#include<stdio.h>
return 0;
}
return 0;
}
return 0;
}
If we run the above program, it will print numbers from 1 to 100
except the numbers 25,50 and 75.
A. Akim SALAMI, EPL-UL 2022-2023 20