CSCI-1190: Beginning C Programming For Engineers: Lecture 2: Logic, Repetition, Iteration Gang Chen
CSCI-1190: Beginning C Programming For Engineers: Lecture 2: Logic, Repetition, Iteration Gang Chen
10. c=a*a+b*b;
11. printf("c*c = %f \n", c);
12. return 0;
13. };
Control Structure
• Sequential execution
• Branch
– if, if-else
– switch
• Repetition
– while
– do-while
• Iteration
– for
if Statement
1. #include <stdio.h>
2. int main()
3. {
4. int grade;
5. printf("Please input your grade:");
6. scanf("%d", &grade);
7. if( grade >= 60) /* boolean expression*/
8. printf("You passed the exam!\n");
9. return 0;
10. };
if-else Statement
1. if( grade >= 60)
2. { /* compound statement */
3. printf("You passed ");
4. printf("the exam!\n");
5. }
6. else
7. {
8. printf("You failed!\n");
9. }
Relational Operators
• Relational expressions == Equal
return 1 if the condition is
true, or 0 otherwise. != Not equal
• Relational operators have < Less than
a lower precedence than
arithmetic operators. <= Less than or
equal
• Don’t confuse == with =
– if( a==3 ) > Greater than
– if( a=3 )
>= Greater than or
equal
Nested if-else Statement
1. if( grade >= 90)
2. printf("You got an A!\n");
3. else if ( grade >= 80 )
4. printf("You got a B!\n");
5. else if ( grade >= 70 )
6. printf("You got a C!\n");
7. else if ( grade >= 60 )
8. printf("You got a D!\n");
9. else
10. printf("You failed!\n");
Logical Operators
Negation: ==1 if expr is 0, and 0 otherwise
!expr !0 == 1;
!2.0 == 0;
And: ==1 if both expr1 and exp2 are true
expr1&&expr2 2 && 3 == 1;
0 && 2 == 0;
Or: ==1 if either expr1 or expr2 are true
expr1||expr2 2 || 3 == 1;
0 || 3 == 1;
4. i++;
5. if(i<=100) i++;
6. goto loop;
i<=100
Yes
No
Sum from 1 to 100 (while)
i=1;
1. int i=1,sum=0; sum=0;
2. while(i<=100)
3. { No
i<=100
4. sum=sum+i;
5. i++; Yes
6. } sum=sum+i;
i++;
Control Flows
i=1; i=1;
sum=0; i=1; sum=0;
sum=0;
Yes
i<=100
sum=sum+i; No
i<=100
sum=sum+i;
No
Yes
i++;
i++; sum=sum+i;
i<=100
Yes i++;
No
Goto While
Sum from 1 to 100 (do-while)
i=1;
1. int i=1,sum=0; sum=0;
2. do{
3. sum=sum+i; sum=sum+i;
4. i++;
5. } while (i<=100); i++;
i<=100
Yes
No
Sum from 1 to 100 (for)
i=1;
1. int i,sum; sum=0;
2. for(i=1,sum=0;i<=100;i++)
3. sum=sum+i; No
i<=100
Yes
sum=sum+i;
i++;
break and continue
1. int i; 1. int i;
2. for(i=1;i<=10;i++) 2. for(i=1;i<=10;i++)
3. { 3. {
4. if(i==5)break; 4. if(i==5)continue;
5. printf("%d ",i); 5. printf("%d ",i);
6. } 6. }
Nested Structure
1. int i,j;
2. for(i=0;i<10;i++)
3. {
4. for(j=0;j<i;j++)
5. printf("*");
6. printf("\n");
7. }
In-Class Exercise 2-2
• Write a program that prints the following
diamond shape. Minimize the number of
printf statements.
*
***
*****
*******
*********
*******
*****
***
*