CS111 - Lecture 8 - Fall 2023 2024
CS111 - Lecture 8 - Fall 2023 2024
INTRODUCTION TO CS
Section 3.9
2
CLASS AVERAGE WITH SENTINEL (fig. 3.8: )
3
CLASS AVERAGE WITH SENTINEL (fig. 3.8: )
Should be unique
(unacceptable input)
4
MULTIPLE CASES USING SWITCH CASE
But:
5
SWITCH STATEMENT
switch (controling expression)
{ If break; is forgotten
case value1: The first case will be
statements1; true, all consecutive
break; cases will be executed
case value2:
statements2;
break; Don’t forget it
...
case valueN:
statementsN;
break;
default: 6
statements;
}
FLOWCHART OF SWITCH STATEMENT
Problem:
Read 2 integer numbers, then perform a menu that
add these 2 numbers if you press 1 and subtract
them if you press 2.
We should read first:
- the 2 numbers (num1 and num2)
- the MenuNo (1 or 2)
Yes No
menuNo ==1
result=
num1+num2
Yes No
menuNo ==2
result=
break; num1 -num2
break;
8
C CODE USING SWITCH STATEMENT
Note:
The value of the variable is overwritten by the new one.
10
COUNTING LETTER GRADES (fig.4.7)
End of file
<Ctrl> z in Windows
Section 4.7
case ‘D’: case ‘d’: ++dCount; break;
case ‘F’: case ‘f’: ++fCount; break;
} //end switch
} // end while
11
COUNTING LETTER GRADES (CONT.)
Section 4.7
printf( "Incorrect letter grade entered." );
printf( " Enter a new grade.\n" );
break; /* optional; will exit switch anyway */
} // end switch } // end while 12
Nested control structures
• Problem
– A college has a list of test results (1 = pass, 2 = fail) for 10
students
– Write a program that analyzes the results
• If more than 8 students pass, print "Raise Tuition"
• Notice that
– The program must process 10 test results
• Counter-controlled loop will be used
– Two counters can be used
• One for number of passes, one for number of fails
– Each test result is a number—either a 1 or a 2
• If the number is not a 1, we assume that it is a 2
• Top level outline
Analyze exam results and decide if tuition should be raised
• First Refinement
Initialize variables
Input the ten quiz grades and count passes and failures
Print a summary of the exam results and decide if tuition should
be raised
• Refine Initialize variables to
Initialize passes to zero
Initialize failures to zero
Initialize student counter to one
• Refine Input the ten quiz grades and count passes
and failures to
While student counter is less than or equal to ten
Input the next exam result
If the student passed
Add one to passes
else
Add one to failures
Add one to student counter
• Refine Print a summary of the exam results and
decide if tuition should be raised to
Print the number of passes
Print the number of failures
If more than eight students passed
Print “Raise tuition”
Initialize passes to zero
Initialize failures to zero
Initialize student to one
if ( grade >= 60 )
printf( "Passed\n");
else
printf( "Failed\n");
23
FUNCTIONS
24
FUNCTIONS
Structured programming
25
FUNCTION CALLS
Function
call
returns
Caller 1
6
Caller Called fn.
2
5
Section 5.2
Called fn. 4
3
Function body
return 0 ;
}
27
Function definition format (continued)
return-value-type function-name( parameter-list )
{
declarations and statements
}
Definitions and statements: function body (block)
Variables can be defined inside blocks (can be nested)
Functions can not be defined inside other functions
Returning control
If nothing returned
return;
If something returned
28
return expression;
FUNCTION Header
29
FUNCTION RETURNS VOID
Consider a function “square” to calculate and print the
square of an integer. Then call it from main().
#include <stdio.h>
//”square” function doesn’t return a value
void square( int y ) { void square( int y ){
int Z= y*y; printf( ″the square is %d″ , y*y(;
return; // can be omitted
printf (″the square is %d″, Z);
}
} // end function
Section 5.5
int x;
printf(“Please enter the number”);
scanf (“%d”, &x);
square (x) ; 30
return 0;
}
RETURN STATEMENT
If function doesn’t return a value (i.e. return-
type-value is void)
Return statement can be omitted or
Execute return;
Section 5.5
terminated
➔ return statement can be omitted بشكل
ضمنى
You can explicitly return non-zero values from main to
indicate that a problem occurred during execution.
صراحة 31
FUNCTION RETURNS A VALUE
Consider a function “square” to calculate and return
the square of an integer. The main() prints the result.
#include <stdio.h>
//”square” function returns the square of parameter
int square( int y ) // y is a copy of argument to function
{ 2 1
return y*y; passes the result of the calculation back
} // end function to the calling function
int main (void) {
int x, sq;
Section 5.5
printf (“Please enter the number”);
scanf (“%d”, &x);
sq = square (x) ; // fn square is invoked or called
printf (″the square is %d″, sq); 32
return 0;
}
FUNCTION PROTOTYPE
A prototype looks like a header function but must end
with a semicolon; and its parameter list just needs to
contain the type of each parameter.
#include <stdio.h>
int square (int); // fn prototype
int main (void) {
int x, sq;
printf (“Please enter the number”);
scanf (“%d”, &x);
sq = square (x) ;
Section 5.5
printf (″the square is %d″, sq);
return 0;
}
int square( int y ) {
33
return y*y;
} // end function
FUNCTION PROTOTYPES
34
HEADER FILES
Standard library header Explanation
<assert.h> Contains macros and information for adding diagnostics that aid program
debugging.
<ctype.h> Contains function prototypes for functions that test characters for certain
properties, and function prototypes for functions that can be used to
convert lowercase letters to uppercase letters and vice versa.
<errno.h> Defines macros that are useful for reporting error conditions.
<float.h> Contains the floating point size limits of the system.
<limits.h> Contains the integral size limits of the system.
<locale.h> Contains function prototypes and other information that enables a pro-
gram to be modified for the current locale on which it is running. The
notion of locale enables the computer system to handle different conven-
tions for expressing data like dates, times, dollar amounts and large
numbers throughout the world.
<math.h> Contains function prototypes for math library functions.
<setjmp.h> Contains function prototypes for functions that allow bypassing of the
usual function call and return sequence.
<signal.h> Contains function prototypes and macros to handle various conditions that
may arise during program execution.
<stdarg.h> Defines macros for dealing with a list of arguments to a function whose
number and types are unknown.
<stddef.h> Contains common definitions of types used by C for performing certain
calculations.
<stdio.h> Contains function prototypes for the standard input/output library func-
tions, and information used by them.
<stdlib.h> Contains function prototypes for conversions of numbers to text and text
to numbers, memory allocation, random numbers, and other utility 35
functions.
<string.h> Contains function prototypes for string processing functions.
<time.h> Contains function prototypes and types for manipulating the time and
date.
Program with Three Functions
#include <stdio.h>
Section 5.5
for ( x=1 ; x<=10 ; x++) { // fn square is invoked or called
sq= square (x) ;
printf( "%d ", sq) ;
} //end for
return 0; 38
}
Tracing
TRACING PROGRAM WITH FUNCTION CALL
Memory used by
#include <stdio.h> main () Screen
int square( int );
x 1
int main( void ) { 1
int x;
for ( x = 1; x <= 10; x++ ) {
/
printf( "%d ", square(x));
} /* end for */
return 0; copy
} /* end main */
Section 5.5
Memory used by square ()
Section 5.5
Memory used by square ()
Section 5.6
2 Coercion of arguments
Means, forcing of arguments to the appropriate
type ) Arithmetic Conversion Rules).
41
Math Library Functions
44