ES03 Lab Manual

78
XAVIER UNIVERSITY Ateneo de Cagayan Cagayan de Oro City, Philippines ES 03 Computer Fundamentals and Programming LABORATORY MANUAL ELECTRONICS ENGINEERING DEPARTMENT COLLEGE OF ENGINEERING Compiled By: FRANKLIN REY PACQUIAO November 2009

Transcript of ES03 Lab Manual

Page 1: ES03 Lab Manual

XAVIER UNIVERSITY Ateneo de Cagayan

Cagayan de Oro City, Philippines

ES 03Computer Fundamentals and

Programming

LABORATORY MANUAL

ELECTRONICS ENGINEERING DEPARTMENT

COLLEGE OF ENGINEERING

Compiled By: FRANKLIN REY PACQUIAO

November 2009

Page 2: ES03 Lab Manual

ES 03 : Computer Fundamentals and ProgrammingDepartment of Electronics, College of EngineeringXavier University – Ateneo de Cagayan

DESCRIPTION: This course is an introduction of the computer as a tool for engineering students in analyzing and solving problems. Lecture discussion will include topics on logic formulation, algorithm, and flowcharting. Laboratory sessions will cover discussion of the fundamentals of the C programming language, and interpretation of the algorithm and flowchart by programming using C.

INSTRUCTOR: Engr. Meldy Grace M. Comandante

CREDIT UNITS: 2 Units (6 Hours per Week)CO-REQUISITE:OBJECTIVES: At the end of the semester, the students must be able to:

1. Understand basic information technology concepts;2. Use application software and the Internet properly;3. Acquire proficiency in algorithm development using a high-level programming language;4. Use the computer as a tool in engineering practice.

Lesson No. Title No. of Hours

Laboratory Rules and Equipment Orientation 31 Overview of the C Language 32 Input and Output Statements 63 Conditional Statements 34 Iterative Statements 35 Functions and Structured Programming 36 Recursion 67 Single – Dimensional Arrays 6

DESIGN PROJECT 6PROJECT DEFENSE 6

Page 3: ES03 Lab Manual

Grading System:

FG = 10% Attendance + 25% Lab. Exercises + 30% Class

Participation + 35% Project

Detailed Criteria:

Lab Exercises

Neatness, Completeness 20%Data/Results 30%Answer to Questions 20%Analysis and Conclusion 30%Total 100%

Project

Weekly Report 35%Final Paper 30%Final Defense 35%Total 100%

GRADING STANDARDS

Grading Standards:

92.00 100.00 A

84.00 91.00 A-

76.00 83.00 B

68.00 75.00 B-

60.00 67.00 C

59.99 And below F

Page 4: ES03 Lab Manual

LESSON 1: OVERVIEW OF THE C LANGUAGE

Objectives To determine the history of the C language To determine the different data types and keywords used in C language To determine the variables, constants, operators and expressions used in C To determine the structure of a simple C program

1.1 History of C Language

B was developed in the year 1970 by Ken Thompson. The said language is a successor of Basic Command Programming Language (BCPL), which was developed by Martin Richards. To augment B’s power, Dennis Ritchie invented and first implemented the C Programming Language in Bell Laboratory. C was originally developed under UNIX environment running in DEC PDP-11. It stands for Combined Programming Language and sometimes called System Programming Language (SPL). It did not become immediately popular after its creation. It took almost six years when many people read and learned the usefulness of the language after Brian Kernighan and Dennis Ritchie created a famous book called “The C Programming Language:.

X3J11 committee was created in the year 1983 under the American National Standard Institute (ANSI) to provide machine definition of the language and was then approved in 1989. ANSI cooperated with the International Standard Organization (ISO) to refer to as ANSI/ISO 9899:1990.

C is often called a middle-level language. C as a middle-level language means that it combines elements of high-level language with the functionalism of assembly language. It allows manipulation of bits, bytes, and addresses the basic elements with which the computer functions.

Input commands, output commands, and special words often referred to as reserved words allow the use of lower case only. They should be written in lower case since C is sensitive to those words. They have only 32 keywords (27 from Kernighan and Ritchie standard and 5 added by the ANSI Standardization Committee).

C was initially used for system development work, in particular the programs that make up the operating system. C is used mainly because it produces codes that run as fast as codes written in assembly language.

1.2 Some examples of the uses of C

Operating System Language Compilers Assemblers Text Editors

Page 5: ES03 Lab Manual

Print Spoolers Network Devices Modern Programs Databases Language Interpreters Utilities

1.3 Features of C Language

A simple core language, such as math functions or files handling provided by a standard set of library routines.

Focus on procedural programming language paradigm which facilitates for programming in a structured style.

Parameters are always passed by value, never by reference. C encourages the creation of libraries user-defined functions. C is flexible when it allows unrestricted conversion of data from one type to

another, such as conversion of a character to its numeric equivalent.

1.4 Data Types

There are five elementary data types in C: character (char), integer (int), floating point (float), double floating point (double) and void. Values of type char are used to hold ASCII characters or any 8-bit quantity. Variables of type int are use to hold integer quantities. Values of type float and double are used to hold real numbers. Real numbers have both an integer and fractional component. The type void has three uses: The first is to declare explicitly a function as returning no value. The second is to declare explicitly a function as having no parameters. The third is to create generic pointers.

Type Bidwidth Range char 8 0 to 255int 16 -32768 to 32767float 32 3.4E-38 to 3.4E+38double 64 1.7E-308 to 1.7E+308void 0 valueless

Type Modifiers

Except type void, the basic data types may have various modifiers preceding them. A modifier is used to alter the meaning of the base type to fit the needs of various situations more precisely. The list of modifiers includes the following:

signedunsignedlongshort

Page 6: ES03 Lab Manual

Type Bidwidth Range char 8 -128 to 127unsigned char 8 0 to 255signed char 8 -128 to 127int 16 -32768 to 32767unsigned int 16 0 to 65535signed int 16 -32768 to 32767short int 16 -32768 to 32767unsigned short int 16 0 to 65535signed short int 16 -32768 to 32767long int 32 -2147483648 to 2147483647unsigned long int 32 0 to 4294967295signed long int 32 -2147483648 to 2147483647float 32 3.4E-38 to 3.4E+38double 64 1.7E-308 to 1.7E+308long double 64 1.7E-308 to 1.7E+308

1.5 Keywords

Keywords in C are reserved words that have a special meaning. Reserved words are words are words “reserved” by the programming language for expressing various statements and constructs, thus, these may not be redefined by the programmer.

List of 32 Keywords/Reserved words as defined by the ANSI standard

auto double int structbreak else long switchcase enum register typedefchar extern return unionconst float short unsignedcontinue for signed voiddefault goto sizeof volatiledo if static while

1.6 Identifiers

Identifiers are composed of a sequence of letters, digits, and the special character underscore. Avoid using names that are too short or too long. Limit the identifiers from 8 to 15 characters only.

1.7 Variables

Variables are identifiers that can store a changeable value. These can be different data types.

Page 7: ES03 Lab Manual

Rules for defining or naming identifiers/variables:

1. It must consist only of letters, digits, and underscore.Example:_duh, num_1 (correct)

2. It should not begin with a digit.Example: 1name, 3to3 (incorrect)

3. An identifier defined in the C standard library should not be redefined.Example: printf, scanf (incorrect)

4. It is case sensitive; meaning uppercase is not equal to the lowercase.Example: ans ≠ Ans ≠ aNs ≠ anS ≠ ANs ≠ ANS

5. Do not include embedded blanks.Example: large num (incorrect)

6. Do not use any of the C language keywords as your variable/identifier.

7. Do not call your variable/identifier by the same name as other functions.

1.9.1 Variable Declaration

All variables must be declared before they may be used. The general form of declaration is shown here:

Type variable list;

Example: int i, j, k;short i, j, k;

1.9.2 Two kinds of variable

A. Local Variables

Variables that are declared inside a function are called local variables. It can only be referenced by statements that are inside the block in which the variables are declared.

Example:

#include<stdio.h>

main( ){

Page 8: ES03 Lab Manual

int a, b, c;________;________;________;

}

B. Global Variables

Global variables are known throughout the entire program and may be used by any piece of code. Global variables are created by declaring them outside of any function.

Example:

#include<stdio.h>int a, b, c;

main( ){

________;________;________;

}

1.10 Constants

Constants are identifiers/variables that can store a value that cannot be changed during program execution.

Example: const int count = 100;

Where integer count has a fixed value of 100

1.11 Arithmetic, Logical, Relational, and Bitwise Operators

Operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. There are three classes of operators in C: arithmetic, logical and relational and bitwise.

1.11.1 Arithmetic Operators

Operator Action + Addition - Subtraction * Multiplication / Division

Page 9: ES03 Lab Manual

% Modulus Divisor - - Decrement a value + + Increment a value

1.11.2 Relational and Logical Operators

In the term relation operator, the word relational refers to the relationship values can have with one another. In the term logical operator, the word logical refers to the ways these relationships can be connected together using the rules of formal logic. The key to the concept of relational and logical operators is the idea of true or false.

1.11.2.1 Relational Operators

Operator Action > Greater than >= Greater than or equal to < Less than <= Less than or equal to = = Equal != Not equal

1.11.2.2 Logical Operators

Operator Action Truth Table && AND true && true = true

true && false = falsefalse && true = falsefalse && false = false

|| OR true && true = truetrue && false = truefalse && true = truefalse && false = false

! NOT ! true = false! false = true

1.11.3 Bitwise Operator

Bitwise operations are the testing, setting or shifting of the actual bits in a byte or a word, which corresponds to C’s standard char and int data types and variants. Bitwise operators cannot be used on type float, double, long double, void or other more complex types.

Page 10: ES03 Lab Manual

Operator Action & AND| OR^ Exclusive OR (XOR)~ One’s complement>> Shift right<< Shift left

1.11.4 The ? Operator

? Operator is a very powerful and convenient operator that can be used to replace certain statements of the if-then-else form.

Example: y = x > 9 ? 100:200

is equivalent to

if (x > 9)y = 100;

elsey = 200;

1.12 Evaluation of Expression

Expression refers to anything that evaluates to a numeric value.

Operator precedence and associativityOperators Associativity

( ) ++ (postfix) -- (postfix) Left to right+ (unary) - (unary) ++ (prefix) -- (prefix) Right to left

* / % Left to right+ - Left to right

< <= > >= Left to right= = != Left to right

&& Left to right|| Left to right?: Right to left

= += -= *= /= etc Right to left, (comma operator) Left to right

Page 11: ES03 Lab Manual

Examples:

A. Evaluate the following:

1. Given: z = 5, a = 3, b = 9, w = 2, y = -5;

Expression: z – (a * b / 2) + w * y5 – (3 * 9 / 2) + 2 * -55 – (27 / 2) + -105 – 13 – 10-8 – 10-18

2. Given : a = 5, b = 2, y = 3, c = 4, x = 1 ;

Expression: (a * b + 2) * -y / (c + x)(5 * 2 + 2) * -3 / (4 + 1)(10 + 2) * -3 / 512 * -3 / 5-36 / 5-7

B. Evaluate the following expressions and determine whether they yield a value of TRUE or FALSE

1. Given: dei = 0, y = 4.0, z = 2.0, x = 3.0;

Expression : ! dei || (y + z >= x – z)! 0 || (4.0 + 2.0 >= 3.0 – 2.0)1 || (6.0 >= 1.0)1 || 11 TRUE

2. Given : x = 3, y = 2, j = 5, k = 3 ;

Expression : (x – y) <= (j – k = = 3)(3 – 2) <= (5 – 3 = = 3)1 <= (2 = = 3)1 <= 00FALSE

Page 12: ES03 Lab Manual

1.13 Converting Mathematical Formula to C Expression

To solve mathematical problems using the computer, the formula should be translated to the programming language to be used. Arithmetic computation should be written as C expressions.

Example:

b2 – 4ac = b * b – 4 * a * ca + b = (a + b) / (c + d)c + d

1.14 Converting English Conditions to C Expressions

Solutions to problems may sometimes depend on a set of conditions. To use the computer to solve such problems, these conditions should be converted to the C.

Example:

x and y are greater than z can be converted to x > z && y > z

x is equal to 1.0 or 3.0 can be converted to x = = 1.0 || x = = 3.0

1.15 Structure of a simple C program

<#include directive><#define directive>

main( ){

<variable declaration section>statements. . .

}

A. #include directive – contains information needed by the program to ensure the correct operation of C’s standard library functions.

Example: #include<stdio.h>

B. #define directive – used to shorten the keywords in the program. – also used to define constants and aliases.

Example: #define g gotoxy

C. Variable declaration section – it is the place where you declare your variables.

Page 13: ES03 Lab Manual

D. Body of the program – start by typing main( ) and the { and } (open and close braces). All statements should be written inside the { and } braces.

1.16 Commonly used include files in C language

1. alloc.h – declares memory management functions2. conio.h – declares various functions used in calling IBM-PC ROM BIOS3. ctype.h – contains information used by the classification and character conversion

macros.4. math.h – declares prototype for the math functions.5. stdio.h – defines types and macros needed for standard I/O.6. string.h – declares several string manipulation and memory manipulation routines.

1.17 Important Symbols

\n - is a line char used to move the cursor to the next line‘ ‘ - single quote is used for single character/letter“ “ - double quote is used for two or more character{ - open curly brace signifies begin} - close curly brace signifies end& - address of operator* - indirection operator/pointer

Page 14: ES03 Lab Manual

LESSON 2: INPUT AND OUTPUT STATEMENTS

Objectives To be able to create, execute, and save a C program To interactively design a simple input/output program using C programming

language To explain the major elements of the program by the method of dissection

2.1 Input Statement

A statement used to input a single character or a sequence of characters from the keyboard.

1. getch – a function used to input a single character from the keyboard without echoing the character on the monitor.

Syntax: getch( );Example: ch = getch( );

2. getche – a function used to input a single character from the keyboard, the character pressed echoed on the monitor, like the READLN in PASCAL.

Syntax: getche( );Example: ch = getche( );

3. getchar – a function used to input a single character from the keyboard, the character pressed echoed on the monitor, terminated by pressing ENTER key.

Syntax: getchar( );Example: ch = getchar( );

4. gets – a function used to input sequence of character from the keyboard, spaces are accepted, terminated by pressing enter key.

Syntax: gets( );Example: gets(ch);

5. scanf – a function used to input single character or sequence of characters from the keyboard, it needs the control string codes in able to recognized. Spaces are not accepted upon inputting. Terminated by pressing spacebar.

Syntax: scanf(“control string codes”, identifier);Example: scanf(“%d”, &num);

2.2 Output Statement

Page 15: ES03 Lab Manual

A statement used to display the argument list or string on the monitor.

1. printf – a function used to display the argument list on the monitor. It sometimes needs the control string codes to help display the remaining argument on the screen.

Syntax: printf(“control string codes”, argument list);Example: printf(“Hello, %s, you are %d years old”, name, age);

2. putchar – a function used to display the argument list or string on the monitor. It is like overwriting a character.

Syntax: putchar( );Example: putchar(tolower (ch));

3. puts – a function used to display the argument list or string on the monitor. It does not need the help of the control string codes.

Syntax: puts( );Example: puts(“hello”);

2.3 Format Strings and Escape Sequences

All format specifiers start with a percent sign (%) and are followed by a single letter indicating the type of data and how data are to be formatted.

List of commonly used format specifiers:

%c – used for single char in Cscanf(“%c”, &ch);printf(“%c”, ch);

%d – decimal number (whole number)scanf(“%d”, &num);printf(“%d”, num);

%e – scientific notation/exponential formscanf(“%e”, &result);printf(“%e”, result);

%f – number with floating or decimal pointscanf(“%f”, &pesos);printf(“%f”, pesos);

%o – octal number

Page 16: ES03 Lab Manual

scanf(“%o”, &value);printf(“%o”, value);

%s – string of charactersscanf(“%s”, str);printf(“%s”, str);

%u – unsigned numberscanf(“%u”, &nos);printf(“%u”, nos);

%x – hexadecimal numberscanf(“%x”, &value);printf(“%x”, value);

%X – capital number for hexadecimal numberscanf(“%X”, &nos);printf(“%X”, nos);

%% - print a percent signscanf(“%%”, &value);printf(“%%”, value);

List of commonly used escape sequences:

\\ - prints backslash\’ - prints single quotes\” - prints double quotes\? - prints question mark\n - newline

Examples:

1. Create the traditional first program in honor of Dennis Ritchie.

/* The traditional first program in honor of Dennis Ritchie who invented C at Bell Labs in 1972 */

#include <stdio.h> main() { printf("Hello World!\n"); system("pause"); //this line is only needed under windows }

Output

Page 17: ES03 Lab Manual

Enter Name: Paul Enter Age: 3Hello Paul, you are 3 years old

First number: 5Second number: 6Sum of two numbers: 11Product of two numbers: 30

Hello World!

Wreck of the Hesperus:Its depth at sea in different units:7 fathoms42 feet504 inches

2. Write a program based on the wreck of the ship Hesperus. This calamity at sea, which was made famous in a poem by Henry Wadsworth Longfellow, occurred off the reef of Norman’s Woe near Gloucester, Massachusetts, in 1839. The waters off the reef are about 7 fathoms deep. In the program we convert this depth to other units of measure.

#include <stdio.h> Outputmain( ){int inches, feet, fathoms;fathoms = 7;feet = 6 * fathoms;inches = 12 * feet;printf(“Wreck of the Hesperus:\n”);printf(“Its depth at sea in different units:\n”);printf(“ %d fathoms\n”, fathoms);printf(“ %d feet\n”, feet);printf(“ %d inches\n”, inches);system("pause");}

3. Create a program that accepts and displays a person’s name and age.

#include<stdio.h> Outputmain( ){int age;char name[10];printf(“\n Enter Name:”);scanf(“%s”, name);printf(“\n Enter Age:”);scanf(“%d”, &age);printf(“\n Hello %s, you are %d years old”, name, age);getch( );}

4. Make a program that will compute and display the sum and product of two numbers.

#include<stdio.h> Outputmain( ){int A, B, Sum, Prod;printf(“\nFirst number:”);scanf(“%d”, &A);

Page 18: ES03 Lab Manual

Input your three initials and your age:Greetings f.a.p. Next year your age will be 26

printf(“Second number:”);scanf(“%d”, &B);Sum = A + B;Prod = A * B;printf(“\nSum of two numbers: %d”, Sum);printf(“\nProduct of two numbers: %d”, Prod);getch( );}

5. Write a program in which the user is prompted to input his/her initials followed by the age.

#include <stdio.h> Outputmain( ){char first, middle, last;int age;

printf(“Input your three initials and your age: ”);scanf(“%c%c%c%d”, &first, &middle, &last, &age);printf(“\nGreetings %c.%c.%c. %s %d.\n”, first, middle, last,

“Next year your age will be”, age + 1);system(“pause”);}

Page 19: ES03 Lab Manual

PROGRAMMING EXERCISES

1. Create a program that asks for a distance in kilometers and converts it into its metric equivalent.

2. Write a program that asks the user to enter the radius of a circle and then computes for its area. Recall that the formula to compute for the area is AREA = Pi x R2, where R is the radius. The output must be similar to the one below.The area of the circle with radius 2 cm is 12.56 cm2.

3. Create a program that converts a Fahrenheit measure to a Celsius measure (C = 5/9 x (F–32)).

4. Write a program that will compute and display the midterm grade of a student. The midterm grade is equal to one-third of the minor exam and two-thirds of the midterm exam.

5. Create a program that will input a number in kilowatt and display its equivalent measure in watts.

6. Create a program that will compute and display the area of a square. Recall that the formula to compute the AREA = S2 where S is the side of the square.

7. Make a program that will convert an inputted number in inches (in.) and display its equivalent measure in feet (ft).

8. Create a program that will get as input from the user the base and height of a triangle. Compute and display the area of the rectangle.

9. Write a program that inputs two real numbers then exchanges their values.10. Make a program the will accept a number in square meters (m2) and display its

equivalent measure in hectares (has).Hint: 1000 m2 = 1 ha

Page 20: ES03 Lab Manual

LESSON 3: CONDITIONAL STATEMENTS

Objectives To learn how to run a command conditionally To learn the different types of conditional statements used in C

Conditional Statements are statements that check an expression then may or may not execute a statement or group of statements depending on the result of the condition.

In C the following are the types of conditional statements:

3.1 The IF statement

The general form of the if statement is:

Where:if is a reserve word in C

expression is relational or Boolean expression that evaluates to a TRUE (1) or FALSE (0) value

statement may either be a single C statement or a block of C statements.

The general form of the if statement with block of statements is:

In an if statement, if the expression evaluates to TRUE (1), the statement or the block of statements that forms the target of the if statement will be executed. Otherwise, the program will ignore the statement or the block of statements.

Note: Never place a semicolon after the expression in an If statement.

if (expression) statement;

if (expression){

statement_sequence;}

Page 21: ES03 Lab Manual

Enter student grade: 95Congratulations you PASSED!

Enter value for price: 2000Discount is 200.00

Example 1. Write a program that will output “Congratulations you PASSED!” if the student’s grade is greater than or equal to 60.

#include<stdio.h> Outputint grade;main( ){

printf(“Enter student grade:”);scanf(“%d”, &grade);if (grade >= 60)

printf(“Congratulations you PASSED!”);getch( );

}

Example 2. Write a program that will ask for a price. If the price is greater than 1000, compute a 10% discount from the original price. Display the computed discount.

#include<stdio.h> Outputfloat price, discount;main( ){

printf(“Enter value for price:”);scanf(“%f”, &price);if(price > 1000){

discount = price * 0.10;printf(“Discount is %.2f”, discount);

}getch( );

}

3.2 The IF-ELSE statement

The general form of the if-else statement is:

where:

if (expression) statement_1;

elsestatement_2;

Page 22: ES03 Lab Manual

Enter student grade: 50Sorry you FAILED!

if and else are reserve words in C

expression is relational or boolean expression that evaluates to a TRUE (1) or FALSE (0) value

statement_1 and statement_2 may either be a single C statement or a block of C statements.

The general form of the if-else statement with block of statements is:

In an if-else statement, if the expression is TRUE (1), the statement or block of statements after the if statement will be executed; otherwise, the statement or block of statements in the else statement will be executed.

NOTE: Only the code associated with the if or the code that is associated with the else executes, never both.

Example 3. Write a program that will output “Congratulations you PASSED!” if the student’s grade is greater than or equal to 60. Otherwise output, “Sorry you FAILED!”

#include<stdio.h> Outputint grade;main( ){

printf(“Enter student grade:”);scanf(“%d”, &grade);if (grade >= 60)

printf(“Congratulations you PASSED!”);else

printf(“Sorry you FAILED!”);getch( );

}

if (expression){

statement_sequence;}else{

statement_sequence;}

Page 23: ES03 Lab Manual

3.3 The NESTED-IF statement

One of the most confusing aspects of the if statement in any programming language is nested ifs. A nested if is an if statement that is the object of either an if or else. This is sometimes referred to as “an if within an if”.

The reason that nested ifs are so confusing is that it can be difficult to know what else associates with what if.

Fortunately, C provides a very simple rule for resolving this type of situation. In C, the else is linked to the closest preceding if that does not already have an else statement associated with it.

Consider the following situations:

Situation 1 The else at number 3 is paired with the if in number 2 since it is the nearest if statement with the else statement.

1. if ……

2. if ………

3. else

Situation 2 The else in number 5 is paired with the if in number 1.

1. if …2. {3. if …

…4. }5. else

Notice that there is a pair of braces found in number 2 and number 4. The pair of braces defines the scope of the if statement in number 1 starting from the { in number 2 and ends with } in number 4. Therefore, the else statement in number 5 cannot be paired with the if statement in number 3 because the else statement is outside the scope of the first if statement. This makes the if statement in number 1 the nearest if statement to the else statement in number 5.

Example 4. Write a program that reads in three numbers A, B and C and determine which is the largest.

Page 24: ES03 Lab Manual

Enter three numbers: 7 11 5B is the largest.

#include<stdio.h> Outputint A, B, C;main( ){printf(“Enter three numbers:”);scanf(“%d%d%d”, &A, &B, &C);

if (A > B)if (A > C)

printf(“A is the largest.\n”);else

printf(“C is the largest.\n”);else

if (B > C)printf(“B is the largest.\n”);

elseprintf(“C is the largest.\n”);

getch( );}

3.4 The IF-ELSE-IF Ladder

A common programming construct in C is the if-else-if ladder.

The general form of the if-else-if ladder statement is:

where:

if and else are reserve words in C

expression_1, expression_2 up to expression_n is relational or boolean expression that evaluates to a TRUE (1) or FALSE (0) value

if (expression_1) statement_1;

else if (expression_2)statement_2;

else if (expression_3)statement_3;

::

elsestatement_else;

Page 25: ES03 Lab Manual

Enter an integer: 4Wednesday

Enter an integer: 4Wednesday

statement_1, statement_2 up to statement_else may either be a single C statement or a block of C statements.

In an if-else-if ladder statement, the expressions are evaluated from the top downward. As soon as a true condition is found, the statement associated with it is executed, and the rest of the ladder will not be executed. If none of the condition is true, the final else is executed.

The final else acts as a default condition. If all other conditions are false, the last else statement is performed. If the final else is not present, then no action takes place.

Note: The final else is optional, you may include this part if needed in the program or you may not include if not needed.

Example 5. Write a program that will ask the user to input an integer then output the equivalent day of the week. 1 is Sunday, 2 is Monday and so on. If the inputted number is not within 1-7, output “Day is not available!”

#include<stdio.h> Outputmain( ){

int day;printf(“Enter an integer:”);scanf(“%d”, &day);if (day = = 1)

printf(“Sunday”);else if (day = = 2)

printf(“Monday”);else if (day = = 3)

printf(“Tuesday”);else if (day = = 4)

printf(“Wednesday”);else if (day = = 5)

printf(“Thursday”);else if (day = = 6)

printf(“Friday”);else if (day = = 7)

printf(“Saturday”);else

printf(“Day is not available!”);getch( );

}

3.5 The SWITCH Statement

The switch statement is a multiple-branch decision statement.

Page 26: ES03 Lab Manual

The general form of the switch statement is:

In a switch statement, a variable is successively tested against a list of integer or character constants. If a match is found, a statement or block of statements is executed. The default part of the switch is executed if no matches are found.

There are three important things to know about switch statements:

1. The switch differs from if statements in such a way that switch can only test for equality whereas if can evaluate a relational or logical expression.

2. No two case constants in the same switch can have identical values. Of course, a switch statement enclosed by an outer switch may have case constants that are the same.

3. If character constants are used in the switch, they are automatically converted to their integer values.

NOTE: The break statement is used to terminate the statement sequence associated with each case constant. It is a C keyword which means that at that point of execution, you should jump to the end of the switch statement terminated by the symbol }.

switch (variable){

case constant1:statement sequence_1;break;

case constant2:statement sequence_2;break;

::

default:statement_sequence_default;

}

Page 27: ES03 Lab Manual

Enter an integer: 11Day is not available!

3.5.1 Nested Switch Statement

The general form of the nested switch statement is:

Example 6. Rewrite the program in Example 5 using a switch statement.

#include<stdio.h> Outputmain( ){

int day;printf(“Enter an integer:”);scanf(“%d”, &day);switch (day){

case 1:printf(“Sunday”);break;

case 2:

switch (variable){

case constant1:{switch (variable){

case constant1:statement sequence;break;

case constant2:statement sequence;break;

}break;}

case constant2:statement sequence;break;

::

default:statement sequence;

}

Page 28: ES03 Lab Manual

Enter number 1: 10Enter number 2: 25A – AdditionS – SubtractionM – MultiplicationD – DivisionEnter a character for the operation: AThe answer is: 35

printf(“Monday”);break;

case 3:printf(“Tuesday”);break;

case 4:printf(“Wednesday”);break;

case 5:printf(“Thursday”);break;

case 6:printf(“Friday”);break;

case 7:printf(“Saturday”);break;

default:printf(“Day is not available!”);

}getch( );

}

Example 7. Write a program that will ask the user to input 2 integers and a character (A, S, M or D). If the user inputs ‘A’ for the character, add the 2 numbers, if ‘S’ subtract the 2 numbers, if ‘M’ multiply, and if ‘D’ divide the numbers. Output the computed value.

#include<stdio.h> Outputmain( ){

int num1, num2, ans;char operation;printf(“Enter number 1:”);scanf(“%d”, &num1);printf(“Enter number 2:”);scanf(“%d”, &num2);printf(“A – Addition \n”);printf(“S – Subtraction \n”);printf(“M – Multiplication \n”);printf(“D – Division \n”);printf(“Enter a character for the operation:”);scanf(“%c”, &operation);switch (operation){

case ‘A’:

Page 29: ES03 Lab Manual

ans = num1 + num2;break;

case ‘S’ :ans = num1 - num2;break;

case ‘M’:ans = num1 * num2;break;

case ‘D’:ans = num1 / num2;break;

}printf(“The answer is: %d”, ans);

getch( );}

Page 30: ES03 Lab Manual

PROGRAMMING EXERCISES

1. Write a program that finds the smallest among the five integers inputted by the user.

2. Write a program that computes the grade of a student using the formula:Grade = 40% major exam + 30% ave of 2 long exams + 30% ave of 3 short quizzes

Display the average of two long exams, average of 3 short quizzes and the grade of the student. Display also a message whether the student passed or failed. Passing is 75%.

3. Write a program that asks the user for the hours worked for the week and the hourly rate. The basic salary is computed as:

Salary = hours worked * hourly rateBonuses are given:No. of hours > 45 Bonus of 500 pesosNo. of hours > 40 and <=45 Bonus of 250 pesosNo. of hours > 35 and <=40 Bonus of 150 pesosDisplay the basic salary, bonus and the total salary (basic salary + bonus) for the week.

4. XYZ Company gives year-end bonus to its employees based on their number of years of service and their salary, using the following:

Years of Service Bonus1 10% of salary2 to 5 20% of salary5 to 10 50% of salary11 and above 75% of salary

5. Write a program that accepts five numbers from the user and displays the highest and the lowest number. Assume that there are no duplicate values.

6. Write a program that accepts three numbers from the user and displays the highest and the lowest number. Assume that there are no duplicate values.

7. Write a program that accepts three numbers from the user and displays the values from highest to lowest. Assume that there are no duplicate values.

8. Write a program segment that will ask the user if he wants to compute the perimeter of the area of a triangle. If the perimeter is wanted, ask the measure of the three sides and compute for the perimeter. If the area is wanted, ask for the measures of the base and height and compute for the area. Display the computed value.

9. Write a program that will display “I’TS COLD!” if the temperature is less than 20, “I’TS HOT!” if the temperature is greater than 30, “COOL CLIMATE!” otherwise.

10. Write a program that gives a discount of 100 pesos to a customer if the shirt bought is XL and the price is greater than 500 pesos; a discount of 50 pesos if the shirt bought is L and the price is greater than 400.

11. Write a program to determine the equivalent grade of each student in a class as follows:a. Read in the student’s name, midterm grade, minor exam, and final exam

ratings.

Page 31: ES03 Lab Manual

b. Determine the final grade of the student by the formula:Final grade = 0.30 midterm grade + 0.10 minor exam + 0.60 of final exam

c. Determine the equivalent grade for the numerical value obtained by the following grade marks:

98 – 100 = 4.0095 – 97 = 3.7592 – 94 = 3.5089 – 91 = 3.2586 – 88 = 3.0083 – 85 = 2.7580 – 82 = 2.5077 – 79 = 2.2574 – 76 = 2.0071 – 73 = 1.7568 – 70 = 1.5064 – 67 = 1.2560 – 63 = 1.00below 60= 0.00

12. Write a program that will read a date (month, day and year) in integer form and display the date in standard format.Sample Run:

Enter month: 10Enter day: 23Enter year: 2000

October 23, 2000

Page 32: ES03 Lab Manual

LESSON 4: ITERATIVE STATEMENTS

Objectives To learn about using loops in programming To learn the different types of iterative statements used in C

Iterative statements (loops) allow a set of instructions to be executed or performed several times until certain conditions are met. It can be predefined as in the for loop, or open-ended as in while and do-while.

4.1 The FOR statement

The for statement or for loop is considered as a predefined loop because the number of times it iterates to perform its body is predetermined in the loop’s definition.

The for loop contains a counter whose values determine the number of times the loop iterates. The iteration stops upon reaching the number of times specified in the loop.

The general form of the for statement is:

where:

for is a reserve word in C

initialization is an assignment statement that is used to set the loop’s counter

condition is a relational Boolean expression that determines when the loop will exit

increment defines how the loop’s counter will change each time the loop is repeated

statement_sequence may either be a single C statement or a single block of C statements that make up the loop body

The for loop continues to execute until the condition is TRUE (1). Once FALSE (0), program execution resumes on the statement following the for loop.

for (initialization; condition; increment){

statement_sequence;}

Page 33: ES03 Lab Manual

12345678910

The sum of 1 to 10 is 55

NOTE: a) Never place a semi-colon right after the for header. This is a logical error.b) Never change the value of the for loop’s counter inside the body of the loop.

This will affect the result of the program.c) The increment part of the for loop is execute after the first iteration of the

loop.

Example 1. Write a program that will print the numbers 1 to 10 using a for statement.

#include<stdio.h> Outputint x;main( ){

for(x = 1; x <= 10; x + +)printf(“%d\n”, x);

getch( );}

In example 1, the counter of the for loop is x with the initial value of 1. After the initialization part, the control of the program transfer to the condition to check whether the value of x is less than or equal to 10. Since the result of the condition is TRUE (1), the value of x will be printed.

After the first iteration of the loop, the increment part will be performed making the value of x equal to 2. The control of the program transfers again to the condition part to determine if the result is TRUE (1) or FALSE (0). Since condition is TRUE (1) the value of x will again be printed then the increment part will perform again. The process continues until the condition part evaluates to FALSE (0).

Example 2. Write a program that will get the sum of all integers from 1 to 10.

#include<stdio.h> Outputint x, sum;main( ){

sum = 0;for(x = 1; x <= 10; x + +)

sum = sum + x;printf(“The sum of 1 to 10 is %d\n”, sum);getch( );

}

Page 34: ES03 Lab Manual

12345678910

4.2 The WHILE statement

The while statement or while loop is an open-ended or event-controlled loop. The while loop iterates while the condition is TRUE (1). When it becomes FALSE (0), the program control passes to the line after the loop code.

The general form of the while statement is:

where:

while is a reserve word in C

condition is a relational expression that determines when the loop will exit

statement_sequence may either be a single C statement or a single block of C statements that make up the loop body

Example 3. Write a program that will print the numbers 1 to 10 using while statement.

#include<stdio.h> Outputint x;main( ){

x = 1;while (x <= 10){

printf(“%d\n”, x);x + +;

getch( );}

4.3 The DO-WHILE statement

The second type of open-ended or event-controlled loop is the do-while statement or do-while loop.

The general form of the do-while statement is:

while (condition){

statement_sequence;}

do{

statement_sequence;}while (condition)

Page 35: ES03 Lab Manual

The computed average is 5.50

where:

while and do are reserve words in C

condition is a relational expression that determines when the loop will exit

statement_sequence may either be a single C statement or a single block of C statements that make up the loop body

Do-while is a variation of the while statement which checks the condition at the bottom or end of the loop. This means that a do-while loop “always executes at least once”.

In the do-while loop, when the condition evaluates to TRUE (1), the loop body will be executed, but when FALSE (0), program control proceeds to the next instruction after the do-while loop.

Example 4. Write a program that will get the average of all integers from 1 to 10 using do-while loop.

#include<stdio.h> Outputint x, sum;float average;main( ){

sum = 0;x = 1;do{

sum = sum + x;x + +;

}while (x <= 10)average = sum / 10.00;printf(“The computed average is %.2f\n”, average);getch( );

}

Page 36: ES03 Lab Manual

PROGRAMMING EXERCISES

1. Write a program that will ask the user to enter a number n and display all the numbers from 1 to n on a single line.

2. Write a program that will ask the user to enter a number n and display the sum of all numbers from 1 to n.

3. Write a program that asks the user to enter a number n and display the first n even numbers. Example: if n = 5, the first 5 even numbers are 2, 4, 6, 8 and 10.

4. Write a program that asks the user to enter a number n and display the first n odd numbers. Example: if n = 5, the first 5 odd numbers are 1, 3 , 5 , 7 and 9.

5. Write a program that will compute for n! (n factorial) which is the product of all numbers form 1 to n.

6. Write a program that will compute for and display the sum of all numbers divisible by 3 from 1 to 1000.

7. Write a program that will ask the user to enter a number and display all the factor of the number.

8. Write a program that will accept a number n and display the sum of all even numbers and the sum of all odd numbers from 1 to n.

9. Write a program that will display the following pattern, given the value of n. Example: if n = 4, output

**********

10. Write a program that will display the following pattern, given the value of n. Example: if n = 4, output

**********

11. Write a program that will display the following pattern, given the value of n. Example: if n = 4, output

* ** *******

12. Write a program that will display the following pattern, given the value of n. Example: if n = 4, output

**** *** ** *

13. Write a program that will display the following pattern, given the value of n. Example: if n = 4, output

4321321

Page 37: ES03 Lab Manual

211

14. Write a program that will display the following pattern, given the value of n. Example: if n = 4, output

1234123121

15. Write a program that will display the following pattern, given the value of n and m. Example: if n = 4 and m = 3, output

************

16. Write a program that will display the following pattern, given the value of n and m. Example: if n = 5 and m = 6, output

****** ** ** ** ******

17. Write a program that will display the following pattern, given the value of n. Example: if n = 5, output

* *** ***** **************

18. Write a program that will display the following pattern, given the value of n. Example: if n = 5, output

******** ******* ***** *** *

Page 38: ES03 Lab Manual

Hi! Hello! How are you?

LESSON 5: FUNCTIONS AND STRUCTURED PROGRAMMING

Objectives To learn about using functions in programming To learn the reason for using functions To learn about the commonly used built-in functions in C

A C program is composed of at least one function definition, that is the main( ) function. Execution of the program begins with main( ) and also ends with the main( ) function.

However, a C program can also be composed of other functions aside from main(). Consider the program below:

Example 1. Write a program that will print the lines “Hi! Hello! How are you?” using several functions aside from the main function.

#include<stdio.h> Outputmain( ){

printf(“Hi!”);greet1( );greet2( );getch( );

}

greet1( ){

printf(“Hello!”);}

greet2( ){

printf(“How are you?”);}

The C program presented in example 1 is composed of 3 functions: the main function, the function greet1 and the function greet2.

Therefore we can say that we can create a program that is composed of other functions aside from the main function.

NOTE: The main( ) function should always be present in every C program.

Page 39: ES03 Lab Manual

5.1 Functions

Functions are the building blocks of C in which all program activity occurs.

A function is also called a subprogram or subroutine. It is a part of a C program that performs a task, operation or computation then may return a value to the calling part of the program.

Other functions aside from the main( ) can only be executed by the program through a function call.

NOTE: Function call is a C statement that is used to call a function to execute C statements found inside the function body.

Going back to example 1, the execution of the program starts with the main( ) function. After the clrscr( ) statement the first printf( ) statement will be performed, printing Hi! on the screen.

The next statement greet1( ); is an example of a function call, calling the function greet1( ). Therefore the control of the program transfers to the greet1( ) function executing the printf( ) statement of greet1( ). Therefore, Hello! will be printed.

The control of the program again transfers to the main( ) function. The statement greet2( ); is also a function call, this time calling the function greet2( ). In effect, “How are you?” will be printed on the screen.

The next step is to go back to main( ), then terminate the program after the getch( ) statement.

5.2 General form of a function

The general form of a function is:

where:

function_type specifies the type of value that the function will return.

function_name is any valid identifier name which will name the function.

function_type function_name(parameter list){

body of the function}

Page 40: ES03 Lab Manual

parameter list is a comma separated list of variables that receive the values when the function is called.

body of the function is composed of valid C statements that the function will execute.

Example 2

int subtractor (int x, int y) {

int z;z = x-yreturn (z)

}

Example 2 illustrates a sample of user-defined function. In the example above int is the function type, which means this function will return an integer of whole number value. The name of the function is subtractor. The variables x and y are the two variables that make up the parameter list. It is expected that x and y will receive values once the function is called.

The body of the function inside {} is composed of a local variable declaration for the variable z, an assignment statement and a return statement. These three statements will be executed once the function subtractor is called through a function call.

5.3 Types of functions

C functions are classified into two:

1. Void Functions, which does not return any value when invoked.2. Function that returns a value once invoked.

Example 3

shape ( ){

printf (“* * * * *”);printf (“* *“);printf (“* *“);printf (“* * * * *”);

}

Example 3 is void function. Notice that the function does not contain a return statement for the function to return a value.

Page 41: ES03 Lab Manual

Example 4

int area{

int A;A = L * W;return (A);

}

The function above is an example of a function that will return a value once invoked. Notice that the function contains a return a statement for the variable A. this means that whatever is the computed value of A inside the body of the function will be returned after the function’s execution.

5.4 Actual and Formal Parameters

Actual parameters are the variables found in the function call whose values will be passed to the formal parameters of the called function.

Formal parameters are the variables found in the function header that will receive values from the actual parameters.

Example 5

#include<stdio.h>

main ( ){

int x, y, area;x=25, y=10;area = Compute (x,y); /*x and y are Actualprintf (“%d”, area) parameters*/

}

Compute (int L, int W){

int a;a = L * W; /*L and W arereturn a; Formal parameters*/

}

Page 42: ES03 Lab Manual

In example 5, the variables x and y are the actual parameters. These variables will pass their values to the formal parameters of the function Compute ( ).

On the other hand, the variables L and W are the formal parameters. They will receive the values passed by the variables x and y.

5.5 Call by Value and Pass by Value

The value of the actual parameters can be passed to the corresponding formal parameters either call by value or pass by value.

In the method call by value, the values of the actual parameters are passed to the formal parameters. Changes that happen to the values of the formal parameters inside the function will not affect the values of the actual parameters.

In pass by value or call by reference, the actual parameters also pass their value to the formal parameters. But this time, the changes that happen to the values of the formal parameters inside the function will affect the values of the actual parameters. This is because the actual address of the variables is passed using the address of operator (&) together with the pointer operator (*).

Example 6

#include<stdio.h>

main ( ){

int x, y ;x=10;y=5;printf(“%d%d/n”,x,y);pass (x,y)printf(“%d%d/n”,x,y);getch( );

}

pass (int a, int b){

a=a+5;b=b *2;printf (“%d %d/n”,a,b);

}

Page 43: ES03 Lab Manual

10 515 1010 5

10 515 1015 10

SAMPLE OUTPUT:

Example 6 illustrates call by value. The first printf( ) statement displays the values of the variables x and y printing 10 5 on the screen. The program then calls the function pass. The formal parameters a and b accept the values form x and y. Inside the function pass, the values of a and change to 15 and 10, respectively. The printf( ) statement inside the pass( ) will then print 15 10.

Now, after executing the function pass( ), when control of the program transfers to the main( ) function, the values of x and y remain unchanged. This is because the method that we use is call by value. Therefore the old values of x and y of 10 and 5 will be printed by the last printf( ) statement.

Example 7

#include<stdio.h>

main ( ){

int x, y ;x=10;y=5;printf(“%d%d\n”,x,y);pass (x,y)printf(“%d%d\n”,x,y);getch( );

}

pass (int a, int b){

*a=*a+5;*b=*b *2;printf (“%d %d\n”, *a, *b);

}

SAMPLE OUTPUT:

Page 44: ES03 Lab Manual

The method pass by value or call by reference is illustrated in example 1. Notice the use of the address operator (&) in the actual parameters of the function call, and the pointer operator (*) in the formal parameters of the function heading of pass.

The execution of the program is just similar to that example of 6. The only difference will be on the values that will be printed on the last printf( ) statement. Since we use pass by the value, the changes that happen to the formal parameters a and b will also take effect to the values of x and y. Therefore, once the control of the program transfers to main( ) after executing the body of the function pass( ), the values now of x and y are 15 and 10, respectively.

5.6 C’s Built-in Functions

Aside from user-defined functions, which were discussed earlier in this chapter, C also has built-in functions.

Built-in functions are predefined functions, which can be used by the programmer to perform certain commands or tasks in the program. These functions are already defined in C so there is no need to redefine them because they are ready to use.

The following table summarizes some commonly used built-in functions in C under math.h.

Table 10.1 Commonly Used Built-in Functions in C (math.h)Function Name Use Example

sqrt(x) Calculates the square root of a number

sqrt(9.00) = 3.00

fabs(x) Calculates the absolute value of a number

fabs(11.00) = 11.00fabs(-11.00) = 11.00

ceil(x) Rounds a number to the smallest integer which is not less than the original number

ceil(11.25) = 12

floor(x) Rounds a number to the largest integer which is not greater than the original number

floor(11.25) = 11

sin(x) Calculates the trigonometric sine of a number

sin(0.0) = 0.0

cos(x) Calculates the trigonometric cosine of a number

cos(0.0) = 1.0

tan(x) Calculates the trigonometric tangent of a number

tan(0.0) = 0.0

pow(x,y) Calculates the value of x raised to the yth power

pow(2,3) = 8

*Note: x and y are variables

Page 45: ES03 Lab Manual

PROGRAMMING EXERCISES

1. Write a program that will illustrate the use of a function for computing the square of a number. There must be three other functions aside from main( ). The first function must be responsible for inputting the data, the second for computation of squares and the third, for displaying the result.

Sample Run:

Input N: 3The square of 1 is 1The square of 2 is 4The square of 3 is 9

2. Write a program containing a function that will get the factorial of a number n, which is the product of all numbers from 1 to n.

3. Write a program containing a function that will compute and display the combination of m taken n where:

C(n,m) = n!/(m!(n-m)!)4. Write a program containing a function EquiGrade that will return “A! –

Excellent” if the grade is greater than or equal to 90, “B! – Good” if grade is less than 90 and greater than or equal to 75. “C! – Poor” otherwise.

5. Write a program containing a function that will convert a given measure in kilometers to meters using the following conversion factor (1 km = 1000m).

6. Write a program containing a function that will return the smallest of 3 floating-point numbers.

7. Write a program that inputs 5 numbers and passes them one at a time to function even which uses the modulus operator to determine if an integer is even.

8. Write a program containing a function that returns the Greatest Common Divisor (GDC) of two integers. The GCD of two integers is the largest integer that evenly divides each of the two numbers.

9. Write a program containing a function that will return the largest of 3 floating-point numbers.

10. Write a program containing a function that takes a 5-digit integer and returns the number with its digit reversed. For example, if the number is 12345, the function should return 54321.

Page 46: ES03 Lab Manual

LESSON 6: RECURSION

Objectives To learn about using recursion in programming To apply recursion in programming To determine the difference between direct and indirect recursion

From the previous chapter, we have seen that a user-defined function in C can call other functions through a function call. But aside from calling other functions, a function in a C program can also call itself.

Consider the program segment below:

Example 1.

factorial(int n){

if(n == 1|| n == 0) return1;else return(n*factorial(n-1));

}

The program segment in Example 1 illustrates a function containing a call to itself. The line else return(n*factorial(n-1)); contains the function call for the factorial function.

6.1 Recursion

In C, the repetitive process by which a function calls itself is called recursion or circular definition. This is a way of defining something in terms of itself.

A function is said to be recursive if a statement in the body of the function calls the function that contains it.

A recursive function contains the following parts that are placed using an if-else statement:

a) Base Case – this is the part of the recursive function that is found on the if-clause. This contains the condition that should be satisfied at one point of execution to terminate the repetitive process done by the recursive function.

b) General Case – this is part of the recursive function that is found on the else-clause. This contains the function call of the recursive function to itself.

Page 47: ES03 Lab Manual

4 * factorial (4-1)3 * factorial (3-1)2 * factorial (2-1)

4 * factorial (4-1) = 243 * factorial (3-1) = 62 * factorial (2-1) = 2

NOTE: The repetitive call of the recursion function to itself that is found on the general case should lead towards the condition found on the base case.

A simple example of a recursive function is the factorial function which computes the factorial of an integer n (the product of all whole numbers from 1 to n). This is shown in Example 1.

If the factorial function in Example 1 is called with an argument of 1 or 0, the function returns 1; otherwise it returns the product of n*factorial(n-1). To evaluate this expression, factorial( ) will be called with n-1 as the argument. This process will be repeated until such time that the condition in the if-clause is satisfied, that is, when the value of n becomes 1 or 0.

This will be the tracing part assuming that the initial value passes to n=4:

Simplifying the expressions:

Therefore, the final return value when n=4 is 24.

Example 2. Give the output of the following program when the value entered for a=5.

#include<stdio.h>

main( ){

int a, b;printf(“Enter a value:”);scanf(“%d”, &a);b = solve(a);printf(“The new value is %d”, b);getch( );

}

solve(int a){

if(a == 1) return 2;

Page 48: ES03 Lab Manual

Enter a value: 5The new value is 10

solve (5-1) + 2solve (4-1) + 2solve (3-1) + 2solve (2-1) + 2

solve (5-1) + 2 = 10solve (4-1) + 2 = 8solve (3-1) + 2 = 6solve (2-1) + 2 = 4

else return (solve(a-1) + 2);}

SAMPLE OUTPUT:

This is the tracing part assuming that the value of a=5:

Simplifying the expressions:

Therefore, the final return value when a=5 is 10.

Example 3. Give the output of the following program when the value entered for a=4.

#include<stdio.h>

main( ){

int a, b;printf(“Enter a value:”);scanf(“%d”, &a);b = solve(a);printf(“The new value is %d”, b);getch( );

}

solve(int a){

if(a == 1) return 1;else return (solve(a-1) + 2);

}

Page 49: ES03 Lab Manual

Enter a value: 4The new value is 7

solve (4-1) + 2solve (3-1) + 2solve (2-1) + 2

solve (4-1) + 2 = 7solve (3-1) + 2 = 5solve (2-1) + 2 = 3

SAMPLE OUTPUT:

This is the tracing part assuming that the value of a=4:

Simplifying the expressions:

Therefore, the final return value when a=4 is 7.

6.2 Indirect Recursion

The examples presented on the earlier part of this chapter are examples of direct recursions. Direct recursions are recursive functions that call itself through a function call directly inside the body of the function. However, recursive functions can also be called indirectly. That is, another function will be defined to make the recursive call. This is called indirect recursion.

Consider the example below:

Example 4. Give the output of the following program when the value entered for a = 5.

#include<stdio.h>

main( ){

int a, b;printf(“Enter a value:”);scanf(“%d”, &a);b = solve(a);printf(“The new value is %d”, b);

Page 50: ES03 Lab Manual

Enter a value: 52 4 6 8 10

getch( );}

solve(int a){

int b;if (a == 1){

b = 2;printf(“%d”, b);return b;

}else{

b = solve2 (a-1) + 2;printf(“%d”, b);return b;

}}

solve2(int a){

int b;if (a == 1){

b = 2;printf(“%d”, b);return b;

}else{

b = solve (a-1) + 2;printf(“%d”, b);return b;

}}

SAMPLE OUTPUT:

Example 4 presents a C program containing indirect recursions. Notice that the functions solve() and solve2() call each other. This is an indirect way of having recursive definition.

Page 51: ES03 Lab Manual

solve2 (5-1) + 2solve (4-1) + 2solve2 (3-1) + 2solve (2-1) + 2

solve2 (5-1) + 2 = 10solve (4-1) + 2 = 8solve2 (3-1) + 2 = 6solve (2-1) + 2 = 4

Assuming that that value entered for the variable a in the main() function is 5. The function solve() will be first called passing 5 as the parameter. solve() and solve2() will alternately call each other until condition in their if-clause is satisfied. That is, when either solve() or solve2() will be called with the value one (1) as the passed parameter to a.

This is the tracing part assuming that the value of a=5:

Simplifying the expressions:

Therefore, when a = 5 the values 2 4 6 8 10 will be printed on screen.

Page 52: ES03 Lab Manual

PROGRAMMING EXERCISES

1. Write a C program containing a recursive function that will raise a certain integer x to a certain positive integer n. (Example: if x=2 and n=3, find 23 = 2 * 2 * 2 = 8)

2. Write a program containing the recursive function that will find the following series of numbers 2, 1, 4, 3, 6, 5, 8, 7 … given the value of n from 1 to positive infinity.

3. Write a C program containing a recursive function that will get the whole number quotient result of dividing two integers n and m. (Example: if n=4 and m=3, 4/3 = 1. Output 1)

4. The Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13, 21 … begins with terms 0 and 1 and has the property that each succeeding term is the sum of the two previous terms. Write a program containing a recursive function that computes and displays the nth

Fibonacci number, given the value for n.5. The Greatest Common Divisor (GCD) of two numbers is the largest integer that

evenly divides the two numbers. Write a program containing a recursive function that returns the GCD of two numbers.

Page 53: ES03 Lab Manual

LESSON 7: SINGLE-DIMENSIONAL ARRAYS

Objectives To learn about using arrays in programming To apply arrays in programming

7.1 Arrays

An array is a collection of variables of the same data type that is referenced by a common name.

Consider the illustration below for the array Array1:

25 5 7 11 163

Array1

In the illustration above, the name of the array is Array1. Notice that Array1 contains five whole number values. Each of these values is called an array element.

The specific element in an array is accessed by a position number called an index or subscript.

For arrays in C, the first element of the array has an index of subscript of zero and the last element has an index or subscript of size – 1 where size is the total number of elements in the array.

In our array example, the first array element with a value of 25 has an index of 0, the second element with a value of 5 has an index of 1, the third element with a value of 7 has an index of 2, the fourth element with a value of 11 has an index of 3 and the fifth element with a value of 163 has an index of 4.

7.2 Referencing Array Elements

To reference individual elements of an array, we have to specify the array name and the position number of element (subscript or index) that is enclosed in pair of square bracket [ ].

25 5 7 11 163

Array1

Page 54: ES03 Lab Manual

Therefore the five elements in our array Array1 are the following: Array1[0], Array1[1], Array1[2], Array1[3], Array1[4]. The values of these elements are:

Array1[0] = 25Array1[1] = 5Array1[2] = 7Array1[3] = 11Array1[4] = 163

7.3 Array Declaration

Like ordinary variables, arrays must be declared before they are used in a C program.

The general form for an array declaration is as follows:

where:

type is any valid data type in C which declares the type of values the array will hold

array_name is a valid variable name which will name the array

size defines how many elements the array will hold

Following the general form for an array declaration, the correct declaration for the array Array1 will be:

int Array1[5];

In the declaration above, the data type is int since Array1 holds whole number values. The data type int is followed by the array name, which is Array1. The size of 5 is enclosed in the pair of square brackets [ ] indicates that Array1 is capable of storing 5 integer values.

Example 1. Declare a ten-element floating-point array A.

float A[10];

This declaration declares that arrayA is capable of storing 10 floating-point numbers.

type array_name[size];

Page 55: ES03 Lab Manual

Example 2. Provide the declaration for arrays number with a size of 100 and array answer with a size of 25. Both are integer-arrays.

To answer the second example, we can have the following declarations:

int number[100];int answer[25];

The two declarations for arrays number and answer can be combined into a single declaration:

int number[100], answer[25];

NOTE: You can declare more than one array in a single declaration provided that the arrays are of the same data type. Each of the arrays should be separated by comma in the declaration.

7.4 Array Initialization

Arrays in C can be given initial values during the declaration. This is called array initialization.

Consider the example below:

Example 3. Provide the declaration for the integer-array Array1 with the following initial values: 25, 5, 7, 11 and 163.

int Array1[5] = {25, 5, 7, 11, 163};

In the declaration, {25, 5, 7, 11, 163} is called the initializer list. The initializer list provides the initial values for the array. The comma-separated list of values are enclosed in pairs of curly bracket { },

Example 4. Provide the declaration for the integer-array result with the following intial values: 87, 85, 76 and 90.

int result[4] = {87, 85, 76, 90};

In the declaration for the array result, we say that:

result[0] = 87result[1] = 85result[2] = 76result[3] = 90

Page 56: ES03 Lab Manual

We should remember the following things regarding array initialization:

1. If there are fewer intializers than the size of the array, the remaining elements are initialized to zero.

Example 5.

int n[10] = {5, 26};

Based from the declaration, we say that:

n[0] = 5n[1] = 26n[2] = 0n[3] = 0n[4] = 0n[5] = 0n[6] = 0n[7] = 0n[8] = 0n[9] = 0

2. An initializer list that is greater than the array size is a syntax error.

Example 6.

int g[3] = {5, 16, -3, 67};

Therefore, the declaration above is wrong because there are four initializers in the initializer list while the size of the array is only three.

3. If the array size is omitted from a declaration with an initializer list, the number of elements in the array will be the number of elements in the initializer list.

Example 7.

int exam[ ] = {88, 89, 90, 60, 78};

The declaration above will automatically create a five-element array of type integer with the following values:

exam[0] = 88exam[1] = 89exam[2] = 90exam[3] = 60

Page 57: ES03 Lab Manual

Element 0 is 5Element 1 is 10Element 2 is 15Element 3 is 20 Element 4 is 25

The sum is 39

exam[4] = 78

Example 8. Write a C program that will print the values of the following array: int n[5] = {5, 10, 15, 20, 25}.

#include<stdio.h>main( ){

int n[5] = {5, 10, 15, 20, 25];int x;for (x = 0; x <= 4; x++)

printf(“Element %d is %d”, x, n[x]);getch( );

}

SAMPLE OUTPUT:

Example 9. Write a C program that will compute and display the sum of the following array:

int a[5] = {2, 1, 0, 5, 2, 7, 4, 3, 10, 5}

#include<stdio.h>main( ){

int a[5] = {2, 1, 0, 5, 2, 7, 4, 3, 10, 15};int x, sum;sum = 0;for (x = 0; x <= 9; x++)

sum += a[x];printf(“The sum is %d”, sum);getch( );

}

SAMPLE OUTPUT:

Page 58: ES03 Lab Manual

PROGRAMMING EXERCISES

1. Write a program that will search for the largest value in an array of integers of length 10.

2. Write a program that will search for the smallest value in an array of integers of length 10.

3. Write a program that will take the sum of all the array elements greater than 80 in an array of 10 elements completely filled by the user.

4. Write a program that will print the odd positioned elements in an array of 10 integers.

5. Write a program that will print the even positioned elements in an array of 10 integers.

6. Write a program that will arrange the elements of a 10-integer array in ascending order.

7. Write a program that will arrange the elements of a 10-integer array in descending order.

8. Write a program that will compute and display the average of a 20-element array whose values are inputted by the user.

9. Write a program that will output all the even numbers found in an array of 20 integers. Display also the sum of the values found.

10. Write a program that will output all the odd numbers found in an array of 20 integers. Display also the sum of the values found.