You are on page 1of 66

UNIVERSITI TEKNOLOGI MARA

SCHOOL OF ELECTRICAL ENGINEERING

ECE128
COMPUTER PROGRAMMING
LABORATORY MANUAL

NAME:

STUDENT ID:

GROUP:

INSTRUCTOR:
FACULTY OF ELECTRICAL ENGINEERING
UNIVERSITI TEKNOLOGI MARA

COMPUTER PROGRAMMING LABORATORY


(ECE128)
EXPERIMENT 1

INTRODUCTION TO C PROGRAMMING AND


FORMATTED I/O

OBJECTIVES

1. To familiarise with CodeBlocks Integrated Development Environment (IDE)


2. To learn how to write coding, debugging, compiling and executing C codes using CodeBlocks IDE
3. To learn how to use printf and scanf function
4. To perform basic arithmetic operations
5. To control the output and input format using printf and scanf

THEORY

C Language with CodeBlocks

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.

Now let’s look at an example of 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

/* main function definition */


int main()
{
printf("C program example\n");
return 0;
}
The first few lines in the program are not actually part of the program. These are simply lines of
comment and are included to provide information on what the program does. A comment begins with
/* and end with */. A single line comment can also begin with //. Basically, a C program consists of
two sections, the pre-processor directives and the main function sections. The pre-processor section
is the place where we specify what compiler should do before compiling the source code. Usually we
would specify the included header file which will be used in our program. A header file keeps all the
information about functions available in standard C library. All pre-processor directives begins with the
# symbol.
The second section begins with the function main() definition. The function main() is where the
program starts its execution. The keyword int at the beginning indicates that function main()
returns value of type integer. The returns value will be explained in Chapter C Functions later. For
now, just include the keyword int before the main in each of your programs. The body of the function
main() is between the { (open) and } (close) braces. Within this body is where we write all the
statements that defines what our program does. At the end of function main() we have to include
return 0 statement. This indicates that the program has terminated successfully.

Variables and Data Types

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.

Outputting Information using printf

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.

printf("C program example\n");

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.

printf(format-control-string, other arguments);

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.

% flags field-width precision length type of conversion

The % character indicates the start of the specifier.


The flags specifier is optional. Table 1 lists the available flags that can be specified.

Table 1: Flags in C

Flag Description

+ Display a plus sign preceding the positive value

- Left justify the output within the specified field-width

# Display 0 preceding an octal output value and 0x or 0X preceding an


hexadecimal output value

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.

Table 2: Type of conversion in C

Integer

Conversion Description
d Signed decimal integer

o Unsigned octal integer

u Unsigned decimal integer

Unsigned hexadecimal integer. x displays the letters a – f and X


x or X
displays A - F

Floating-point

Conversion Description
f Signed floating-point with fixed-point notation

e or E Signed floating-point with exponential notation

Signed floating-point with either fixed-point or exponential notation


g or G
depending on the magnitude of the value

Character and String

Conversion Description
c Single character

s Characters until a '\0' is encountered


Inputting Information using scanf

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.

scanf(format-control-string, other arguments);

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.

% * field-width length type of conversion

The % character indicates the start of the specifier.

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.

The type of conversion defines the type of data to be read and


lists the available conversion.

Table 3: Type of conversions in C

Conversion Description
d Signed decimal integer

i Signed decimal, octal or hexadecimal integer

o Octal integer

u Unsigned decimal 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.

3. Open CodeBlocks. Go to All Programs  CodeBlocks  CodeBlocks. The workspace of


CodeBlocks can be seen in Figure 1.

Figure 1: The CodeBlocks workspace

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.

Figure 2: Creating a new project

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.

Tell the compiler to include input/output library


#include <stdio.h>

#include <stdlib.h>

Define a function called main


int main()

printf("Hello world!\n");

return 0; Main function call library output


function to print the text enclose by
} double quote.

The ‘\n’ is used to print a new line.


Implies normal termination of program

Open and close braces enclose the main function


9. Now, execute (run) the source code (program) to see the output of the program. Before you can
execute it, the code must be built (compiled) first. Compiling a C code is achieved by pressing
button ‘Build’ as shown in Figure 5. Compiling a code can also be achieved by selecting Build
menu and choose Build. Upon pressing the build button, the source code will be compiled, linked
and an executable (*.exe) file will be made.

Build button

Figure 5: Building the source code

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

1. Create a new project named 1-DataType.


2. Include the stdio.h header file and define the main() function.
3. Type the following statements to declare the variables.
int var1; // declare variable var1 type int
var1 = 5; // store value of 5 into variable var1

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

var2 char 'a'

var3 float 10.54

var4 double 205.7526

5. Use printf to output the content of the variables. The following statement outputs the content of
variable var1.

printf("The value of variable var1 is %d\n", 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;

9. Repeat the procedure for var2, var3 and var4.


10. Execute the program and observe the output.
PART C: USE SCANF TO READ INTEGERS

1. Create a new project named 1-Input.


2. Include the stdio.h header file and define the main function.
3. Declare two variables named var1 and var2 type int.
4. Use printf to display "Enter two numbers: " on the monitor screen.
5. Type the following statement
scanf("%d", &var1);

6. Repeat the above statement for var2.


7. Use printf to output the contents of variables var1 and var2.
8. Execute the program and observe the output.
9. Replace both scanf statements with the following statement.

scanf("%d%d", &var1, &var2);

10. Execute the program and observe the output.

PART D: USING CONVERSION SPECIFIERS

1. Create a new project named 1-ConvSpecifier.


2. Include the stdio.h header file and define the main() function.
3. Declare a variable named var1 type char.
4. Declare three variables named var2, var3 and var4 type int.
5. Declare a variable named var5 type float.
6. Type the following statements. The first scanf statement reads a character. The next three
scanf statements read decimal, octal and hexadecimal integers. The last scanf statement
reads a floating-point number.
printf("Enter a character:\n");
scanf("%c", &var1);
printf("Enter three same decimal number:\n");
scanf("%d", &var2);
scanf("%o", &var3);
scanf("%x", &var4);
printf("Enter a floating-point number:\n");
scanf("%f", &var5);
7. Output var1 using printf statement and %c specifier.
8. Output var2, var3 and var4 variables using printf statement and their %d conversion
specifiers since var2, var3 and var4 are type int.
9. Output var5 using printf statement and %f specifier.
10. Execute the program. Use these data as inputs: T for character, 155 for decimal numbers and
55.135 for floating-point number. Observe the output.

PART E: READING INPUT WITH FIELD-WIDTH

1. Create a new project named 1-InputFieldWidth.


2. Include the stdio.h header file and define the main() function.
3. Declare three variables named var1, var2 and var3 type int.
4. Type the following statements.
printf("Enter an eight digit integers: ");
scanf("%3d%2d%d",&var1,&var2,&var3);

5. Output variable var1, var2 and var3 using:

printf("%d %d %d",var1,var2,var3);

6. Execute the program and observe the output.

PART F: FILTERING CHARACTER FROM THE INPUT STREAM

1. Create a new project named 1-InputFilter.


2. Include the stdio.h header file and define the main() function.
3. Declare three variables named var1, var2 and var3 type int.
4. Type the following statements.
printf("Enter date(e.g., 151113): ");
scanf("%2d%2d%2d",&var1,&var2,&var3);
printf("Day %d, Month %d, Year %d\n", var1,var2,var3);

5. Execute the program and observe the output.


6. Modify the above statements into the following statements.

printf("Enter date(e.g., 15-11-13): ");


scanf("%2d-%2d-%2d",&var1,&var2,&var3);
printf("Day %d, Month %d, Year %d\n", var1,var2,var3);
7. Execute the program. Observe the output.
8. Modify the above statements into the following statements.
printf("Enter date(e.g., 15/11/13): ");
scanf("%2d%*c%2d%*c%2d",&var1,&var2,&var3);
printf("Day %d, Month %d, Year %d\n", var1,var2,var3);

9. Execute the program. Observe the output.

PART G: PRINTING WITH FIELD-WIDTH AND PRECISION


1. Create a new project named 1-OutputFormat.
2. Include the stdio.h header file and define the main function.
3. Declare a variable named var1 type int.
4. Declare two variables named var2 and var3 type float.
5. Use printf to display "Enter three numbers: " on the monitor screen.
6. Use scanf to read and store three values in variables var1, var2 and var3.
7. Type the following statements.

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

Figure 6: Right justified columns


FACULTY OF ELECTRICAL ENGINEERING
UNIVERSITI TEKNOLOGI MARA

COMPUTER PROGRAMMING LABORATORY


(ECE128)

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

Equality and Relational Operators

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

> x>y x is greater than y

< x<y x is less than y

>= x >= y x is greater than or equal to y

<= x <= y x is less than or equal to y

Table 2: Equality and Relational Operators

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

If student’s grade is greater than or equal to 60


Print “Passed”

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.

The preceding pseudocode If statement may be written in C as

if (grade >= 60)

printf(“Passed\n”);

If… else Selection Statement


The if selection statement performs an indicated action only when the condition is true; otherwise the
action is skipped. The if… else selection statement allows you to specify that different action are to be

performed when the condition is true than when the condition is false. For example, the pseudocode
statement:

If student’s grade is greater than or equal to 60


print “Passed”
else
print “Failed”

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.

The preceding pseudocode if… else statement may be written in C as

if (grade >= 60)


printf(“Passed\n”);
else
printf(“Failed\n”);

Nested if… else statements test for multiple cases by placing if… else statements inside if… else
statements. For example, the following pseudocode statement

If student’s grade is greater than or equal to 90


Print “A”
Else
If student’s grade is greater than or equal to 80
Print “B”
Else
If student’s grade is greater than or equal to 70
Print “C”
Else
If student’s grade is greater than or equal to 60
Print “D”
Else
Print “F”

May be written in C as

if (grade >= 90)


printf(“A\n”);
else if (grade >= 80)
printf(“B\n”);
else if (grade >= 70)
printf(“C\n”);
else if (grade >= 60)
printf(“D\n”);
else
printf(“F\n”);

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 } ).

Switch Multiple-Selection Statement

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);

if(x > y){comparison = "Greater Than";}


else if(x < y){comparison = "Lesser Than";}
else {comparison = "Equal";}
printf("\n x (%d) is %s y (%d).\n", x, comparison, y);
return 0;
}

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.

 Print out program description and user directions


 Ask user for the first integer
 Ask user for the second integer
 Compare the first integer with the second integer
 Print out the finding
Figure 2.2

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

A Actions speak louder than words

B Ball is in your court

C Cross that bridge when you come to it

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:

Enter a number between 1 and 20: 3 <ENTER>


The number you have entered is an odd number.

Enter a number between 1 and 20: 12 <ENTER>


The number you have entered is an even number.

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:

Arithmetic operation(+,-,x,/) : + <ENTER>


Insert first number: 9 <ENTER>
Insert second number: 4 <ENTER>
9 + 4 = 13

Arithmetic operation(+,-,x,/) : x <ENTER>


Insert first number: 2 <ENTER>
Insert second number: 8 <ENTER>
2 x 8 = 16

Arithmetic operation(+,-,x,/) : & <ENTER>


Insert first number: 2 <ENTER>
Insert second number: 8 <ENTER>
Error! Unknown arithmetic operation.

3. Rewrite the program in (2) by using a switch..case statement.


FACULTY OF ELECTRICAL ENGINEERING
UNIVERSITI TEKNOLOGI MARA

COMPUTER PROGRAMMING LABORATORY


(ECE128)

EXPERIMENT 3

REPETITIVE STATEMENT

OBJECTIVES

1. To understand and use the increment, decrement and assignment operators.


2. To use the while repetition statement to execute statements in a program repeatedly.
3. To use the for and do...while repetition statements to execute statements in a program
repeatedly.
4. To use the break and continue program control statements to alter the flow of control.

THEORY

Increment and Decrement Operators

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.

While Repetition Statement

A repetition statement allows you to specify that an action is to be repeated while some condition
remains true. The pseudocode statement:

While there are more item on my shopping list

Purchase next item and cross it off my list

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.

As an example of an actual while(), consider a program segment designed to print 1 2 3 in a single


line. Suppose the integer variable x has been initialized to 1.

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.

do… while Repetition 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.

The syntax of the do while loop is:

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.

As an example of an actual do..while, consider a program segment designed to print 1 2 3 in a


single line. Suppose the integer variable x has been initialized to 1.
int x = 1;
do{
printf(“%d “,x);
x = x + 1;
}
while(x <= 3);

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.

For Repetition Statement

The for loop provides a more concise loop control structure. The general form of the for loop is:

for (initialization; test condition; increment)


{
body of the loop
}
When the control enters for loop the variables used in for loop is initialized with the starting value such
as i=0,count=0. The value which was initialized is then checked with the given test condition. The test
condition is a relational expression, such as i < 5 that checks whether the given condition is satisfied
or not if the given condition is satisfied the control enters the body of the loop or else it will exit the
loop. The body of the loop is entered only if the test condition is satisfied and after the completion of
the execution of the loop the control is transferred back to the increment part of the loop. The control
variable is incremented using an assignment statement such as i=i+1 or simply i++ and the new value
of the control variable is again tested to check whether it satisfies the loop condition. If the value of the
control variable satisfies then the body of the loop is again executed. The process goes on till the
control variable fails to satisfy the condition.

Additional features of the for loop:


We can include multiple expressions in any of the fields of for loop provided that we separate such
expressions by commas. For example in the for statement that begins
for( i = 0; j = 0; i < 10, j=j-10)
Sets up two index variables i and j the former initialized to zero and the latter to 100 before the loop
begins. Each time after the body of the loop is executed, the value of I will be incremented by 1 while
the value of j is decremented by 10.

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)

Break and Continue Statement

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.

#include < stdio.h >


void main()
{
int i=1, num, sum=0;
for (i = 0; i < 5; i++)
{ printf(“Enter the integer”);
scanf(“%d”, &num);
if(num < 0)
{
printf(“You have entered a negative number”);
continue;
}
}
sum+=num;
}
printf(“The sum of positive numbers entered = %d”,sum);
} // end of the program.

PROCEDURE

PART A: INCREMENT AND DECREMENT OPERATORS

1. By considering the program in Listing 1-1:

i) Determine the output by line 8, 9, 12, 13, 15-17 and 19-21.


ii) Explain the results obtained from (i) above.

Line Code listing


1 #include <stdio.h>
2 #include <stdlib.h>
3 int main () {
int c;
4 int a =3;
5 int b = 3;
6 a= a+1;
7 b += 1;

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;

while (counter < 5) {


printf( “enter mark: ”);
scanf(“%d”, &mark);
total = total + mark;
counter +=1;
}

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.

PART C: FOR REPETITION STATEMENT

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

Repetition no of i sum squares


while statement

1 2

9
Repetition no of i sum squares
while statement

10

PART D: BREAK AND CONTINUE STATEMENT

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

Repetition no of User input for x sum num


while statement

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

1. Listing 3-6 is a C program that will produce the output as shown:

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.

Line Code listing


1 #include <stdio.h>
2 int main() {
3 int i;
4 for(i = 1; i < ____; i++) {
5 printf(“%d “, i);
6 if(( i % _____ ) == 0) {
7

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>

Enter a number: 3 <ENTER>

Enter a number: - 4 <ENTER>

The sum of the negative numbers entered is – 6.

Enter a number: 6 <ENTER>

Enter a number: 9 <ENTER>

Enter a number: 3 <ENTER>

Enter a number: 1 <ENTER>

The sum of the negative numbers entered is 0.

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

FACULTY OF ELECTRICAL ENGINEERING


UNIVERSITI TEKNOLOGI MARA

COMPUTER PROGRAMMING LABORATORY


(ECE128)

EXPERIMENT 4

FUNCTIONS

OBJECTIVES

1. To construct programs modularly from small pieces called functions.


2. To create new functions.
3. To used the mechanism to pass information between functions.
4. To understand recursive functions (functions that call themselves).

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).

Here is the general outfit of a C function:

return_type function_name(argument_1, argument_2, ..., argument_n){

function_body

A function may belong to any one of the following categories:

1. Functions with no arguments and no return values.


2. Functions with arguments and no return values.
3. Functions with arguments and return values.

Functions with no arguments (parameters) and no return values

Let us consider the following program

/* Program to illustrate a function with no argument and no return values*/

#include<stdio.h>

void statement1();
void statement2();
void starline();

main()
{ statement1();
statement2();
starline();
}

/*function to print a message*/


void statement1()
{ printf("Sample subprogram output\n");
}

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.

Functions with arguments (parameters) but no return values

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:

Consider the following:


Function calls containing appropriate arguments. For example the function call

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 :

/*Program to find the largest of two numbers using function*/


#include<stdio.h>

largest(int a, int b);

main()
{
int a,b;
printf("Enter the two numbers\n");
scanf("%d %d",&a,&b);
largest(a,b);
}

/*Function to find the largest of two numbers*/


largest(int a, int b)
{
if(a>b)
printf("Largest element = %d\n",a);
else
printf("Largest element = %d\n",b);
}
Functions with arguments and return values

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.

Return value data type of function:

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

Type_specifier function_name(argument list)


Argument declaration;
{
function statement;
}

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()

{ printf("This is an example of recursive function\n");

main();
}

when this program is executed. The line is printed reapeatedly and indefinitely. We might have to
abruptly terminate the execution.

PROCEDURE

PART A

1. Create a new project named 4-function.


2. Include the stdio.h header file.
3. Create a function prototype name square type int with one parameter y type int.
4. Define the main function.
5. Declare a variable named x type int.
6. Type the following statements in the main function.
for(x=1; x<=10; x++){
printf(“ %d\t “,square(x));
}
printf(“\n”);

7. Define the following function at the end of main function.


int square(int y)
{
return y*y;
}

8. Execute the program and observe the output.

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");

4. Execute the program and observe the output.

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

Total of odd integers: 2


Figure 4-3

EXERCISE

1. From procedures of Part A, answer these questions:


i. What is type of square function?
ii. Based on the function theory above, which category is square function belongs to?
iii. In your opinion, what is the advantage of function return value?
iv. Main function has called the square function in this program. Is it called by reference or
called by value? Explain your answer.

2. From procedures of Part B, answer these questions:


i. What void function means?
ii. Which category is loop function belongs to?
iii. In your opinion, why loop function did not has any parameter compared to square
function?

3. Observe the following partial program. Answer the questions below.

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.

FACULTY OF ELECTRICAL ENGINEERING


UNIVERSITI TEKNOLOGI MARA

COMPUTER PROGRAMMING LABORATORY


(ECE128)

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

Array Data Structure


For aggregated data with same type of element, an array can be used as data structure. An array is a
collection of related data elements of the same data type that are referenced by a common name.

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 mark1, mark2, mark3, ..., mark100;

By using an array, the declaration can be simplified like this:

int mark[100];

This will reserve 100 contiguous/sequential memory locations for storing the integer data type.

Graphically can be depicted as:

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:

type array_name[size] = {value_list};


For example:

int id[7] = {1, 2, 3, 4, 5, 6, 7};


float x[5] = {5.6, 5.7, 5.8, 5.9, 6.1};
char vowel[6] = {'a', 'e', 'i', 'o', 'u', '\0'};

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:

char array_name[size] = "string_lateral_constant";

For example, the array vowel in the above example could have been written more compactly as
follows:

char vowel[6] = "aeiou";

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.

Take this example:


int array2D[3][4];

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

PART A: ARRAY DECLARATION

1. Create a new project named DeclareArray.


2. Include the stdio.h header file and define the main() function.
3. Declare an integer variable named x and assign value of 3 to the variable.
4. Declare an integer variable named y and assign value of 1 to the variable.
5. Declare an integer array variable named arr_a with 5 number of element / array index.
6. Type the following statements.
arr_a[0]=5;
arr_a[1]=7;
arr_a[2]=9;
arr_a[3]=11;
arr_a[4]=13;

printf("%d %d %d %d", arr_a[y], arr_a[x], arr_a[x+y],arr_a[x-y]);

7. Execute the program and observe the output.


8. Using single printf statement, print output of array arr_a for the first and last elements.

PART B: ARRAY INITIALIZATION


1. Create a new project named InitializeArray.
2. Include the stdio.h header file and define the main() function.
3. Type the following statements.
int num[4]={1,2}; // Integer array initialization

char huruf[4]={'a','i'}; // Character array initialization

char nama[4]="tom"; // Character array initialization using string


//literals

int i;
for(i=0; i<4; i++)
printf("%c\t %c\t %d\n\n", huruf[i], nama[i], num[i]);

4. Execute the program and observe the output.


5. Modify the printf statement into the following statement.
printf("%c\t %s\t %d\n\n", huruf[i], nama, num[i]);
6. Execute the program and observe the output. Explain why the program can be executed correctly
after the printf statement modification.

PART C: INPUT - OUTPUT OF ARRAY

1. Create a new project named ioArray.


2. Include the stdio.h header file and define the main() function.
3. Declare an integer array variable named num with 4 number of element.
4. Declare an integer variable named i.
5. Type the following statements.
for(i=0; i<4; i++){
printf("\ninput num [%d]: ", i);
scanf("%d", &num[i]);
}

printf("\narray num[%d]: ", i);


for(i=0; i<4; i++)
printf("%d ", num[i]);

6. Execute the program and insert integer numbers for all num array elements. Observe the output.

PART D: CHARACTER ARRAY


1. Create a new project named CharArray.
2. Include the stdio.h header file and define the main function.
3. Declare an integer variable named i.
4. Declare a character array variable named string1 with 20 array index.
5. Type the following statements.
char string2[] = "string literal";

printf("Enter a string: ");


scanf("%s", string1);

printf("string1 is: %s\nstring2: is %s\n"


"string1 with spaces between characters is:\n",
string1, string2);

for(i=0; string1[i] != '\0'; i++)


printf("%c", string1[i]);

6. Execute the program.


7. Type input : Character Array. Observe the output.

PART E: BASIC OPERATION OF ARRAY

1. Create a new project named SumElementArray.


2. Include the stdio.h header file and define the main() function.
3. Declare an integer variable named i.
4. Declare an integer variable named sum and assign value of 10 to the variable.
5. Declare an integer array variable named x with 8 array index and initialize all the elements which
are 7, 5, 4, 2, 1, 8, 18 and 9.
6. Type the following statements.
printf("Before : \nsum = %d\narray x = ", sum);
for(i=0; i<8; i++)
printf("%d\t ", x[i]);
x[3]=22;
sum = x[5] + x[3];
sum += x[2];
x[6] += 1;
x[7] = x[0] + x[3];

printf("\n\nAfter : \nsum = %d\narray x = ", sum);


for(i=0; i<8; i++)
printf("%d\t ", x[i]);
printf("\n\n");
7. Execute the program and observe the output.

PART F: SORTING ARRAY

1. Create a new project named SortArray.


2. Include the stdio.h header file.
3. Define a constant named max with value of 8.
4. Define the main function.
5. Declare three integer variables named i, large and small.
6. Type the following statements.
int num[max]={4,8,13,0,-5,3,20,-1};

printf("Array: ");
for(i=0; i<max; i++)
printf("%d ", num[i]);

large = num[0];
small = num[0];

for(i=0; i<max; i++){


if(num[i]>large)
large = num[i];

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.

PART G: PASSING ARRAY TO FUNCTION

1. Create a new project named MultiArray.


2. Include the stdio.h header file.
3. Declare a prototype integer function called addNumbers with one parameter, an integer array.
4. Define the main function.
5. Inside the main function, declare an integer variable named i.
6. Then, declare an integer array variable named array with 5 number of element.
7. Type the following statements inside the main function.
printf("Enter 5 integers separated by spaces: ");

for(i=0 ; i<5 ; i++) {


scanf("%d", &array[i]);
}
printf("\nTheir sum is: %d\n", addNumbers(array));

return 0;

8. Define addNumbers function with an integer parameter named fiveNumbers.


9. Inside the addNumbers() function, declare an integer variable named i.
10. Then, declare an integer variable named sum and assign value of 0 to the variable.
11. Type the following statements inside the addNumbers function.
for(i=0 ; i<5 ; i++)
sum+=fiveNumbers[i];
return sum;

12. Execute the program and observe the output.

PART H: MULTI-DIMENSIONAL ARRAY

1. Create a new project named MultiArray.


2. Include the stdio.h header file and define the main function.
3. Declare two integer variables named i and j.
4. Declare an integer array variable named arr with 2-dimensional index, row of 2 and column of 6.
5. Type the following statements.
//Getting input from user
for(i=0 ; i<2 ; i++) {
printf("Enter 6 integers separated by spaces: ");
for(j=0 ; j<6 ; j++) {
scanf("%d" , &arr[i][j]);
}
printf("\n");
}
//Displaying output on the screen
printf("You entered:\n");
for(i=0 ; i<2 ; i++) {
for(j=0 ; j<6 ; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}

6. Execute the program and observe the output.

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].

memo[0] memo[1] memo[2] memo[3] memo[4] memo[5]

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].

code[0] code[1] code[2] code[3] code[4] code[5]

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.

4. In a program, declare and initialized an array number; int number[2][3] ={{1,2,3},


{4,5,6}};. Write a statement to swap the content in number[0][0] with the content in
number[1][2]. Using nested for loops and a printf statement, display the contents of
array number.
5. Refer to the flowchart in Figure 5-3. Write a program to declare and initialize float
array[4]={3.45, 2.72, 9.43, 5.98}. Using a for loop, pass each element of the
array to a function ganda(). Function ganda() multiplies the element with two and
displays the result from within the function itself.

Figure 5-3
FACULTY OF ELECTRICAL ENGINEERING
UNIVERSITI TEKNOLOGI MARA

COMPUTER PROGRAMMING LABORATORY


(ECE128)

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=&num;

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.

/* A program to illustrate pointer declaration*/

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.

Pointer expressions & pointer arithmetic

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.

Pointers and function

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

PART A: POINTERS DECLARATION AND ADDRESS OPERATOR

7. Create a new project named Decpointers.


8. Include the stdio.h header file and define the main() function.
9. Declare an integer variable named num and one pointers integer named intptr
10. Declare a float variable named x and a pointer variable named floptr.
11. Declare a char variable named ch and a pointer variable named cptr.
12. Type the following statements.
num=123;
x=12.34;
ch=’a’;
intptr=&num;
cptr=&ch;
floptr=&x;
printf(“Num %d stored at address %u\n”,*intptr,intptr);
printf(“x = %f stored at address %u\n”,*floptr,floptr);
printf(“ch = %c stored at address %u\n”,*cptr,cptr);

13. Execute the program and observe the output.

PART B: POINTERS EXPRESSION AND ARITHMETIC

14. Create a new project named Expointers.


15. Include the stdio.h header file and define the main() function.
16. Declare two integer pointers variable named ptr1 and ptr2.
17. Declare five integer variable named a, b, x, y and z.
18. Type a commands that ptr1 is pointing to variable a and ptr2 is pointing to variable b.
19. Type the following statements.
a=30; b=6;
ptr1 = &a;
ptr2 = &b;
x= *ptr1 + *ptr2 – 6;
y= (6* - *ptr1/ *ptr2) + 30;
printf(“\nAddress of a %u”,ptr1);
printf(“\nAddress of b %u”,ptr2);
printf(“\na=%d, b=%d”,a,b);
printf(“\nx=%d,y=%d”,x,y);
ptr1= ptr2;
printf(“\na=%d, b=%d”,*ptr1,*ptr2);

20. Execute the program and observe the output.

PART C: POINTERS AND FUNCTION (CALL BY VALUE)


21. Create a new project named funpointers1.
22. Include the stdio.h header file.
23. Write a function prototype of type void, function named fncn with two parameters, int p and
int q.
24. Define the main() function.
25. Declare two integer variable named x and y in the main function.
26. Type the following statements in the main function..
x=20;
y=30;
printf(“\n Value of a and b before function call =%d %d”, x, y);
fncn(x,y);
printf(“\n Value of a and b after function call =%d %d”, x, y);
27. Create new function below main function named fncn(int p, int q).
28. Type the following statements in fncn function.
p=p+p;
q=q+q;
29. Execute the program and observe the output.

PART D: POINTERS AND FUNCTION (CALL BY REFERENCE)

30. Create a new project named funpointers2.


31. Include the stdio.h header file and define the main() function.
32. Declare two integer variable named x and y.
33. Type the following statements.
x=20;
y=30;
printf(“\n Value of x and y before function call =%d %d”,x,y);
fncn(&x,&y);
printf(“\n Value of x and y after function call =%d %d”,x,y);
34. Create new function below main function named fncn(int *p, int *q).
35. Type the following statements in fncn function.
*p=*p+*p;
*q=*q+*q;
36. Execute the program and observe the output.

PART E: POINTERS TO ARRAY

37. Create a new project named pointstoArray.


38. Include the stdio.h header file and define the main() function.
39. Declare three integer variable named i, j and n.
40. Declare an integer array variable named a with 100 array index.
41. Declare an integer pointer named ptr.
42. Type the following statements.
printf("\nEnter the number of elements in the array\n");
scanf("%d",&n);
printf("Enter the array elements: ");
for(i=0;i< n;i++)
scanf("%d",&a[i]);
printf("Array element are: \n");
j=0;
for(ptr=a;ptr< (a+n);ptr++)
printf("Value of a[%d]=%d stored at address %u\n",j++,*ptr,ptr);
43. Execute the program and observe the output.

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:

a) the content of variable num


b) the content of variable the pointer is pointing to
c) the address of variable num
d) the address stored in the pointer variable
[Hint: *pointer = *pointer + 2;]

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

3. A character array named huruf is depicted as the following.

a b c t \0

Figure 6-3

Based on the array, write a program to include the following tasks:

a) Declare and initialize the character array huruf.

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;
}

Listing 6-1: Function (pass-by-reference)

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.

You might also like