notes2

Nn return 0 end function main program output

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: de <stdio.h> int main() { /* define and initialize variables */ int counter = 0; /* grade number to be entered */ int grade; /* grade value */ float total = 0; /* sum of all grades that have been input */ float average; /* average of grades */ /* get first grade from user */ printf( "\nEnter grade (enter -1 to end): " ); scanf( "%d", &grade ); Ex. Prog. – Sentinel-controlled repetition 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 /* process while loop */ while ( grade != -1 ) { /* set up loop */ total = total + grade; /* add grade to total */ counter = counter + 1; /* increment counter */ printf( "Enter grade (enter -1 to end): " ); scanf( "%d", &grade ); } /* end while */ /* termination phase */ if (counter != 0 ) { average = total / counter; printf( "The class average is %.2f.\n\n", average ); } /* end if */ else /* if no grades were entered, output message */ printf( "No grades were entered.\n\n" ); return 0; } /* end function main */ Program Output % a.out Enter grade (enter -1 to end): Enter grade (enter -1 to end): Enter grade (enter -1 to end): Enter grade (enter -1 to end): Enter grade (enter -1 to end): The class average is 67.25. % % a.out Enter grade (enter -1 to end): -1 No grades were entered. % 56 68 98 47 -1 Nested Control Structures - Example • Problem – A college has a list of test results (1 = pass, 2 = fail) for 10 students – Write a program that allows the user to enter each student’s results and then prints how many passed and how many failed • Output should look like: % a.out Enter result Enter result Enter result Enter result Enter result Enter result Enter result Enter result Enter result Enter result Passed: 6 Failed: 4 % (1=pass, (1=pass, (1=pass, (1=pass, (1=pass, (1=pass, (1=pass, (1=pass, (1=pass, (1=pass, 2=fail): 2=fail): 2=fail): 2=fail): 2=fail): 2=fail...
View Full Document

This note was uploaded on 03/02/2009 for the course ENGR 3 taught by Professor Ben-yaakov during the Fall '08 term at UCSB.

Ask a homework question - tutors are online