0% found this document useful (0 votes)
7 views

lecture notes for c n cpp - functions

The document discusses sentinel-controlled loops in programming, explaining how they function using a special value to terminate the loop. It also covers function definitions in C, including prototypes, local and global variables, and parameter passing methods (by value and by reference). Additionally, it provides examples of both parameter passing techniques and concludes with an assignment for further exploration of the concepts presented.

Uploaded by

victorspark8
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

lecture notes for c n cpp - functions

The document discusses sentinel-controlled loops in programming, explaining how they function using a special value to terminate the loop. It also covers function definitions in C, including prototypes, local and global variables, and parameter passing methods (by value and by reference). Additionally, it provides examples of both parameter passing techniques and concludes with an assignment for further exploration of the concepts presented.

Uploaded by

victorspark8
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Sentinel Controlled Loops

When the last entry of a loop is a special value, this is called a sentinel. That is, the whole loop continues to
execute as long as the program do not read the sentinel. Consider the following example:
Scanf(var);
While(var != sentinel)
{scanf(var);
}
Example 2.
//sentinel loop - 10-11-2024
#include <stdio.h>
int main()
{
const int sentinel = -100; //a sentinel special value
int average, num, sum = 0, count = 0;
printf("Enter values you want to add OR end with %d\n",sentinel, " ");
scanf("%d", &num);
while (num != sentinel){
sum = sum +num;
count++;
printf("Enter next values OR end with: %d\n",sentinel);
scanf("%d", &num);
}
if (count !=0){
average = sum/count;}
else{
printf("\nNo input\n");
}
printf("Sum of your Numbers is: %d\n",sum);
printf("Avearge of your Numbers is: %d\n", average);
return 0; //not neceesary needed. the compiler will do the needful
}//end main function

The sample code runs but with errors. What is the error?
Chapter Six
Functions
The C and C++ standard library provides a rich collection of functions for performing common
mathematical calculations, string manipulations, character manipulations, input/output, and many other
useful operations. These are sometimes referred to as programmer-defined functions. Functions are
invoked by a function call, which specifies the function name and provides information (as arguments)
that the function needs to perform its designated task.
Functions allow you to modularize a program. All variables defined in function definitions are local
variables—they can be accessed only in the function in which they’re defined. Most functions have a list
of parameters that provide the means for communicating information between functions. A function’s
parameters are also local variables of that function.
Definition: Functions are used in C to break large computing tasks into smaller units or modules, which
are block of statements separated from the main program to perform a portion of the main task. they can be
inbuilt or standard, programmer or user-defined. A function when declared has a prototype specifying the
function type, name, and parameter list.
6.1 Function Definition
The format of a function definition is
return-value-type function-name (parameter-list)
{
definitions
statements
}
The function-name is any valid identifier. The return-value-type is the data type of the result returned to
the caller. The return-value-type void indicates that a function does not return a value. Together, the return-
value-type, function-name and parameter-list are sometimes referred to as the function header. The
parameter-list is a comma-separated list that specifies the parameters received by the function when it’s
called. If a function does not receive any values, parameter-list is void. A type must be listed explicitly for
each parameter.
Consider a program that uses a function square to calculate and print the squares of the integers from 1 to
10.
1. //Functions - 11-11-2024
2. #include <stdio.h>
3. //you declare a function before the main function
4. int square(int y); //the function prototype
5. // now begin the main fucntion
6. int main(){
a. int count;
b. for(count = 1; count <= 10; count++){
i. printf("%d ", square(count));//function call sqaure(count)
c. }
d. printf("");
e. return 0;
7. }// end main fucntion

8. //now let’s write the function body


9. int square (int y)//y is the argument that returns the value
10. {
a. return y * y;
11. }//end function square
Let’s analyze the program.
int square( int y ); is a function prototype as written in Line 4.
a. The int in parentheses informs the compiler that square expects to receive an integer value from
the caller. The int to the left of the function name square informs the compiler that square returns
an integer result to the caller. The compiler refers to the function prototype to check that any calls
to square (line 6bi) contain the correct return type, the correct number of arguments and the
correct argument types, and that the arguments are in the correct order.
b. printf( "%d ", square( count ) ); is a function call via the name and parameter. Function square is
invoked or called in main within the printf statement. Function square receives a copy of the value
of count in the parameter y (line 9). Then square calculates y * y. The result is passed back returned
to function printf in main where square was invoked (line 6bi), and printf displays the result. This
process is repeated 10 times using the for statement.
c. The definition of function square (lines 9–11) shows that square expects an integer parameter y.
The keyword int preceding the function name (line 9) indicates that square returns an integer result.
The return statement in square passes the value of the expression y * y (that is, the result of the
calculation) back to the calling function in line 6bi.
There are three ways to return control from a called function to the point at which a function was invoked.
If the function does not return a result, control is returned simply when the function-ending right brace is
reached, or by executing the statement.
Lab examples:
1. use a function to get the max from three numbers entered by the user.
2. in the sample program above, which is the local and global variable?
3. The scope of var y is limited to what block?
6.2. Parameter Passing
In many programming languages, there are two ways to pass arguments—pass-by-value and pass-by-
reference. A C function is either invoked by a value or by reference.
When arguments are passed by value, a copy of the argument’s value is made and passed to the called
function. Changes to the copy do not affect an original variable’s value in the caller. When an argument is
passed by reference, the caller allows the called function to modify the original variable’s value.
Pass-by-value should be used whenever the called function does not need to modify the value of the caller’s
original variable. This prevents the accidental side effects (variable modifications) that so greatly hinder
the development of correct and reliable software systems. Pass-by-reference should be used only with
trusted called functions that need to modify the original variable.
In C, all arguments are passed by value. It is possible also to simulate pass-by-reference but this is done
via pointers.
Why?
The return statement may be used to return one value from a called function to a caller (or to return control
from a called function without passing back a value). Many functions require the capability to modify
variables in the caller or to pass a pointer to a large data object to avoid the overhead of passing the object
by value (which incurs the time and memory overheads of making a copy of the object).
In C, you use pointers and the indirection operator to simulate pass-by-reference. When calling a function
with arguments that should be modified, the addresses of the arguments are passed. This is normally
accomplished by applying the address operator (&) to the variable (in the caller) whose value will be
modified. In a deeper concept, such as in arrays;
thus, arrays are not passed using operator & because C automatically passes the starting location in
memory of the array (the name of an array is equivalent to &arrayName[0]). When the address of
a variable is passed to a function, the indirection operator (*) may be used in the function to modify
the value at that location in the caller’s memory.
Examples – Parameter Passing by Value: pass-by-value
//pass by value - 11-11-2024
#include <stdio.h>
int byValue(int n);
int main(){
int num = 5;
printf("The original Number is %d ", num);
num = byValue(num);
printf("\nThe New Number is %d ", num);
return 0;
}
int byValue (int n){
int cube;
cube = n*n*n;
return cube;
}

Examples – Parameter Passing by reference: pass-by-reference

//pass by reference - 11-11-2024


#include <stdio.h>
void byReference(int *nPtr); //beacuse it is not returning a value - void
int main(){
int num = 5;
printf("The original Number is %d ", num);
byReference(&num);//invoke the function
printf("\nThe New Number is %d ", num);
return 0;
}
void byReference (int *nPtr){
*nPtr = *nPtr * *nPtr * *nPtr;
//return cube; // no return statement is used because address is returned
}

Assignment.
Explain the two examples above and give your own opinion.

You might also like