Lab Manual Latest

83
FACULTY OF ELECTRICAL ENGINEERING UNIVERSITI TEKNOLOGI MARA LABORATORY MANUAL NAME: KP. UITM: GROUP:

Transcript of Lab Manual Latest

Page 1: Lab Manual Latest

FACULTY OF ELECTRICAL ENGINEERING UNIVERSITI TEKNOLOGI MARA

LABORATORY MANUAL

NAME:

KP. UITM:

GROUP:

Page 2: Lab Manual Latest

Table of Contents

EXPERIMENT 1..................................................................................................................................3

EXPERIMENT 2................................................................................................................................19

EXPERIMENT 3................................................................................................................................27

EXPERIMENT 4................................................................................................................................40

EXPERIMENT 5................................................................................................................................49

EXPERIMENT 6................................................................................................................................58

EXPERIMENT 7................................................................................................................................64

FACULTY OF ELECTRICAL ENGINEERINGUNIVERSITI TEKNOLOGI MARA

INTRODUCTION TO C PROGRAMMING LABORATORY (ECE126)

EXPERIMENT 1

INTRODUCTION TO C PROGRAMMING ANDFORMATTED I/O

OBJECTIVES

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

2. To learn how to 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

2

Page 3: Lab Manual Latest

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,

3

Page 4: Lab Manual Latest

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 text book for more escape sequences. Now let’s look at 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

4

Page 5: Lab Manual Latest

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

x or XUnsigned hexadecimal integer. x displays the letters a – f and X displays A - F

5

Page 6: Lab Manual Latest

Floating-point

Conversion Description

f Signed floating-point with fixed-point notation

e or E Signed floating-point with exponential notation

g or G Signed floating-point with either fixed-point or exponential notation 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);

6

Page 7: Lab Manual Latest

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

7

Page 8: Lab Manual Latest

PROCEDURE

PART A: WELCOME TO C

1. Create a folder in My Document folder. Name the folder with your student number and name.

Example: 200xxxxxxx Abu Bakar

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.

8

Page 9: Lab Manual Latest

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.

9

Page 10: Lab Manual Latest

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.

10

Page 11: Lab Manual Latest

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.

11

Page 12: Lab Manual Latest

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 <stdio.h>

#include <stdlib.h>

int main()

{

printf("Hello world!\n");

return 0;

}

12

Tell the compiler to include input/output library

Define a function called main

Main function call library output function to print the text enclose by double quote.

Implies normal termination of program

Open and close braces enclose the main function

Page 13: Lab Manual Latest

9. Now let’s execute (run) the source code (program) to see what’s the output of the program.

Before you can execute it, the code has to 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.

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 have to 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 ECE126 course”. Build and execute the program

and observe the output.

13

Build button

Page 14: Lab Manual Latest

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 intvar1 = 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 Data Type 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.

14

Page 15: Lab Manual Latest

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 all variables using printf statement and their %d conversion specifiers since var2, var3

and var4 are type int.

8. 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.15

Page 16: Lab Manual Latest

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., 150589): ");

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-05-89): ");

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/05/89): ");

scanf("%2d*%2d*%2d",&var1,&var2,&var3);

printf("Day %d, Month %d, Year %d\n", var1,var2,var3);

9. Execute the program. Observe the output.

16

Page 17: Lab Manual Latest

PART G: PRINTING WITH FIELD-WIDTH AND PRECISION1. 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 17

Page 18: Lab Manual Latest

2. Write a program to evaluate a quadratic or higher-order polynomial, such as

y=A x2+Bx+CThe program will have to ask the user for each of the coefficients (A,B and C), as well as the value of x at which to evaluate the function. Display the value of the coefficients, x and y.

REFERENCES

Horton I. (1997). Beginning C. Wrox.

Cheng H. H. (2010), C for Engineers and Scientists

Deitel P. J. & Deitel H. M. (2007). C How To Program. Pearson.

Hanly J. R. & Koffman E. B. (2007). Problem Solving and Program Design in C. Pearson.

18

Page 19: Lab Manual Latest

FACULTY OF ELECTRICAL ENGINEERINGUNIVERSITI TEKNOLOGI MARA

INTRODUCTION TO C PROGRAMMING LABORATORY (ECE126)

EXPERIMENT 2

SELECTION STATEMENT

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.

19

Page 20: Lab Manual Latest

C equality or relational

operator

Example of C condition Meaning of C condition

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

20

Page 21: Lab Manual Latest

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 90Print “A”

ElseIf student’s grade is greater than or equal to 80

Print “B”ElseIf student’s grade is greater than or equal to 70

Print “C”ElseIf 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)21

Page 22: Lab Manual Latest

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.

22

Page 23: Lab Manual Latest

PROCEDURE

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) 10b) 11

By using CodeBlocks, key-in, build and run the program to verify your answer.

#include <stdio.h>#include <stdlib.h>int main() { int pw;

printf(“enter your password: “);scanf(“%d”, &pw);if(pw == 11){

printf(“\n correct password \n”);}

printf(“Thank you \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 = 8c) 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;

printf(“enter first number: “);scanf(“%d”,&first);printf(“\n enter second number: “);scanf(“%d”,&second);

ans = first – second;

if(ans >= 0){printf(“\n Answer is a positive number \n”);

}else {

printf(“\n Answer is a negative number \n”);}

printf(“Thank you \n”); return 0;

}Listing 2-2

23

Page 24: Lab Manual Latest

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) first number = 13, second number = 8b) first number = 8 , second number = 13c) first number = 8, second number = 8

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;

printf(“enter first number: “);scanf(“%d”,&first);printf(“\n enter second number: “);scanf(“%d”,&second);

if(first > second){printf(“\n First number is greater.”);

}else if(first < second){

printf(“\n Second number is greater.”);}

else { printf(“\n Both numbers are equal. \n”);}

printf(“Thank you.\n”);

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) ab) bc) cd) de) 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’:

24

Page 25: Lab Manual Latest

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

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:

25

Page 26: Lab Manual Latest

Arithmetic operation(+,-,x,/) : + <ENTER>Insert first number: 9 <ENTER>Insert first number: 4 <ENTER>9 + 4 = 13

Arithmetic operation(+,-,x,/) : x <ENTER>Insert first number: 2 <ENTER>Insert first number: 8 <ENTER>2 x 8 = 16

Arithmetic operation(+,-,x,/) : & <ENTER>Insert first number: 2 <ENTER>Insert first number: 8 <ENTER>Error! Unknown arithmetic operation.

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

REFERENCES

Horton I. (1997). Beginning C. Wrox.

Deitel P. J. & Deitel H. M. (2007). C How To Program. Pearson.

Hanly J. R. & Koffman E. B. (2007). Problem Solving and Program Design in C. Pearson.

26

Page 27: Lab Manual Latest

FACULTY OF ELECTRICAL ENGINEERINGUNIVERSITI TEKNOLOGI MARA

INTRODUCTION TO C PROGRAMMING LABORATORY (ECE126)

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

27

Page 28: Lab Manual Latest

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

28

Page 29: Lab Manual Latest

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

Page 30: Lab Manual Latest

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

30

Page 31: Lab Manual Latest

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

31

Page 32: Lab Manual Latest

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

Line Code listing1 #include <stdio.h>2 #include <stdlib.h>3 int main () {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);

14 c=5;15 printf( “%d\n”,c);16 printf( “%d\n”,++c);

/*preincrement*/17 printf( “%d\n”, c);

18 c=5;19 printf( “%d\n”,c);20 printf( “%d\n”, c++);

/*preincrement*/21 printf( “%d\n”, c);

22 return 0;23 }

32

Page 33: Lab Manual Latest

Listing 3-1

1. By considering the program in Listing 3-1, determine what is printed on screen by line no 8, 9,

12, 13, 15-17 and 19-21.

2. Then, by using CodeBlocks, key-in, build and run the program to verify your answer in step 1.

PART B: WHILE AND DO… WHILE REPETITION STATEMENT

Listing 3-2 below 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.

#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

statementUser input for mark total counter

1 9

2 8

3 5

33

Page 34: Lab Manual Latest

4 6

5 2

Table 3-2

1. Fill in the Table 3-2 on the content of variables total and counter after each repetition of the

while statement.

2. What would be printed on screen by the last printf statement ?

3. Key-in, build and run the program using CodeBlocks to verify your answer.

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

Listing 3-3 below 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. 22 + 42 + 62 + … + 202).

#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

1. Fill in the Table 5 below on the content of variables i, sum and squares after each repetition of

the for statement.

Table 5

Repetition no of while statement

i sum squares

1 2

34

Page 35: Lab Manual Latest

Repetition no of while statement

i sum squares

2

3

4

5

6

7

8

9

10

2. What would be printed on screen by the two printf statements ?

3. Key-in, build and run the program using CodeBlocks to verify your answer.

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 6, determine the values of variables sum and num for each repetition of

the while() statement.

#include<stdio.h>int main() {int x;int num = 0;int sum = 0; while (true) { printf(“\n Input a mark: “); scanf(“%d”, &x); if( x == -1) { break; } sum += x; num++; }return 0;

35

Page 36: Lab Manual Latest

}

Listing 3-4

Table 6

Repetition no of while statement

User input for x sum num

1 30

2 20

3 0

4 23

5 -1

2. Explain what happen after a user had entered the mark as -1.

3. Key-in, build and run the program in Listing using CodeBlocks to verify your answer.

4. Listing 3-5 below shows a continue statement inside a for loop. Fill in the values of variables

x and y in Table 7 for each repetition of the for statement.

5. Key-in, build and run the program in Listing using CodeBlocks to verify your answer.

#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

36

Page 37: Lab Manual Latest

Table 7

Repetition no of for statement

x y

1

2

3

4

5

6

7

8

9

10

EXERCISE

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

Line Code listing1 #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 34 5 6

37

Page 38: Lab Manual Latest

7 8 9

Output for Listing 3-6

a) Lines 4, 6 and 7 are incomplete. Complete the code by filling in the blanks.

b) Key-in, build and run the complete code in CodeBlocks to verify your answer.

c) Rewrite the code in (1) using a do..while statement so that the same output is produced.

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 while

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

38

Page 39: Lab Manual Latest

scanf(“%d”, &start); printf(“\nEnd integer: “); scanf(“%d”, &end); while (true){

} printf(“The sum between %d and %d is %d\n”,start,end,sum);return 0;}

Listing 3-7

4. By using for and a continue statement, design a program that gives the following output:

9 8 6 5 4 3 1 0

Use CodeBlocks to test your program.

REFERENCES

Horton I. (1997). Beginning C. Wrox.

Deitel P. J. & Deitel H. M. (2007). C How To Program. Pearson.

Hanly J. R. & Koffman E. B. (2007). Problem Solving and Program Design in C. Pearson.

39

Page 40: Lab Manual Latest

FACULTY OF ELECTRICAL ENGINEERINGUNIVERSITI TEKNOLOGI MARA

INTRODUCTION TO C PROGRAMMING LABORATORY (ECE126)

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:

40

Page 41: Lab Manual Latest

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

41

Page 42: Lab Manual Latest

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.

42

Page 43: Lab Manual Latest

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.

43

Page 44: Lab Manual Latest

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

44

Page 45: Lab Manual Latest

}

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: USING FUNCTIONS

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.

45

Page 46: Lab Manual Latest

6. Type the following statements in the main function.

for(x=1; x<=10; x++){printf(“%d “,square(x));

}printf(“\n”);

7. Define below function out of main function.

int square(int y)

{return y*y;

}

8. Execute the program and observe the output.

PART B: USING FUNCTIONS

1. Modify the previous program in PART A by adding another function prototype name loop type

void after step 7.

2. Modify the main function 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 ",square(x));

}

printf("\n");

4. Execute the program and observe the output.

PART C: RECURSION

1. Create a new project named 4-recursion.

2. Include the stdio.h header file.

3. Create a function prototype name factorial type long with one parameter number type long.

4. Define the main function.

5. Declare a variable named i type int.

6. Type the following statements.46

Page 47: Lab Manual Latest

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

printf(“%2d! = %1d\n” , i, factorial(i));

}

7. Define below function out of main function.

long factorial (long number){

if(number<= 1){return 1;

}else{

return(number * factorial(number – 1));}

}

8. Execute the program and observe the output.

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.

47

long factorial(long n){ if (n == 0 || n == 1)

return 1;else

return n * factorial(n - 1);}

Page 48: Lab Manual Latest

i. Is this partial program is function declaration or function definition?

ii. State 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.

REFERENCES

Deitel P. J. & Deitel H. M. (2007). C How To Program. Pearson.

http://wiki.linuxquestions.org

http://www.exforsys.com

48

Page 49: Lab Manual Latest

FACULTY OF ELECTRICAL ENGINEERINGUNIVERSITI TEKNOLOGI MARA

INTRODUCTION TO C PROGRAMMING LABORATORY (ECE126)

EXPERIMENT 5

ARRAY

OBJECTIVES

1. To use the array data structure to represent lists and tables of values.

2. To define an array, initialize an array and refer to individual elements of an array.

3. To pass arrays to functions.

4. To use arrays to store, sort and search lists and tables of values.

5. 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;

49

Page 50: Lab Manual Latest

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.

50

Page 51: Lab Manual Latest

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:

51

Page 52: Lab Manual Latest

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

52

Page 53: Lab Manual Latest

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 %s\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 ARRAY1. 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";

53

Page 54: Lab Manual Latest

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 ", 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 ", x[i]);

printf("\n\n");

7. Execute the program and observe the output.

54

Page 55: Lab Manual Latest

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

Page 56: Lab Manual Latest

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.

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

}

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.

56

Page 57: Lab Manual Latest

EXERCISE

1. Write a full C Program that will add 2 matrices (3 x 3) and store the answers in another matrix.

Illustration of the matrices is shown below:

[ 1 2 3¿ ] [ 4 5 6 ¿ ]¿¿

¿¿ +

[ a b c ¿ ] [ d e f ¿ ]¿¿

¿¿ =

[(1+a) (2+b) (3+c ) ¿ ] [(4+d ) (5+e ) (6+ f )¿ ]¿¿

¿¿

All the values in the three matrices are stored in arrays (one matrix represents one array). Values

in the first matrix are given as shown above. For the second matrix, the values are entered by

users. For the output, display the answer in the form of matrix as shown below.

a nswer1 answer2 answer3 a nswer4 answer5 answer6a nswer7 answer8 answer9

2. Write a program that will calculate the sum of 10 array elements by using for loop.

REFERENCES

Horton I. (1997). Beginning C. Wrox.

Deitel P. J. & Deitel H. M. (2007). C How To Program. Pearson.

Hanly J. R. & Koffman E. B. (2007). Problem Solving and Program Design in C. Pearson.

57

Page 58: Lab Manual Latest

FACULTY OF ELECTRICAL ENGINEERINGUNIVERSITI TEKNOLOGI MARA

INTRODUCTION TO C PROGRAMMING LABORATORY (ECE126)

EXPERIMENT 6

POINTERS

OBJECTIVES1. To understand pointers and pointers operator.

2. To use pointers to pass arguments to functions by reference.

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

58

Page 59: Lab Manual Latest

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.

59

Page 60: Lab Manual Latest

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.

60

Page 61: Lab Manual Latest

PROCEDURE

PART A: POINTERS DECLARATION AND ADDRESS OPERATOR

1. Create a new project named Decpointers.

2. Include the stdio.h header file and define the main() function.

3. Declare an integer variable named num and one pointers integer named intptr

4. Declare a float variable named x and a pointer variable named floptr.

5. Declare a char variable named ch and a pointer variable named cptr.

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

7. Execute the program and observe the output.

PART B: POINTERS EXPRESSION AND ARITHMETIC

1. Create a new project named Expointers.

2. Include the stdio.h header file and define the main() function.

3. Declare two integer pointers variable named ptr1 and ptr2.

4. Declare five integer variable named a, b, x, y and z.

5. Type a commands that ptr1 is pointing to variable a and ptr2 is pointing to variable b.

6. 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); 61

Page 62: Lab Manual Latest

printf(“\nx=%d,y=%d”,x,y);

ptr1= ptr2;

printf(“\na=%d, b=%d”,*ptr1,*ptr2);

7. Execute the program and observe the output.

PART C: POINTERS AND FUNCTION (CALL BY VALUE)1. Create a new project named funpointers1.

2. Include the stdio.h header file.

3. Write a function prototype of type void, function named fncn with two parameters, int p and

int q.

4. Define the main() function.

5. Declare two integer variable named x and y in the main function.

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

7. Create new function below main function named fncn(int p, int q).

8. Type the following statements in fncn function.

p=p+p;

q=q+q;

9. Execute the program and observe the output.

PART D: POINTERS AND FUNCTION (CALL BY REFERENCE)

1. Create a new project named funpointers2.

2. Include the stdio.h header file and define the main() function.

3. Declare two integer variable named x and y.

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

5. Create new function below main function named fncn(int *p, int *q).

62

Page 63: Lab Manual Latest

6. Type the following statements in fncn function.

*p=*p+*p;

*q=*q+*q;

7. Execute the program and observe the output.

PART E: POINTERS TO ARRAY

1. Create a new project named pointstoArray.

2. Include the stdio.h header file and define the main() function.

3. Declare three integer variable named i, j and n.

4. Declare an integer array variable named a with 100 array index.

5. Declare an integer pointer named ptr.

6. Type the following statements.

printf(“\nEnter the elements of 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”);

j=0;

for(ptr=a;ptr< (a+n);ptr++)

printf(“Value of a[%d]=%d stored at address %u\n”,j++,*ptr,ptr);

7. Execute the program and observe the output.

EXERCISE

1. Write a program using pointers that counts the number of elements that are nonzero and stops when a zero is found from the given array. Display the result using fprintf statement.

array[] = {4, 5, 8, 9, 8, 1, 0, 1, 9, 3};

REFERENCES

Deitel P. J. & Deitel H. M. (2007). C How To Program. Pearson.

63

Page 64: Lab Manual Latest

http://www.exforsys.com

64

Page 65: Lab Manual Latest

FACULTY OF ELECTRICAL ENGINEERINGUNIVERSITI TEKNOLOGI MARA

INTRODUCTION TO C PROGRAMMING LABORATORY (ECE126)

EXPERIMENT 7

C STRUCTURE

OBJECTIVES

1. To understand C structure.

2. To use C structure.

THEORY

A structure or sometimes is also referred to as struct is a collection of variables under a single

name. These variables can be of different types, and each can be accessed by its name. Variables in

a struct are called members or fields. A structure may include arrays, pointers and another structure

as its member.

Declaring a structure

Normally a struct is defined before the main function. Declaring a struct requires the struct

keyword, followed by a name. Then the collection of variables is declared between a pair of curly

bracekets. The closing bracket must be followed by a semi colon.

65

Page 66: Lab Manual Latest

A typical structure definition is shown below.

General Examplestruct struct_tag_name {

type field_name1; 

type field_name2;

};

struct employee {

char name[20]; 

int salary;

};

struct introduces the structure definition. struct_tag_name is the structure name.

field_name1 and field_name2 are the struct members.

Declaring a structure variables

It is also possible to combine the declaration of the structure composition with the structure variables

as shown below. However, if struct_tag_name was declared outside main, the structure

variables struct_var1 and struct_var2 will be global variables.

General Examplestruct struct_tag_name {

type field_name1; 

type field_name2;

} struct_var1,struct_var2;

struct employee {

char *name; 

int salary;

} Employee1, Employee2;

The struct_tag_name is optional in the above condition and can be rewritten as:

General Examplestruct {

type field_name1; 

type field_name2;

} struct_var1,struct_var2;

struct {

char *name; 

int salary;

} Employee1, Employee2;

The structure variables can also be declared in the main function as follows.

struct struct_tag_name struct_var1,struct_var2;

struct struct_tag_name refers to the above declared structure. struct_var1 and

struct_var2 are variables of type structure struct_tag_name.

66

Page 67: Lab Manual Latest

Initializing structure variables

There are two ways to initialize variables.

i. All fields in one statement.

struct employee Employee1 = {“Maria”, 1200};

ii. One field at a time.

Use the Dot operator(.) to refer to an individual field.

struct employee Employee1; /*Declare Employee1 of type struct employee */

Employee1.name = “Maria”; /* Initialize name to Maria*/Employee1.salary = 1200; /* Initialize salary to 1200 */

Arrays of structure variables

A group of similar type variable can be stored in an array.struct dbase{ char *name; int salary;};

main(){

struct dbase employee[3];employee [0].name="Maria";employee [0].salary=1200;employee [1].name="Tony";employee [1].salary=2000;employee [2].name="Gunther";employee [2].salary=3500;

The initialization can also be rewritten as:

struct dbase employee[3]= {{“Maria”,1200},{“Tony”,2000},{“Gunther”,3500}};

To display, use printf statements as follows:

printf(" Name : %s \n", employee[0].name);printf(" Salary : %d \n", employee [0].salary);printf(" Name : %s \n", employee[1].name);printf(" Salary : %d \n", employee [1].salary);printf(" Name : %s \n", employee[2].name);printf(" Salary : %d \n", employee [2].salary);

or be simplified as follows:

for (i=0;i<3;i++)67

Page 68: Lab Manual Latest

{printf(" Name : %s \n", employee[i].name);printf(" Salary : %d \n", employee [i].salary);

}

Pointing to structures

A pointer can be a member of a structure. It is used to refer to a struct by its address. The pointer stores the memory address of a structure variable. Use arrow operator (->) to access the structure members/fields.

#include <stdio.h> struct data { int id; char *name; char *address; };int main() { struct data employee, *stPtr; stPtr = &employee; //Pointing to structure variable employee stPtr->id = 1; // Accessing the structure field stPtr->name = "Alina"; // (*strPtr).name = “Alina” can also be used stPtr->address ="Penang"; printf("Employee Information:\n"); printf("id=%d\n %s\n %s\n", stPtr->id, stPtr->name,stPtr->address); return 0; }

Passing Structures to Functions

Passing structures are similiar to passing arrays to functions. An example of passing structure to function is as follows.

#include <stdio.h>

struct robot { char *name; int energy; int IQ; };

void printInfo(struct robot r); /* function prototype*/

int main() {

struct robot ROBOT1 = {"Earthling Ed", 100, 231}; /* initialize 2 ROBOTs */ struct robot ROBOT2 = {"Toxic Tom", 150, 254}; /* robot names, energy and IQ */

printInfo(ROBOT1); printInfo(ROBOT2);

return 0;}

68

Page 69: Lab Manual Latest

/* Function PrintInfo */void printInfo(struct robot r) { printf("%s has %d units of energy, an IQ of %d...\n", r.name, r.energy, r.IQ);

}

PROCEDURE

PART A: STRUCTURE DECLARATION1. Create a new project named IntroStruct.

2. Include the stdio.h header file.

3. Declare a structure named database. The members of the structure are as follows:

int id_number;

float salary;

4. In main() function, create a variable employee to be of type struct database.

5. Initialize the id_number and salary of the employee by using:

employee.id_number = 1;

employee.salary = 2000.00;

6. Use printf statements to output the data for employee.

printf(" Id is: %d \n", employee.id_number);

printf(" Salary is: %d \n", employee.salary);

7. Execute the program and observe the output.

PART B: USE OF TYPE CHAR IN A STRUCTURE

1. Create a new project named DecStruct.

2. Include the stdio.h header file.

3. Declare a structure named student. The members of the structure are as follows:

int id;

char *name;

float percentage;

4. In the main() function, declare a structure-type variable named student1.

5. Type the following statements: 69

Page 70: Lab Manual Latest

student1.id=1;

student1.name = "Siti Aminah";

student1.percentage = 90.5;

6. Type the following printf statement to output the id for student1.

printf(" Id is: %d \n", student1.id);

7. Add printf statements to output the percentage and name of student1.

8. Execute the program and observe the output.

9. Change char *name in step 3 to char name[20];

10. Execute the program and observe the output.

11. Re-initialize the data in step 5 in a single statement as follows:

struct student student1= {1234,"Siti Aminah",90.5};

12. Execute the program and observe the output.

PART C: IMPLEMENT STRUCTURE WITH ARRAY VARIABLES

1. Create a new project named ArrayStruct.

2. Include the stdio.h header file.

3. Declare a structure named distanceAU before the main function.

4. The members of the structure are as follow:

name

distance

5. In the main function, declare a distanceAU structure-type variable named planet.

struct distanceAU planet[3];

6. Then, initialize all three variables according to Table 8 . Hint:

planet[0].name="Mercury";

planet[0].distance=0.39;

Table 8: Distance of planets from the sun in Astronomical unit (AU)Name Distance in Astronomical Unit (AU)

Mercury 0.39Venus 0.72Earth 39.5

7. Display the information about the planet name and its distance for all three planets. Hint:

printf(" Planet: %s \n", planet[0].name);printf(" Distance from the sun in AU is %f \n", planet[0].distance);

70

Page 71: Lab Manual Latest

PART D: IMPLEMENT STRUCTURE WITH ARRAY FIELD AND SCANF

1. Create a new project named arrayfield.

2. Type the following:

#include <stdio.h>

struct student

{

char name[20];

int id;

float marks;

};

3. In the main function, type:

main()

{

struct student s1[3];

int i;

printf("Enter Name, Id, Marks:\n");

for(i=0; i<=2; i++)

scanf("%s %d %f", &s1[i].name, &s1[i].id, &s1[i].marks);

}

4. Execute the program.

5. Use a for loop to display the student names, student ids and student marks.

PART E: PASSING STRUCTURE TO FUNCTION

1. Create a new project named StructFunc.

2. Include the stdio.h header file.

3. Declare a structure named tag before the main function.

4. The members of the structure are as follow:

int weight;

char name[20];

5. Write the function prototype

void largest( struct tag *animal);

6. In the main function, initialized struct tag animal[2] with these informations.

struct tag animal[2] = {{7000,"elephant"},{ 4,"cat"}};

7. Write a function call as follows

largest(animal);

71

Page 72: Lab Manual Latest

8. Declare the function largest. In function largest, compare the weight of the two animals using

if statement.

9. Display the weight and the name of the heaviest animal.

EXERCISE

1. The daily sales of Kedai OneMalaysia are recorded as follows.

Table 9Product name price per unit (RM) Unit sold

papaya 2.50 40coconut 1.00 30

rambutan 0.20 1000durian 15.00 60

Write a program using a structure to key in the data and then find the product with the largest sale in term of ringgit.

2. Explain the output of the program shown in Listing 7-1 below.

#include <stdio.h>#include <stdlib.h>struct tag { char *p; char name[32]; } s ={"abcd","ABCD"}; int main(){ printf("s.p = %s\n",s.p); printf("s.p[1] = %c\n",s.p[1]); printf("s.name = %s\n",s.name); printf("s.name[0] = %c\n",s.name[0]); printf("s.name = %c\n",*s.name); return 0;

}Listing 7-1

REFERENCES

Deitel P. J. & Deitel H. M. (2007). C How To Program. Pearson.

http://www.zentut.comhttp://www.programiz.com

72