Professional Documents
Culture Documents
ECE128
COMPUTER PROGRAMMING
LABORATORY MANUAL
NAME:
STUDENT ID:
GROUP:
INSTRUCTOR:
FACULTY OF ELECTRICAL ENGINEERING
UNIVERSITI TEKNOLOGI MARA
OBJECTIVES
THEORY
C is a general purpose programming language developed in 1972 by Dennis Ritchie. It was originally
designed and implemented for UNIX operating system. CodeBlocks IDE is a software for developing,
debugging, compiling and executing C or C++ program.
/*
This program was written by Siti Aminah in Mei 2013.
This program displays the sentence “C program example” on
computer screen.
*/
#include<stdio> // to include standard input/output library
Variable is a memory location that can store value. The stored value can be retrieved or modified
when necessary. Initialization of a variable means a value is given to the variable during its
declaration. When a variable is declared, its data type is given to specify what type of data can be
stored in the variable. There are four basic data types in C programming language: char, int,
float and double. Each data type has its own size. The size of a variable is the memory space
allocated in the memory required to store its value.
printf is a standard library function which can be used to output information to the display screen.
Its function is to output whatever information contained between the parentheses. For example, let’s
take the previous program’s printf statement.
The printf function is to print on the monitor screen the string of characters between the quotation
marks. You may notice that there is a ‘\n’ character at the end of the printf statement. This
character is called newline escape sequence. The function of this escape sequence is to print a
newline. Refer to textbook for more escape sequences. Now, refer to another example of printf
statement.
printf("%d\n", num);
The first argument consists of conversion specifier "%d" indicates that an integer is to be printed on
the monitor screen. The second argument contains the value to be printed represented by a variable;
in this case, the variable is num.
Formatted Output
printf can be controlled to display different format of information on the screen. Let’s revise the
printf function general form.
The format-control-string field describes the output format will be displayed on the screen.
This field is to be manipulated to get the desired output. For example, to output an integer we specify
the format-control-string with %d. The format-control-string can be controlled by
specifying the flags, field-width, precision, length and the type of conversion. The following is the
general form of format-control-string.
Table 1: Flags in C
Flag Description
blank Print a blank space before a positive value not preceded with a plus sign
The field-width specifies the size of field in which output to be printed. If the output value requires
more character than the specified field-width, the field will be expanded. Otherwise the field will
be padded with blank spaces. The field-width is optional.
The optional precision specifier for an integer indicates the minimum number of digits to be
displayed. precision for a floating-point values specifies the number of digit to appear after the
decimal point.
The length specifies the length of output value to be printed. h indicates a short values and l
indicates a long value.
The type of conversion defines the type of data to be printed and the following Table 2 lists the
available conversion.
Integer
Conversion Description
d Signed decimal integer
Floating-point
Conversion Description
f Signed floating-point with fixed-point notation
Conversion Description
c Single character
scanf is a standard library function which can be used to input information from keyboard. It takes
whatever entered from the keyboard and interprets it as specified by the conversion specifier and
stores the result in a variable. The following is an example of scanf function statement.
scanf("%d", &variable);
The first argument consists of conversion specifier "%d" indicates that an integer is to be read from the
standard input which is usually the keyboard. The second argument is where we specify the variable
to be used to store the input integer. Notice that the variable name starts with the ampersand (&)
character. The & is the address-of operator in C programming. It tells the scanf function the location
(address) of the memory is stored in memory.
Formatted Input
scanf can be controlled to read precise input from the keyboard. Lets revise the scanf function
general form.
The format-control-string field describes the format of the input. This field is to be manipulated
to get the desired input. The following is the format-control-string general form.
The * is the assignment suppression character. It indicates the input value that is read to be
discarded. The * is optional.
The field-width specifies the number of characters to be read by the scanf function. The
field-width is optional.
The length specifies the input is to be converted as short or long. The length is optional.
Conversion Description
d Signed decimal integer
o Octal integer
x Hexadecimal integer
c Character
s String of characters
e, f, g Floating-point
Arithmetic Operators
Arithmetic operations can be performed in C programming language. There are five operators
available in C which are + (addition), - (subtraction), * (multiplication), / (division) and % (modulus).
Multiplication, division and modulus have higher precedence over the addition and subtraction.
PROCEDURE
PART A: WELCOME TO C
1. Create a folder in My Document folder. Name the folder with your student number and name.
Example: 202xxxxxxx Aziyah
2. Save all your works in the created folder. At the end of the laboratory, copy the directory into your
USB drive for backup.
4. Now go to File, choose New and click Project. A dialog box will be opened, choose Console
Application and press Go. Click Next on the next windows. Select C and press Next. Give the
project title 1-Welcome. In the ‘Folder to create project in’ field, navigate to your created
directory previously. Then press Next. The dialog box can be seen in Figure 2.
5. Once the project title is specified, press Next button. Finally, on the next window, press Finish
button.
6. Once Finish button is pressed, you should have a workspace similar to the Figure 3. As can be
seen at the left pane of Figure 3, 1-Welcome project is created.
Figure 3: 1-Welcome project is created
7. Now if you double click the directory Sources, you can see main.c file. This is your C source file.
Now double click main.c file to open the file. Once the file is open, the file’s content will be
displayed on editor window as shown in Figure 4. The editor window is the place where you will
be writing your C code.
Figure 4: Editor window
8. As can be seen on the editor, the source file contains a few lines of C code. The code and its
explanation are given below.
#include <stdlib.h>
printf("Hello world!\n");
Build button
10. The result of building the program can be seen at the output window (below editor window). If
there are errors during the build process, the errors in the code must be identified and corrected.
Assume that the output window reporting zero error and warning, press the ‘Run’ button to
execute the code. Observe the output.
11. Now change the “Hello world!” to “Welcome to ECE128 course”. Build and execute the program
and observe the output.
PART B: VARIABLES AND DATA TYPES
4. Repeat the procedure in step 3 for the following variables in Table 4. Note that single quotes (‘ ‘)
are required to assign a value to a char type variable (var2).
Table 4
-----
Variable Value
5. Use printf to output the content of the variables. The following statement outputs the content of
variable var1.
6. Repeat the procedure to output the content of variables var2, var3 and var4 using their
corresponding conversion specifiers like %c, %f and %lf.
7. Execute the program and observe the output.
8. In the previous procedures, each variable is declared and assigned a value with statements such
as:
int var1;
var1 = 5;
The declaration and assignment can be combined into a single statement and produces the same
result. This step is called initializing a variable while declaring it.
Rearrange step 3 above by typing:
int var1 = 5;
printf("%d %d %d",var1,var2,var3);
printf("%10d\n", var1);
printf("%5f\n", var2);
printf("%20f\n", var3);
8. Execute the program and when ask for input, type: 505, 505.505 and 505.505. Observe and
relate the output with %10d, %5f and %20f in the printf statements.
9. Modify the printf statements into the following statements
printf("%.9d\n", var1);
printf("%.6f\n", var2);
printf("%.2f\n", var3);
10. Execute the program and when ask for input, type: 592, 251.8658 and 1.5268. Observe and try to
relate the output with the %.9d, %.6f and %.2f in the printf statements.
EXERCISE
1. Write a program that converts the temperature 0, 100 and 212 in degree Fahrenheit to degree
Celcius. Use the formula:
celcius = (5.0 / 9.0) * (fahrenheit – 32);
Display the converted temperatures up to 3 decimal places. The output should be printed in two
right-justified columns as shown in Figure 6.
FAHRENHEIT CELCIUS
0 -17.778
100 37.778
212 100.000
EXPERIMENT 2
OBJECTIVES
1. To use the if selection statement and the if...else selection statement to select actions.
2. To understand and use the equality and relational operators in the conditional statements.
3. To understand multiple selection using the switch selection statement.
THEORY
Executable C statements either perform actions or make decisions. We might make a decision in a
program, for example, to determine if a person’s grade on an exam is greater than or equal to 60 and
if it is to print the message “Congratulations! You Passed”. This section introduces a simple version of
C’s if statement that allows a program to make a decision based on the truth or falsity of a statement
of fact called a condition.
If the condition is met (true) the statement in the body of the if statement is executed. If the condition
is not met (false) the body statement is not executed. Whether the body statement is executed or not,
after the if statement completes, execution proceeds with the next statement after the if statement.
Condition in if statements are formed by using the equality operators and relational operators are
summarized in Table 2 below.
C equality or relational Example of C condition Meaning of C condition
operator
== x == y x is equal to y
!= x != y x is not equal to y
If Selection Statement
Selection structures are used to choose among alternative courses of action. For example, suppose
the passing grade on an exam is 60. The pseudocode statement is
This determines if the condition “student’s grade is greater than or equal to 60” is true or false. If the
condition is true, then “Passed” is printed, and the next pseudocode statement in order is “Performed”.
If the condition is false, the printing is ignored and the next pseudocode statement in order is
performed.
printf(“Passed\n”);
performed when the condition is true than when the condition is false. For example, the pseudocode
statement:
prints “Passed” if the student’s grade is greater than or equal to 60 and prints failed if the student’s
grade is less than 60. In either case, after printing occurs, the next pseudocode statement in
sequence is performed. Note that the body of the else is also indented.
Nested if… else statements test for multiple cases by placing if… else statements inside if… else
statements. For example, the following pseudocode statement
May be written in C as
The if selection statement expects only one statements in its body. To include several statements in
the body of an if, enclose the set of statements in braces ( { and } ).
Occasionally, an algorithm will contain a series of decisions in which a variable or expression is tested
separately for each of the constant integral values it may assume, and different actions are taken.
This is called multiple selections. The Switch statement consists of a series of case labels and an
optional default case.
switch (value) {
case ‘1’:
printf(“1”);
break;
case ‘2’:
printf(“2”);
break;
default:
printf(“other”);
break;
}
Here, value is a variable. If the content of value is 1, the statement printf(“1”); is executed.
Then, break; is executed to exit from the switch statement without checking the rest of other cases.
If the content of value is 2, the statement printf(“2”); is executed. Then, break; is executed to
exit from the switch statement without checking the rest of other cases. If the content of value is other
than 1 and 2, the statement printf(“other”); is executed. Then, break; is executed to exit from
the switch statement without checking other cases. Note that the break; statement is optional at the
end of each cases. Without which, all cases will be checked.
PROCEDURE
PART A
1. Consider the program in Listing 2-1. The program asks the user to enter a password. Determine
what is printed next if the user enters a password:
a) 10
b) 11
By using CodeBlocks, key-in, build and run the program to verify your answer.
#include <stdio.h>
#include <stdlib.h>
int main() {
int answer=977;
int password;
printf("enter your password: ");
scanf("%d", &password);
if(password == answer){
printf("Correct password \n");
}else{
printf("FAILED ATTEMPT\n");
}
return 0;
}
Listing 2-1
2. Consider the program in Listing 2-2. The program asks the user to enter two numbers.
Determine what is printed next if the user enters the following numbers:
a) first number = 9, second number = 4
b) first number = 6, second number = 8
c) first number = 3, second number = 3
By using CodeBlocks, key-in, build and run the program to verify your answer.
#include <stdio.h>
#include <stdlib.h>
int main() {
int first,second,ans;
char *polarity;
printf(" variable x : ");
scanf("%d",&first);
printf("\n variable y: ");
scanf("%d",&second);
ans = first - second;
printf("\n x - y = %d \n", ans);
if(ans >= 0){polarity = "Positive";}
else {polarity = "Negative";}
printf("\n Answer (%d) is a %s number \n", ans, polarity);
printf("Thank you \n");
return 0;
}
Listing 2-2
3. Consider the program in Listing 2-3. The program asks the user to enter two numbers.
Determine what is printed next if the user enters:
a) x = 13, y = 8
b) x = 8 , y = 13
c) x = 8, y = 8
By using CodeBlocks, key-in, build and run the program to verify your answer.
#include <stdio.h>
#include <stdlib.h>
int main() {
int x,y;
char *comparison;
printf(" variable x: ");
scanf("%d",&x);
printf("\n variable y: ");
scanf("%d",&y);
Listing 2-3
4. Consider the program in Listing 2-4. The program asks the user to enter an alpha character (ie.
a,b,c,…,z). Determine what is printed next if the user enters the following alpha characters:
a) a
b) b
c) c
d) d
e) y
By using CodeBlocks, build and run the program to verify your answer.
#include <stdio.h>
#include <stdlib.h>
int main() {
char alph;
printf(“enter an alpha character: “);
scanf(“%c”,&alph);
switch(alph) {
case ‘a’:
printf(“\n Your entered ‘a’ \n”);
break;
case ‘b’:
printf(“\n Your entered ‘b’ \n”);
break;
case ‘c’:
printf(“\n Your entered ‘c’ \n”);
break;
default:
printf(“\n Your entered other than a/b/c \n”);
break;
}
printf(“Thank you.\n”);
return 0;
}
Listing 2-4
PART B
1. Write a C program using if…else if statement based on the pseudo code in Figure 2.2. This
program prompts user for two integers. It finds whether the first integer is greater than, less than
or equal to the second integer.
2. Using switch..case statement, write a C program based on Figure 2.4. This program prompts
user to enter A, B or C and display an output based on user’s input.
Input Output
Figure 2.4
EXERCISES
1. By using an if..else statement, design a C program that asks the user to input an integer
number between 1 and 20. After the user has input the number and press ENTER, the
program will display whether the number is odd or even. Examples of program output are
shown as followings:
Hint: use modulus operator (%). An even number, when divided by 2 produces zero
remainder. An odd number, when divided by 2 produces a non zero remainder.
2. By using a nested if .. else statement, design a C program that asks the user to input
two integer numbers and choose what arithmetic operations (+, -, x or /) to perform on those
numbers. After the user has input the numbers and choose the arithmetic operation, the
program will display the arithmetic statement with the result. The arithmetic statement is
displayed in the following format: <first number> <arithmetic operation><second number> =
<result>. If the arithmetic statement entered by user is unknown (eg. & is entered), the
program output an error message. Examples of program output are shown as followings:
EXPERIMENT 3
REPETITIVE STATEMENT
OBJECTIVES
THEORY
C provides the unary increment operator, ++, and the unary decrement operator, --. If a variable c is
incremented by 1, the increment operator ++ can be used rather than the expressions c = c + 1; or c
+= 1;
If increment or decrement operators are placed before a variable (prefixed), they are referred to as the
preincrement or predecrement operators, respectively. Preincrementing/predecrementing a variable
causes the variable to be incremented/decremented by 1, and then the new value of the variable is
used in the expression in which it appears.
Postincrementing/postdecrementing the variable causes the current value of the variable to be used in
the expression in which it appears, and then the variable value is incremented/decremented by 1.
A repetition statement allows you to specify that an action is to be repeated while some condition
remains true. The pseudocode statement:
describes the repetition that occurs during a shopping trip. The condition, “ There are more items on
my shopping list” may be true or false. If it is true, then the action, “Purchase next item and cross it off
my list” is performed.
The statement contained in the while repetition statement constitute the body of the while. The while
statement body may be a single statement or a compound statement. Eventually, the condition will
become false. At this point, the repetition terminates, and the first pseudocode statement after the
repetition structure is executed.
int x = 1;
while (x <= 3){
printf(“%d “,x);
x = x + 1;
First, variable x is is declared and initialized to 1. Then, while statement is executed for the first time.
The while statement checks the condition (x <= 3). Currently, x = 1. Since (1 <= 3) is true, the
condition becomes True. So, the body of the while statement is executed. The content of variable x
is printed on screen (i.e. 1 ). Then, x is incremented to 1 (i.e. x = 2).
The while statement is executed again by checking the condition (x <= 3). Now, x=2. Since (2 <= 3)
is true, the condition (x <= 3) becomes True. So, the body of the while statement is executed again.
The content of variable x is printed on screen (i.e. 2). Then, x is incremented to 1 (i.e. x = 3).
The while statement is executed again by checking the condition (x <= 3). Now, x=3. Since (3 <= 3)
is true, the condition (x <= 3) becomes True. So, the body of the while statement is executed again.
The content of variable x is printed on screen (i.e. 3). Then, x is incremented to 1 (i.e. x = 4).
The while statement is executed again by checking the condition (x <= 3). Now, x=4. Since (4 <= 3)
is false, the condition (x <= 3) becomes False. So, the body of the while statement is not executed.
The program exits the while statement.
The do .. while loop is also a kind of loop, which is similar to the while loop in contrast to while
loop, the do..while loop tests at the bottom of the loop after executing the body of the loop. Since
the body of the loop is executed first and then the loop condition is checked we can be assured that
the body of the loop is executed at least once.
do
statement;
while(expression);
Here the statement is executed, then expression is evaluated. If the condition expression is true then
the body is executed again and this process continues till the conditional expression becomes false.
When the expression becomes false, the loop terminates.
First, variable x is is declared and initialized to 1. Then, the body of while statement is executed for
the first time. The current content of x is printed on screen (i.e. 1). Then, x is incremented (i.e. now, x
= 2). Finally, the condition (x <= 3) is checked. Since (2 <= 3) is true, the condition (x <= 3) becomes
True. So, the body of while is executed again. The current content of x is printed on screen (i.e. 2).
Then, x is incremented (i.e. now, x = 3). Finally, the condition (x <= 3) is checked. Since (3 <= 3) is
true, the condition (x <= 3) becomes True. The body while is executed again. The current content of
x is printed on screen (i.e. 3). Then, x is incremented (i.e. now, x = 4). Finally, the condition (x <= 3) is
checked. Since (4 <= 3) is false, the condition (x <= 3) becomes False. The body of the while
statement is NOT executed and the while() loop terminates.
The for loop provides a more concise loop control structure. The general form of the for loop is:
Just as the need may arise to include more than one expression in a particular field of the for
statement, so too may the need arise to omit on or more fields from the for statement. This can be
done simply by omitting the desired filed, but by marking its place with a semicolon. The
init_expression field can simply be “left blank” in such a case as long as the semicolon is still included:
for(;j!=100;++j)
Sometimes while executing a loop it becomes desirable to skip a part of the loop or quit the loop as
soon as certain condition occurs, for example consider searching a particular number in a set of 100
numbers as soon as the search number is found it is desirable to terminate the loop. C language
permits a jump from one statement to another within a loop as well as to jump out of the loop. The
break statement allows us to accomplish this task. A break statement provides an early exit from
for, while, do and switch constructs. A break causes the innermost enclosing loop or switch
to be exited immediately.
During loop operations it may be necessary to skip a part of the body of the loop under certain
conditions. Like the break statement C supports similar statement called continue statement. The
continue statement causes the loop to be continued with the next iteration after skipping any
statement in between. The continue with the next iteration the format of the continue statement is
simply:
continue;
Consider the following program that finds the sum of five positive integers. If a negative number is
entered, the sum is not performed since the remaining part of the loop is skipped using continue
statement.
PROCEDURE
8 printf( “a = %d\n”,a);
9 printf( “b = %d\n”,b);
10 a=a-1;
11 b-=1;
12 printf( “a = %d\n”,a);
13 printf( “b = %d\n”,b);
/*preincrement*/
14 c=5;
15 printf( “%d\n”,c);
16 printf( “%d\n”,++c);
17 printf( “%d\n”, c);
/*postincrement*/
18 c=5;
19 printf( “%d\n”,c);
20 printf( “%d\n”, c++);
21 printf( “%d\n”, c);
22 return 0;
23 }
Listing 3-1
PART B: t
1. Listing 3-2 is a program that finds the average of five (5) marks entered by user. At the end of the
while() statement, the average is calculated and displayed on screen. Referring to the Listing 3-
2,
i. Fill in the Table 3-2 on the content of variables total and counter after each repetition
of the while statement.
ii. Determine the output display for the last printf statement.
#include <stdio.h>
#include <stdlib.h>
int main () {
int counter =0;
int total = 0;
int mark = 0;
int average = 0;
average = total/5;
printf( “class average is %d\n”, average);
return 0;
}
Listing 3-2
Repetition no of
while User input for mark total counter
statement
1 9
2 8
3 5
4 6
5 2
Table 3-2
2. Rewrite the program in Listing 3-2 using a do…while statement so that the output is still the
same as before.
1. Listing 3-3 is a program that finds the sum of ten (10) positive even numbers (i.e. 2 + 4 + 6 + … +
20) and the sum of their squares (i.e. 2 2 + 42 + 62 + … + 202). Fill in the Table 3-3 below on the
content of variables i, sum and squares after each repetition of the for statement.
#include <stdio.h>
#include <stdlib.h>
int main () {
int i;
int sum = 0;
int squares = 0;
for(i = 2;i<=20;i+=2){
sum+= i;
squares += i * i;
}
printf(“sum of first 10 positive even numbers = %d\n”,sum);
printf(“sum of their squares = %d\n”,squares);
return 0;
}
Listing 3-3
Table 3-3
1 2
9
Repetition no of i sum squares
while statement
10
1. Listing 3-4 below shows a break statement inside an infinite while loop. For each repetition of
the while statement, the user is asked to enter a mark (an integer number). If the user input the
values as shown in Table 5, determine the values of variables sum and num for each repetition of
the while() statement. Explain what happen after a user had entered the mark as -1.
#include<stdio.h>
int main() {
int x;
int num = 0;
int sum = 0;
while (1)
{
printf(“\n Input a mark: “);
scanf(“%d”, &x);
if( x == -1) {
break;
}
sum += x;
num++;
}
return 0;
}
Listing 3-4
Table 5
1 30
2 20
3 0
4 23
5 -1
2. Listing 3-5 shows a continue statement inside a for loop. Fill in the values of variables x and
y in Table 6 for each repetition of the for statement.
#include<stdio.h>
int main() {
int x;
int y = 0;
for( x = 1; x <= 10; x++) {
if( x == 5) {
continue;
}
y++ ;
printf(“%d”,x);
}
return 0;
}
Listing 3-5
Table 6
Repetition no of x y
for statement
1
8
9
10
EXERCISE
i. Lines 4, 6 and 7 are incomplete. Complete the code by filling in the blanks.
ii. Rewrite the code in Listing 3-6 using a do..while statement so that the same output is
produced.
8 }
9 }
10 return 0;
11 }
Listing 3-6
1 2 3
4 5 6
7 8 9
Output for Listing 3-6
2. Design a C program that requires a user to enter 4 integer numbers. The numbers entered can be
positive or negative integers. After the user had entered the four (4) numbers, the program will
add all the negative numbers together and display the result. You are required to use a for
statement in your program. Examples of outputs are shown below:
Enter a number: - 2 <ENTER>
Enter a number: 9 <ENTER>
3. With the aid of a break statement inside the while statement, complete the program in Listing
3-7 so that the sum of integers from start to end can be calculated. Note that the start and end
numbers must be different integer numbers. For example, if the start and end integers are 4 and 7
respectively, the sum of integers between those two numbers is 4 + 5 + 6 + 7 = 22. Use
CodeBlocks to test your program.
#include<stdio.h>
int main()
{
int start,end;
int sum = 0;
printf(“Start integer: “);
scanf(“%d”, &start);
printf(“\nEnd integer: “);
scanf(“%d”, &end);
while (1){
}
printf(“The sum between %d and %d is %d\n”,start,end,sum);
return 0;
}
Listing 3-7
4. Using a for loop, write a program to ask user to enter 10 integers. The program calculates the
sum of any even integers entered by the user and counts the total number of odd integers.
5. Using a while loop, write a program to print the following sequence:
i) 10 9 8 7 6 5 4 3 2 1 0
ii) 0 2 4 8 10
EXPERIMENT 4
FUNCTIONS
OBJECTIVES
THEORY
Function in C
A function is a complete and independent program which is used (or invoked) by the main program or
other subprograms. A subprogram receives values called arguments from a calling program, performs
calculations and returns the results to the calling program.
First of all a function can be thought of as a way to store a procedure. This procedure contains some
instructions that you want to carry out many times. Also it's a way to structure your program. It can
also be regarded as a function in a more mathematical sense. A wide variety of functions are
available in the standard library, glibc (Some of these are actually in the math library, accessed by
linking the program with -lm).
function_body
#include<stdio.h>
void statement1();
void statement2();
void starline();
main()
{ statement1();
statement2();
starline();
}
void statement2()
{ printf("Sample subprogram output two\n");
}
void starline()
{ int a;
for (a=1;a<30;a++)
printf("%c",'*');
printf("\n");
}
In the above example there is no data transfer between the calling function and the called function.
When a function has no arguments it does not receive any data from the calling function. Similarly
when it does not return value the calling function does not receive any data from the called function. A
function that does not return any value cannot be used in an expression it can be used only as
independent statement.
The nature of data communication between the calling function and the arguments to the called
function and the called function does not return any values to the calling function this shown in
example below:
value (500,0.12,5)
Would send the values 500,0.12 and 5 to the function value (p, r, n) and assign values 500 to p, 0.12
to r and 5 to n. the values 500,0.12 and 5 are the actual arguments which become the values of the
formal arguments inside the called function.
Both the arguments actual and formal should match in number type and order. The values of actual
arguments are assigned to formal arguments on a one to one basis starting with the first argument as
shown below:
main()
{
function1(a1,a2,a3);
}
function1(f1,f2,f3);
{
function body;
}
here a1,a2,a3 are actual arguments and f1,f2,f3 are formal arguments.
The no of formal arguments and actual arguments must be matching to each other suppose if actual
arguments are more than the formal arguments, the extra actual arguments are discarded. If the
number of actual arguments are less than the formal arguments then the unmatched formal
arguments are initialized to some garbage values. In both cases no error message will be generated.
The formal arguments may be valid variable names, the actual arguments may be variable names
expressions or constants. The values used in actual arguments must be assigned values before the
function call is made.
When a function call is made only a copy of the values actual arguments is passed to the called
function. What occurs inside the functions will have no effect on the variables used in the actual
argument list. Let us consider the following program :
main()
{
int a,b;
printf("Enter the two numbers\n");
scanf("%d %d",&a,&b);
largest(a,b);
}
The function of the type Arguments with return values will send arguments from the calling function to
the called function and expects the result to be returned back from the called function back to the
calling function.
To assure a high degree of portability between programs a function should generally be coded without
involving any input output operations. For example different programs may require different output
formats for displaying the results. Theses shortcomings can be overcome by handing over the result
of a function to its calling function where the returned value can be used as required by the program.
In the above type of function the following steps are carried out:
1. The function call transfers the controls along with copies of the values of the actual arguments of
the particular function where the formal arguments are creates and assigned memory space and are
given the values of the actual arguments.
2. The called function is executed line by line in normal fashion until the return statement is
encountered. The return value is passed back to the function call is called function.
3. The calling statement is executed normally and return value is thus assigned to the calling function.
Note that the value return by any function when no format is specified is an integer.
C function returns a value of type int as the default data type when no other type is specified explicitly.
For example if function does all the calculations by using float values and if the return statement such
as return (sum); returns only the integer part of the sum. This is since we have not specified any
return type for the sum. There is the necessity in some cases it is important to receive float or
character or double data type. To enable a calling function to receive a non-integer value from a
called function we can do the two things:
1. The explicit type specifier corresponding to the data type required must be mentioned in the
function header. The general form of the function definition is
The type specifier tells the compiler, the type of data the function is to return.
2. The called function must be declared at the start of the body in the calling function, like any other
variable. This is to tell the calling function the type of data the function is actually returning. The
program given below illustrates the transfer of a floating-point value between functions done in a
multiple function program:
#include<stdio.h>
int add(a,b);
int sub(p,q);
main()
{
int x,y;
x=12;
y=9;
printf("%d\n", add(x,y));
printf("%d\n", sub(x,y));
}
int add(a,b)
{
return(a+b);
}
int sub(p,q)
{
return(p-q);
}
We can notice that the functions too are declared along with the variables. These declarations clarify
to the compiler that the return type of the function add is float and sub is double.
Recursion
Recursive function is a function that calls itself. When a function calls another function and that
second function calls the third function then this kind of a function is called nesting of functions. But a
recursive function is the function that calls itself repeatedly.
A simple example:
main()
main();
}
when this program is executed. The line is printed reapeatedly and indefinitely. We might have to
abruptly terminate the execution.
PROCEDURE
PART A
PART B
1. Modify the previous program in PART A by adding a new function prototype of a function named
loop of type void.
2. Modify the main function to have only one line of statement as below:
main( )
{
loop( ); //a function call
}
3. Type the following statements in the loop function definition:
int x;
for(x=1; x<=10; x++)
{ printf("%d\t ",square(x));
}
printf("\n");
PART C
1. Explain the operation of the code in Listing 4-1. Support the explanation with a sample of output.
#include <stdio.h>
int factorial(int number);
int main()
{
int i;
for(i=1; i<=4; i++)
{
printf("%d! = %d\n" , i, factorial(i));
}
}
int factorial(int number)
{
int res;
if(number<= 1)
{
return 1;
}
else
{
res=number*factorial(number-1);
return(res);
}
}
Listing 4-1
PART D
1. Write a function using C to calculate the sum of two integers. The function is being called from the
main program and it returns the result to the main program. The function has the following
characteristics.
a) Function name : addiere()
b) Function parameters: summand1, summand2
c) Parameter data type: int
d) Function return data type: int
Sample output:
This is a program to add two integers.
Please enter two integers:
>>3
>>2
The sum of the integers is 5.
Figure 4-1
2. Refer to the flowchart in Figure 4-2. Write a program based on the flowchart.
Figure 4-2
3. Write a program to include a function that calculates the count of odd integers entered by a user.
Follow the hints for the program:
a) Write a function prototype as int determine(int x);.
b) In the main program, user is prompted for 5 integers. Use for loop.
c) Each time user enters an integer, the integer will be passed to the function
determine(int x).
d) The function will determine whether the integer is an even or odd integer. A variable
counter used in the function is declared as a global variable. Use % to determine odd
number. If it is odd, the counter will be increased by one.
e) The total count of odd integers will be returned to the main program and be displayed.
Sample output:
This program counts the occurrence of odd integers.
Please enter five integers:
>>3
>>2
>>1
>>2
>>4
EXERCISE
long factorial(long n)
{ if (n == 0 || n == 1)
return 1;
else
return n *
factorial(n - 1);
}
i. Is this partial program is function declaration or function definition?
ii. State two(2) differences between function declaration and function definition.
iii. Is this function has any parameter? Explain why.
iv. In your opinion, discuss the benefit of recursion.
4. Define a function called calculator that calculates sum of ten numbers that have been given
by the user. Write a complete program and test the result correctly.
EXPERIMENT 5
ARRAY
OBJECTIVES
5. To use the array data structure to represent lists and tables of values.
6. To define an array, initialize an array and refer to individual elements of an array.
7. To pass arrays to functions.
8. To use arrays to store, sort and search lists and tables of values.
9. To define and manipulate multiple-subscripted arrays.
THEORY
All the elements of an array occupy a set of contiguous memory locations and by using an index or
subscript we can identify each element. For example, instead of declaring mark1, mark2, ..., markN to
store and manipulate a set of marks obtained by the students in certain courses, we could declare a
single array variable named mark and use an index, such as N, to refer to each element in mark. This
absolutely has simplified declaration of the variables.
For example, if 100 list of marks of integer type, they can be declared as follows:
int mark[100];
This will reserve 100 contiguous/sequential memory locations for storing the integer data type.
Array Initialization
An array may be initialized at the time of its declaration, which means to give initial values to an array.
Initialization of an array may take the following form:
The first line declares an integer array id and it immediately assigns the values 1, 2, 3, ..., 7 to id[0],
id[1], id[2],..., id[6].
In the second line assigns the values 5.6 to x[0], 5.7 to x[1], and so on.
Similarly the third line assigns the characters ‘a’ to vowel[0], ‘e’ to vowel[1], and so on. Note again, for
characters we must use the single apostrophe (’) to enclose them. Also, the last character in the
array vowel is the NULL character (‘\0’).
Initialization of an array of type char for holding strings may takes the following form:
For example, the array vowel in the above example could have been written more compactly as
follows:
When the value assigned to a character array is a string (which must be enclosed in double quotes),
the compiler automatically supplies the NULL character but we still have to reserve one extra place for
the NULL.
Two-Dimensional Array
Dimension of array is the number of indices required to reference an element. For example,
arrayOfInts[0] is the first element. The index is 0; there is only 1 index so arrayOfInts is one
dimensional.
Now suppose if arrayOfInts[0] needs to hold 2 integers, therefore it will move into the next dimension;
arrayOfInts[0][0] could hold the first integer, and arrayOfInts[0][1] could hold the other. We need 2
indices to reference each integer, so arrayOfInts is two dimensional. 2-dimensional arrays are useful
for storing grid-base information, like coordinates.
This tells the computer to reserve enough memory space for an array with 12, that is, 3 x 4 elements.
One way to picture these 12 elements is an array with 3 rows and 5 columns.
Graphically can be depicted as:
PROCEDURE
int i;
for(i=0; i<4; i++)
printf("%c\t %c\t %d\n\n", huruf[i], nama[i], num[i]);
6. Execute the program and insert integer numbers for all num array elements. Observe the output.
printf("Array: ");
for(i=0; i<max; i++)
printf("%d ", num[i]);
large = num[0];
small = num[0];
if(num[i]<small)
small = num[i];
}
7. Using printf statement, print out the large and small values.
8. Execute the program and observe the output.
return 0;
EXERCISES
1. Write a program to declare and initialize an array memo[] with the values as shown in
Figure 5-1. Write printf statements to display the value of memo[1] and memo[3].
4 5 7 9 13 2
Figure 5-1
2. Figure 5-2 illustrates an array named code. Write a statement to create the array with the
assigned values as shown in Figure 5-2. Using printf statements, display the value of
code[0] and code[4].
E E 1 1 0 \0
Figure 5-2
3. Write a program that prompts user to enter 5 values and store them into an array mata. Using
a suitable loop and a printf statement, display the contents of the entire array.
Figure 5-3
FACULTY OF ELECTRICAL ENGINEERING
UNIVERSITI TEKNOLOGI MARA
EXPERIMENT 6
POINTERS
OBJECTIVES
10. To understand pointers and pointers operator.
11. To use pointers to pass arguments to functions by reference.
12. To use pointers to functions.
THEORY
Pointers
In c a pointer is a variable that points to or references a memory location in which data is stored. Each
memory cell in the computer has an address that can be used to access that location so a pointer
variable points to a memory location we can access and change the contents of this memory location
via the pointer.
A pointer is a variable that contains the memory location of another variable. The syntax is as shown
below. You start by specifying the type of data stored in the location identified by the pointer. The
asterisk tells the compiler that you are creating a pointer variable. Finally you give the name of the
variable.
type * variable name
Example:
int *ptr;
float *string;
Once we declare a pointer variable we must point it to something we can do this by assigning to the
pointer the address of the variable you want to point as in the following example:
ptr=#
This places the address where num is stores into the variable ptr. If num is stored in memory 21260
address then the variable ptr has the value 21260.
main()
{
int *ptr;
int sum;
sum=45;
ptr=∑
printf (“\n Sum is %d\n”, sum);
printf (“\n The sum pointer is %d”, ptr);
}
we will get the same result by assigning the address of num to a regular(non pointer) variable. The
benefit is that we can also refer to the pointer variable as *ptr the asterisk tells to the computer that we
are not interested in the value 21260 but in the value stored in that memory location. While the value
of pointer is 21260 the value of sum is 45 however we can assign a value to the pointer * ptr as in
*ptr=45.
This means place the value 45 in the memory address pointer by the variable ptr. Since the pointer
contains the address 21260 the value 45 is placed in that memory location. And since this is the
location of the variable num the value also becomes 45. this shows how we can change the value of
pointer directly using a pointer and the indirection pointer.
Like other variables pointer variables can be used in expressions. For example if p1 and p2 are
properly declared and initialized pointers, then the following statements are valid.
y=*p1**p2;
sum=sum+*p1;
z= 5* - *p2/p1;
*p2= *p2 + 10;
C allows us to add integers to or subtract integers from pointers as well as to subtract one pointer
from the other. We can also use short hand operators with the pointers p1+=; sum+=*p2; etc.,
we can also compare pointers by using relational operators the expressions such as p1 >p2 , p1==p2
and p1!=p2 are allowed.
The pointer are very much used in a function declaration. Sometimes only with a pointer a complex
function can be easily represented and success. The usage of the pointers in a function definition may
be classified into two groups.
1. Call by reference
2. Call by value.
Call by value
We have seen that a function is invoked there will be a link established between the formal and actual
parameters. A temporary storage is created where the value of actual parameters is stored. The
formal parameters picks up its value from storage area the mechanism of data transfer between
actual and formal parameters allows the actual parameters mechanism of data transfer is referred as
call by value. The corresponding formal parameter represents a local variable in the called function.
The current value of corresponding actual parameter becomes the initial value of formal parameter.
The value of formal parameter may be changed in the body of the actual parameter. The value of
formal parameter may be changed in the body of the subprogram by assignment or input statements.
This will not change the value of actual parameters.
Call by Reference
When we pass address to a function the parameters receiving the address should be pointers. The
process of calling a function by using pointers to pass the address of the variable is known as call by
reference. The function which is called by reference can change the values of the variable used in the
call.
Pointer to arrays
An array is actually very much like pointer. We can declare the arrays first element as a[0] or as int *a
because a[0] is an address and *a is also an address the form of declaration is equivalent. The
difference is pointer is a variable and can appear on the left of the assignment operator that is lvalue.
The array name is constant and cannot appear as the left side of assignment operator.
PROCEDURE
EXERCISE
1. Write a program to declare and initialize an integer variable num with value 10. Declare a pointer
variable and point it to variable num. Using the pointer, access the content of variable num and
add it with 2. Using printf statements, show:
2. Figure 6-2 shows the contents of an array. Write a program to initialize the array and declare a
pointer named Ptr and point it to the last element of the array. Using a printf statement, show
the content of the last element of the array that the pointer is indirectly referring to. From its
current location, write a statement that moves the pointer to the position of num[2]. Then, using
pointer Ptr, write a statement to change the content of num[2] from 7 to 100.
num[0] num[1] num[2] num[3] num[4] num[5]
4 5 7 9 13 2
Figure6- 2
a b c t \0
Figure 6-3
b) Declare a pointer charPtr and point it to the zeroth element of array huruf.
c) By incrementing and decrementing the position of pointer charPtr and using printf statements,
display the word cat on the computer screen.
4. The code in Listing 6-1 shows a program with a function named passRef. In the main function,
the reference (address) of the variables num1 and num2 are passed to function passRef. This is
called pass-by-reference. Write and run the code to see the result.
#include <stdio.h>
int passValue(int num1, int num2);
int main()
{
int num1=10,num2=100;
printf(" Num1 = %d Num2 = %d\n",num1,num2);
passValue (num1,num2);
printf(" Num1 = %d Num2 = %d\n",num1,num2);
}
int passValue(int num1, int num2)
{
num1= 20;
num2= 2000;
}
Based on the program code in Listing 6-1, write a new program to declare and initialize two
integers num1=10 and num2=100. Using a printf statement, display the values of num1 and num2.
From the main function, pass the two variables num1 and num2 to a function named passValue.
The function prototype can be written as int passValue(int num1, int num2). In function
passValue, assign 20 to num1 and 2000 to num2.
The function does not return any value. In the main function, once again, write a printf
statement to print the values of num1 and num2. Compare the result with the one obtained from
Listing 6-1 above.