CS 111
INTRODUCTION TO CS
1 Presented by Assoc. Prof. Hala Abdel-Galil
Head of computer science department
SENTINEL-CONTROLLED REPETITION
Indefined repetition: Number of repetitions is not
known in advance.
Use a special value called a “Sentinel value” (also
called a “signal value”, a “dummy value”, or a “flag
value” ) to indicate “end of data entry”
Ex: enter -1 to end
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
Nested if..else can be very hard to follow and can
be confuse sometimes.
switch statement is used for multiple selection
But:
only use with integer and character constants
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
Same as nested if..else
7
Fig. 4.8: p.157
EXAMPLE USING 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
int num1, num2, menuNo, result;
printf (“Enter 2 integer numbers”);
scanf (“%d %d”, &num1,&num2 );
printf (“Choose an operation (1 or 2)”);
scanf (“%d”, &menuNo);
switch (menuNo ) {
case 1:
result= num1 + num2;
break;
case 2:
result= num1 - num2;
break;
default:
} /* end switch */ 9
printf (“The result is %d”, result);
ASSIGNMENT OPERATORS
C provides several assignment operators for
abbreviating assignment expressions.
For example, the statement
c = c + 3;
= c += 3;
addition assignment operator
Note:
The value of the variable is overwritten by the new one.
10
COUNTING LETTER GRADES (fig.4.7)
getchar() function from (<stdio.h>) reads one character
from the keyboard and stores it in variable grade
End of file
<Ctrl> z in Windows
while ((grade= getchar()) != EOF){
F){
switch(grade){
case ‘A’: case ‘a’: ++aCount; break;
case ‘B’: case ‘b’: ++bCount; break;
case ‘C’: case ‘c’: ++cCount; break;
Section 4.7
case ‘D’: case ‘d’: ++dCount; break;
case ‘F’: case ‘f’: ++fCount; break;
} //end switch
} // end while
11
COUNTING LETTER GRADES (CONT.)
while ((grade= getchar()) != EOF){
switch(grade){
case ‘A’: case ‘a’: ++aCount; break;
case ‘B’: case ‘b’: ++bCount; break;
case ‘C’: case ‘c’: ++cCount; break;
case ‘D’: case ‘d’: ++dCount; break;
case ‘F’: case ‘f’: ++fCount; break;
case ‘\n’ : /* ignore newlines, */
case ‘\t’: /* tabs,*/
case ‘ ‘: /* spaces*/
break;
default:
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
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
Print the number of passes
Print the number of failures
If more than eight students passed
Print “Raise tuition”
1 /* Fig. 3.10: fig03_10.c
2 Analysis of examination results */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main()
7 {
8 /* initialize variables in definitions */
9 int passes = 0; /* number of passes */
10 int failures = 0; /* number of failures */
11 int student = 1; /* student counter */
12 int result; /* one exam result */
13
14 /* process 10 students using counter-controlled loop */
15 while ( student <= 10 ) {
16
17 /* prompt user for input and obtain value from user */
18 printf( "Enter result ( 1=pass,2=fail ): " );
19 scanf( "%d", &result );
20
21 /* if result 1, increment passes */
22 if ( result == 1 ) {
23 passes = passes + 1;
24 } /* end if */
25 else { /* otherwise, increment failures */
26 failures = failures + 1;
27 } /* end else */
28
29 student = student + 1; /* increment student counter */
30 } /* end while */
31
32 /* termination phase; display number of passes and failures */
33 printf( "Passed %d\n", passes );
34 printf( "Failed %d\n", failures );
35
36 /* if more than eight students passed, print "raise tuition" */
37 if ( passes > 8 ) {
38 printf( "Raise tuition\n" );
39 } /* end if */
40
41 return 0; /* indicate program ended successfully */
42
43 } /* end function main */
9
TEST
1- If the grade of a student is equal to
70 what is the output of the following
statement:
printf( "%s\n", grade >= 60 ?
"Passed" : "Failed" );
1-b)Write the above statement in another
way by using if statemnt.
0
1- A) IF THE GRADE OF A STUDENT IS EQUAL TO 70
WHAT IS THE OUTPUT OF THE FOLLOWING STATEMENT:
if ( grade >= 60 )
printf( "Passed\n");
else
printf( "Failed\n");
Write the above statement in another
way by using Ternary conditional
operator (?:)
1
1-C) If d =5, e= 3, f= 3, g=30
what’s the result of the following
statements
d -= 4
e *= 5
f /= 3
g %= 9
FIND THE ERROR
Switch (num)
{
case 1 ;
printf(“num is 1”);
case 2 ;
printf(“num is 2”);
default;
printf(“num is neither 1 nor 2”);
}
22
) Write a while statement that prints numbers
from -3 to 3 with 0.5 increments
23
FUNCTIONS
24
FUNCTIONS
Structured programming
Divide large Divide and conquer
program into concept
Functions
library Standard C programmer-defined
functions( Built-in( functions
pow , printf scanf, Ex:
25
FUNCTION CALLS
Function
call
returns
Caller 1
6
Caller Called fn.
2
5
Section 5.2
Called fn. 4
3
Caller or Calling function 26
EVERY C FUNCTION HAS 2 PARTS:
int main ( ) header
{
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;
or, until reaches right brace
If something returned
28
return expression;
FUNCTION Header
means for communicating
information between functions
Output from function Inputs to function
(return-value type) Function name
(parameter list)
int sum2int (int , int) {…… .}
double average2 ( float, float) {…….}
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
int main (void) {
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;
If function does return a value, the statement
return expression ;
returns the value of expression to the caller
Main’s return type
In C standard, the main implicitly returns 0 when
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
Data types printf conversion scanf conversion
specifications specifications
long double %Lf %Lf
double %f %lf
float %f %f
unsigned long int %lu %lu
long int %ld %ld
unsigned int %u %u
int %d %d
short %hd %hd
char %c %c
Fig. 5.5 Promotion hierarchy for data types.
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>
int Square( int ); /* declares these functions */
int Cube( int );
int main( )
{
int num = 3 ;
int sq , cb ;
function call
sq = Square(num);
printf(“ The square of 3 is %d \n “, sq );
cb = Cube(num);
printf(“ The cube of 3 is %d \n “, cb );
36
return 0;
}
Square and Cube functions
int Square( int n )
{
int s; Local variables
s=n*n; known only in this function
return s;
}
int Cube( int n )
{
int c = n * n * n ;
return c; 37
}
CALLING FUNCTION INSIDE A LOOP
Consider a program that uses a function square to
calculate and print the squares of the integers from 1 to 10
#include <stdio.h>
int square( int ); /* function prototype needed if
function definition comes after use in program */
int main (void( {
int x, sq;
/ * loop 10 times and calculate square of x each time */
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 ()
int square( int y ) y
{ 1
return y * y;
} /* end function square */
39
Call by value Or Pass by value
TRACING PROGRAM WITH FUNCTION CALL
Memory used by
#include <stdio.h> main () Screen
int square( int );
x 1 4
int main( void ) { 1
2
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 ()
int square( int y ) y
{ 2
Can fun. Square
return y * y; has variable x?
} /* end function square */
40
FUNCTIONS PROTOTYPES FEATURES
1 The compiler uses it to validates function calls.
Compilation error occurred if:
The function call doesn’t match the function
prototype.
The function prototype and the function
definition disagree
Section 5.6
2 Coercion of arguments
Means, forcing of arguments to the appropriate
type ) Arithmetic Conversion Rules).
41
Math Library Functions
Function Description Example
sqrt( x ) square root of x sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0
exp( x ) exponential function ex exp( 1.0 ) is 2.718282
exp( 2.0 ) is 7.389056
log( x ) natural logarithm of x log( 2.718282 ) is 1.0
log( 7.389056 ) is 2.0
(base e)
log10( x ) logarithm of x (base 10) log10( 1.0 ) is 0.0
log10( 10.0 ) is 1.0
log10( 100.0 ) is 2.0
fabs( x ) absolute value of x fabs( 5.0 ) is 5.0
fabs( 0.0 ) is 0.0
fabs( -5.0 ) is 5.0
ceil( x ) rounds x to the smallest ceil( 9.2 ) is 10.0
ceil( -9.8 ) is -9.0
integer not less than x
floor( x ) rounds x to the largest floor( 9.2 ) is 9.0
floor( -9.8 ) is -10.0
integer not greater than x
pow( x, y ) x raised to power y (xy) pow( 2, 7 ) is 128.0
pow( 9, .5 ) is 3.0
fmod( x, y ) remainder of x/y as a fmod( 13.657, 2.333 ) is
1.992
floating point number
sin( x ) trigonometric sine of x sin( 0.0 ) is 0.0
(x in radians)
cos( x ) trigonometric cosine of x cos( 0.0 ) is 1.0
(x in radians)
tan( x ) trigonometric tangent of x tan( 0.0 ) is 0.0
(x in radians)
Fig. 5.2 Commonly used math library functions.
Write a program to permits the user to
enter two numbers ( for ten times) then
calculate the addition and subtraction ,
also multiplication for two numbers ( by
using function calculate which uses
Switch statement )
THANKS
44