Part II
Part II
1
More on ‘printf’, & ‘scanf’
Output int main()
New line
Enter marks in 5 {
subjects: 85 75 60 72int m1, m2, m3, m4, m5, aggr;
56
float per;
Aggregate Marks = 348
printf (“\nEnter marks in 5 subjects: ”);
Percentage Marks = scanf (“%d %d %d %d %d”, &m1, &m2,
69.000000 &m3, &m4, &m5);
aggr = m1 + m2 + m3 + m4 + m5;
per = aggr / 5;
printf (“Aggregate Marks = %d\n”, aggr);
printf (“Percentage Marks = %f\n”, per);
return 0;
} 2
The if else statement
3
EXAMPLES
int main()
{
int qty, dis;
float rate, tot;
printf (“Enter quantity and rate”);
scanf (“%d %f”, &qty, &rate);
if (qty > 1000)
dis = 10;
else
dis = 0;
tot = (qty * rate) - (qty * rate * dis / 100);
printf (“Total expenses = Rs. %f\n”, tot);
return 0;
}
4
Multiple statements within if-else
int main()
{
float bs, gs, da, hra;
printf (“Enter basic salary”);
scanf (“%f”, &bs);
if (bs < 1500)
{
hra = bs * 10 / 100;
da = bs * 90 / 100;
}
else
{
hra = 500;
da = bs * 98 / 100;
}
gs = bs + hra + da;
printf (“gross salary = Rs. %f\n”, gs);
return 0;
} 5
Flow chart of the previous program 6
Nested if-else
if (i == 1)
printf (“You would go to heaven !\n”);
else
{
if (i == 2)
printf (“Hell was created with you in mind\n”);
else
printf (“How about mother earth !\n”);
}
9
int main()
{
char sex, ms;
int age;
printf (“Enter age, sex, marital status”);
scanf (“%d %c %c”, &age, &sex, &ms);
if ((ms == ’M’) || (ms == ’U’ && sex == ’M’ &&
age > 30) || (ms == ’U’ && sex == ’F’ && age
> 25))
printf (“Driver should be insured\n”);
else
printf (“Driver should not be insured\n”);
return 0;
}
10
The ‘else if’
11
The salary problem.
12
int main() else if (g == ’f’ && yos >= 10 && qual
{ == 1)
13
The ! operator
if (! flag)
The Hierarchy of operators
14
The conditional operators
Example 1 Example 2
int x, y; int i;
scanf (“%d”, &x);
scanf (“%d”, &i);
y = (x > 5 ? 3: 4);
(i == 1 ? printf (“Amit”) :
This statement will
printf (“All and sundry”));
store 3 in y if x is
What will be the result
greater than 5,
if i = 2
otherwise it will store
4 in y.
15
The ‘for’ loop
16
for(i=0; i<1000; i++){
printf(“hello”);
}
what is i++ ??
increment i by 1 for each iteration
i++ is equivalent to i = i+1
17
CODE
.. RESULT
#include<stdio.h>
int main(){
for(int i=0;i<=10;i++){
printf("%d\n",i);
}
}
IF THERE IS ONLY ONE INSTRUCTION WITHIN A FOR
LOOP THEN CURLY BRACES CAN BE AVOIDED.
18
SAME RESULTS FOR ++i
Same result
#include<stdio.h>
int main(){
for(int i=0;i<=10;){
printf("%d\n",i);
i = i+1;
}
}
19
CODE
..
RESULT
#include<stdio.h>
int main(){
int i = 1;
for(;i<=10;){
printf("%d\n",i);
i = i+1;
}
}
20
CODE RESULT
#include<stdio.h>
int main(){
int i;
for(i=0;i++<=10;){
printf("%d\n",i);
}
}
21
The ‘while’ loop
22
Example of while loop
#include<stdio.h>
int main(){
int i = 5;
while(i>1){
printf("teach the computer\n");
i = i-1;
}
return 0;
}
23
Factorial !!!!!
RESULT OF THE
CODE
24