









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
A chapter from a rudimentary introduction to c programming course, focusing on decisions and repetition in c programming. It covers for loops, while loops, nested loops, and if statements. Sample programs are included to illustrate the concepts.
Typology: Study notes
1 / 15
This page cannot be seen from the preview
Don't miss anything!










6 For Loops.................................. B 7 While Loops and Other Loops....................... B 8 Ifs...................................... B 9 More Ifs................................... B 10 Booleans................................... B 11 Programming Issues............................ B
CpSc111 – Goddard – Notes Chapter 6
Loops are designed for repetition.
A boolean condition is an expression that is either false or true. A simple boolean condition is a comparison between two values using one of the six relational opera- tors:
== != < > <= >=
The == tests for equality; the != tests for inequality. There must be no space between the characters in these operators. We will see later how to make more complex conditions.
A loop is used when you have code to be repeated. A for-loop is often used when you know how many times something needs to be repeated. This is sometimes called count-based looping. The basic structure is:
int index_var; for ( index_var = init_value; continue_condition; update index_var) { body_code ; }
The code that is repeated each time is called the body. The variable that keeps track of the number of times through the loop is called the index variable. Execution of the for-loop is as follows.
Run the program. If you put in a large value of max, the value of fact will overflow: an int variable can only store values within a fixed range.
A loop within a loop is called a nested loop: there is an outer and an inner loop. Here is a program to draw a square of stars, such as
Notice that the body of the outer i loop prints a single row of stars.
//This program draws a square of stars - wdg 2008 #include <stdio.h>
//Main function int main(void) { const int SIZE=5; const char GLYPH=’*’;
int i,j; for(i=0; i<SIZE; i++) { for(j=0; j<SIZE; j++) { printf("%c", GLYPH); } printf("\n"); }
return 0; }
Practice. Adapt the above program to print a triangle of stars, rather than a square.
CpSc111 – Goddard – Notes Chapter 7
The second common loop is the while-loop. The basic structure is:
while ( continuation_condition ) { body_code ; }
As in the for loop, the body might never be executed. As an example, here is code to count up to 10 with a while loop:
int i=1; while( i<=10 ) { printf("%d", i); i++; }
Note that initialization occurs before the loop, and update occurs at the end of the body. The while loop is often used for sentinel-based looping: a sentinel is a distinguish- ing value that tells the loop to stop. For example, the user inputs values until she inputs -1 not to continue.
There is also a do loop which is occasionally useful. Also occasionally useful are the break and continue constructs: these allow one to jump out or jump ahead in a loop. We’ll do an example later.
CpSc111 – Goddard – Notes Chapter 8
The if statement is the primary selection control structure. The format is
if ( condition ) then_code ;
The condition is a boolean condition as before. If the condition is true the then code is executed; if the condition is false the then code is skipped. A statement is a single piece of code; a block is several statements enclosed in braces. Here is an example:
if( gradePointAverage >= 3.0) { printf("Scholarship retained"); }
Here is a standard way of determining the maximum of a collection of values. The idea is to maintain a variable maxSoFar with the maximum value seen so far; this variable is updated each time a new value is seen by comparing it with that value. There is a standard problem of how to initialize the value of maxSoFar. This program sidesteps this by assuming that all values are nonnegative, and therefore the maximum is at least zero. Another approach is to initialize the value of maxSoFar to the first value that is read.
/* calculate maximum of user input
int main(void) {
const int LENGTH = 10; printf("Enter %d values\n", LENGTH); float maxSoFar = 0.0;
int i; float value; for(i=0; i<LENGTH; i++) { printf("Enter value "); scanf("%f", &value); if( value > maxSoFar ) maxSoFar = value; }
printf( "Max is %4.1f\n", maxSoFar ); return 0; }
value of key and does the appropriate action; more usually a switch is done with an int variable. At execution, the value of key is examined and control jumps to the appropriate label (given by case statement); default is like an else.
char key = ... switch ( key ) { case ’A’: printf("alpha"); break; case ’B’: printf("bravo"); break; case ’C’: printf("charlie"); break; default: printf("zulu"); break; }
The break command transfers execution to the first statement after the switch. Without the break’s, an A would trigger all four printf’s.
// This program converts user-supplied number to letter grade // wdg 2008 #include <stdio.h>
//Main function int main(void) { float rawGrade; char letterGrade; printf("Enter grade: "); scanf("%f", &rawGrade); if( rawGrade<0.0 ) { printf("Cannot be negative" ); } else { if (rawGrade>=90.0) letterGrade = ’A’; else if (rawGrade>=80.0) letterGrade = ’B’; else if (rawGrade>=70.0) letterGrade = ’C’;
else // rawGrade<70. letterGrade = ’F’; printf("Value %.2f is worth a %c\n", rawGrade, letterGrade); } return 0; }
It is also sometimes useful to know that the && and || are short-circuit evaluators: for example, if the first part of an && evaluates to false, so that the result is guaranteed to be false, then the remaining part is not evaluated. For example, to do something with a fraction might write:
if ( denom!=0 && num/denom > threshold )
If it turns out that denom is zero, then the division will not be performed and so one will not trigger a division-by-zero problem.
Here is a program that reads in a sequence from the user and then prints a message as to whether the sequence is strictly increasing, strictly decreasing, or neither.
// reads 10 numbers from user and says whether increasing or decreasing #include <stdio.h> #include <stdbool.h>
int main( void ) { const int LENGTH = 10; bool isIncreasing = true, isDecreasing = true; float prev, current; int i;
for(i=0; i<LENGTH; i++) { printf("Enter value "); scanf("%f", ¤t); if( i>0 && current<=prev) isIncreasing = false; if( i>0 && current>=prev) isDecreasing = false; prev = current; }
if( isIncreasing ) printf("Is strictly increasing\n"); else if( isDecreasing ) printf("Is strictly decreasing\n"); else printf("Not strictly monotonic\n");
return 0; }