A Rudimentary Intro to C programming: Decisions and Repetition - Prof. Wayne D. Goddard, Study notes of Computer Science

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

Pre 2010

Uploaded on 07/29/2009

koofers-user-x87
koofers-user-x87 🇺🇸

9 documents

1 / 15

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
A Rudimentary Intro to C programming
Wayne Goddard
School of Computing, Clemson University, 2008
Part 2: Decisions and Repetition
6 For Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B1
7 While Loops and Other Loops . . . . . . . . . . . . . . . . . . . . . . . B4
8 Ifs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B6
9 More Ifs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B8
10 Booleans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B11
11 Programming Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . B14
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download A Rudimentary Intro to C programming: Decisions and Repetition - Prof. Wayne D. Goddard and more Study notes Computer Science in PDF only on Docsity!

A Rudimentary Intro to C programming

Wayne Goddard

School of Computing, Clemson University, 2008

Part 2: Decisions and Repetition

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

For Loops

Loops are designed for repetition.

6.1 Boolean Conditions and Relational Operators

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.

6.2 The For Loop

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.

  1. Initialize index variable
  2. Check condition. If false then stop.
  3. Execute body code.
  4. Update index variable.
  5. Goto 2.

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.

6.5 Nested Loops and Sample Program: squareDraw.c

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

While Loops and Other Loops

7.1 The While Loop

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.

7.2 Other Loop Stuff

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

Ifs

8.1 The If Statement

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"); }

8.2 Sample Program: listMax.c

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

  • Assumes values nonnegative
  • wdg 2008 */ #include <stdio.h>

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.

9.4 Sample Program: grader.c

// 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.

10.3 Sample Program: sequence.c

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", &current); 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; }