You are on page 1of 59

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

ES 03 : Computer Fundamentals and Programming Department of Electronics, College of Engineering Xavier 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. Engr. Ingrid Yvonne A. Madrial 2 Units (6 Hours per Week) 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.

INSTRUCTOR: CREDIT UNITS: CO-REQUISITE: OBJECTIVES:

Lesson No. 1 2 3 4 5 6 7

Title Laboratory Rules and Equipment Orientation Overview of the C Language Input and Output Statements Conditional Statements Iterative Statements Functions and Structured Programming Recursion Single Dimensional Arrays DESIGN PROJECT PROJECT DEFENSE

No. of Hours 3 3 6 3 3 3 6 6 6 6

Grading System: FG = 10% Attendance + 25% Lab. Exercises + 30% Class Participation + 35% Project Detailed Criteria: Lab Exercises Neatness, Completeness Data/Results Answer to Questions Analysis and Conclusion Total Project Weekly Report Final Paper Final Defense Total GRADING STANDARDS Grading Standards: 35% 30% 35% 100% 20% 30% 20% 30% 100%

92.00 84.00 76.00 68.00 60.00 59.99

100.00 91.00 83.00 75.00 67.00 And below

A AB BC F

LESSON 1: OVERVIEW OF THE C LANGUAGE


Objectives To determine the history of the C language To familiarize the parts of the Dev-C++ Integrated Development Environment 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 Bs 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 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 Dev-C++ Integrated Development Environment

1.5 Four Parts of Dev-C++ IDE 1. Main Menu

instructs C to do something as indicated in the list of menu.

Basic commands of C 1. File used to load and save files in C. 2. Run used to compile (check for errors), links, and runs the program currently loaded in the environment. 3. Compile used to compile the program currently in the environment. 2. Text Editor - It is where you type your program and where you see the current line and column of the text you typed. 3. Compiler message window - It is located below the text editor. It is used to display various compiler or linker meassages. 4. Hotkeys - It is located beneath the middle of main menu and text editor. It refers to shortcut or shorthand for selecting a menu. 1.6 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 char int float double void 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: signed unsigned Bidwidth 8 16 32 64 0 Range 0 to 255 -32768 to 32767 3.4E-38 to 3.4E+38 1.7E-308 to 1.7E+308 valueless

long short Type char unsigned char signed char int unsigned int signed int short int unsigned short int signed short int long int unsigned long int signed long int float double long double 1.7 Keywords Keywords in C are reserved words that have a special meaning. Reserved 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 break case char const continue default do 1.8 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.9 Variables double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while Bidwidth 8 8 8 16 16 16 16 16 16 32 32 32 32 64 64 Range -128 to 127 0 to 255 -128 to 127 -32768 to 32767 0 to 65535 -32768 to 32767 -32768 to 32767 0 to 65535 -32768 to 32767 -2147483648 to 2147483647 0 to 4294967295 -2147483648 to 2147483647 3.4E-38 to 3.4E+38 1.7E-308 to 1.7E+308 1.7E-308 to 1.7E+308

Variables are identifiers that can store a changeable value. These can be different data types. 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: 1.9.2 int i, j, k; short i, j, k;

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( ) { 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 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 > >= < <= == != 1.11.2.2 Logical Operators Operator && Action AND Truth Table true && true = true true && false = false false && true = false false && false = false true && true = true true && false = true false && true = true false && false = false ! true = false ! false = true Action Greater than Greater than or equal to Less than Less than or equal to Equal Not equal

||

OR

! 1.11.3 Bitwise Operator

NOT

Bitwise operations are the testing, setting or shifting of the actual bits in a byte or a word, which corresponds to Cs 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. Operator & | ^ ~ >> << 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; else y = 200; 1.12 Evaluation of Expression Action AND OR Exclusive OR (XOR) Ones complement Shift right Shift left

Expression refers to anything that evaluates to a numeric value. Operator precedence and associativity Operators () ++ (postfix) -- (postfix) + (unary) - (unary) ++ (prefix) -- (prefix) * / % + < <= > >= == != && || ?: = += -= *= /= etc , (comma operator) Examples: Associativity Left to right Right to left Left to right Left to right Left to right Left to right Left to right Left to right Right to left Right to left Left to right

A. Evaluate the following: 1. Given: z = 5, a = 3, b = 9, w = 2, y = -5; Expression: z (a * b / 2) + w * y 5 (3 * 9 / 2) + 2 * -5 5 (27 / 2) + -10 5 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 / 5 12 * -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 || 1 1 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 <= 0 0 FALSE

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 * c a + 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 Cs 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. 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 functions

2. conio.h declares various functions used in calling IBM-PC ROM BIOS 3. 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 \n { } & * Important Symbols

- 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

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

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 C scanf(%c, &ch); printf(%c, ch); %d decimal number (whole number) scanf(%d, &num); printf(%d, num); %e scientific notation/exponential form scanf(%e, &result); printf(%e, result); %f number with floating or decimal point scanf(%f, &pesos); printf(%f, pesos); %o octal number scanf(%o, &value);

printf(%o, value); %s string of characters scanf(%s, str); printf(%s, str); %u unsigned number scanf(%u, &nos); printf(%u, nos); %x hexadecimal number scanf(%x, &value); printf(%x, value); %X capital number for hexadecimal number scanf(%X, &nos); printf(%X, nos); %% - print a percent sign scanf(%%, &value); printf(%%, value); List of commonly used escape sequences: \\ \ \ \? \n 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 Hello World! - prints backslash - prints single quotes - prints double quotes - prints question mark - newline

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 Normans 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> Output main( ) Wreck of the Hesperus: { Its depth at sea in different units: int inches, feet, fathoms; 7 fathoms fathoms = 7; 42 feet feet = 6 * fathoms; 504 inches 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 persons name and age. #include<stdio.h> Output main( ) Enter Name: Paul { Enter Age: 3 int age; Hello Paul, you are 3 years old 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> main( ) { int A, B, Sum, Prod; printf(\nFirst number:); scanf(%d, &A); printf(Second number:); Output First number: 5 Second number: 6 Sum of two numbers: 11 Product of two numbers: 30

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> main( ) { char first, middle, last; int age; Output Input your three initials and your age: Greetings f.a.p. Next year your age will be 26

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

PROGRAMMING EXERCISES 1. 2. Create a program that asks for a distance in kilometers and converts it into its metric equivalent. 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. Create a program that converts a Fahrenheit measure to a Celsius measure (C = 5/9 x (F32)). 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. Create a program that will input a number in kilowatt and display its equivalent measure in watts. 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. Make a program that will convert an inputted number in inches (in.) and display its equivalent measure in feet (ft). 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. Write a program that inputs two real numbers then exchanges their values. Make a program the will accept a number in square meters (m 2) and display its equivalent measure in hectares (has). Hint: 1000 m2 = 1 ha

3. 4. 5. 6. 7. 8. 9. 10.

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:

if (expression) statement;

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:

if (expression) { statement_sequence; }
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.

Example 1. Write a program that will output Congratulations you PASSED! if the students grade is greater than or equal to 60. #include<stdio.h> int grade; main( ) { Output Enter student grade: 95 Congratulations you PASSED!

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> Output float price, discount; Enter value for price: 2000 main( ) Discount is 200.00 { 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:

if (expression) statement_1; else statement_2;


where:

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:

if (expression) { statement_sequence; } else { statement_sequence; }


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 students grade is greater than or equal to 60. Otherwise output, Sorry you FAILED! Output Enter student grade: 50 Sorry you FAILED!

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

printf(Enter student grade:); scanf(%d, &grade); if (grade >= 60) printf(Congratulations you PASSED!); else printf(Sorry you FAILED!); getch( ); }

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. 2. 3. if if else

Situation 2 The else in number 5 is paired with the if in number 1. 1. if 2. { 3. 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.

if

#include<stdio.h> Output int A, B, C; Enter three numbers: 7 11 5 main( ) B is the largest. { 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); else printf(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:

if (expression_1) statement_1; else if (expression_2) statement_2; else if (expression_3) statement_3; : : else statement_else;
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

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> Output main( ) Enter an integer: 4 { Wednesday 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. Enter an integer: 4 Wednesday

The general form of the switch statement is:

switch (variable) { case constant1: statement sequence_1; break; case constant2: statement sequence_2; break; : : default: statement_sequence_default; }
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 }.

3.5.1

Nested Switch Statement The general form of the nested switch statement is:

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; }
Example 6. Rewrite the program in Example 5 using a switch statement. #include<stdio.h> main( ) { int day; printf(Enter an integer:); scanf(%d, &day); switch (day) { case 1: printf(Sunday); break; case 2: Output Enter an integer: 11 Day is not available!

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> Output main( ) Enter number 1: 10 { Enter number 2: 25 int num1, num2, ans; A Addition char operation; S Subtraction printf(Enter number 1:); M Multiplication scanf(%d, &num1); D Division printf(Enter number 2:); Enter a character for the operation: A scanf(%d, &num2); The answer is: 35 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:

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

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 rate Bonuses are given: No. of hours > 45 Bonus of 500 pesos No. of hours > 40 and <=45 Bonus of 250 pesos No. of hours > 35 and <=40 Bonus of 150 pesos Display 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 Bonus 1 10% of salary 2 to 5 20% of salary 5 to 10 50% of salary 11 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 ITS COLD! if the temperature is less than 20, ITS 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 students name, midterm grade, minor exam, and final exam ratings.

b.

12.

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.00 95 97 = 3.75 92 94 = 3.50 89 91 = 3.25 86 88 = 3.00 83 85 = 2.75 80 82 = 2.50 77 79 = 2.25 74 76 = 2.00 71 73 = 1.75 68 70 = 1.50 64 67 = 1.25 60 63 = 1.00 below 60= 0.00 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: 10 Enter day: 23 Enter year: 2000 October 23, 2000

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 loops 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:

for (initialization; condition; increment) { statement_sequence; }


where: for is a reserve word in C initialization is an assignment statement that is used to set the loops counter condition is a relational Boolean expression that determines when the loop will exit increment defines how the loops 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.

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 loops 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> int x; main( ) { for(x = 1; x <= 10; x + +) printf(%d\n, x); getch( ); } Output 1 2 3 4 5 6 7 8 9 10

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> Output int x, sum; The sum of 1 to 10 is 55 main( ) { sum = 0; for(x = 1; x <= 10; x + +) sum = sum + x; printf(The sum of 1 to 10 is %d\n, sum); getch( ); }

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:

while (condition) { statement_sequence; }


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> int 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: Output 1 2 3 4 5 6 7 8 9 10

do { statement_sequence; } while (condition)

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> Output int x, sum; The computed average is 5.50 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( ); }

PROGRAMMING EXERCISES 1. 2. 3. 4. 5. 6. 7. 8. 9. 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. Write a program that will ask the user to enter a number n and display the sum of all numbers from 1 to n. 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. 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. Write a program that will compute for n! (n factorial) which is the product of all numbers form 1 to n. Write a program that will compute for and display the sum of all numbers divisible by 3 from 1 to 1000. Write a program that will ask the user to enter a number and display all the factor of the number. 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. Write a program that will display the following pattern, given the value of n. Example: if n = 4, output * ** *** **** Write a program that will display the following pattern, given the value of n. Example: if n = 4, output **** *** ** * Write a program that will display the following pattern, given the value of n. Example: if n = 4, output * ** *** **** Write a program that will display the following pattern, given the value of n. Example: if n = 4, output **** *** ** * Write a program that will display the following pattern, given the value of n. Example: if n = 4, output 4321 321

10.

11.

12.

13.

14.

15.

16.

17.

21 1 Write a program that will display the following pattern, given the value of n. Example: if n = 4, output 1234 123 12 1 Write a program that will display the following pattern, given the value of n and m. Example: if n = 4 and m = 3, output **** **** **** Write a program that will display the following pattern, given the value of n and m. Example: if n = 5 and m = 6, output ***** * * * * * * * * ***** Write a program that will display the following pattern, given the value of n. Example: if n = 5, output * *** ***** ****** ******** Write a program that will display the following pattern, given the value of n. Example: if n = 5, output ******** ******* ***** *** *

18.

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. Output Hi! Hello! How are you?

#include<stdio.h> main( ) { 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.

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:

function_type function_name(parameter list) { body of the function }


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.

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-y return (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.

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 functions 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); printf (%d, area) } Compute (int L, int W) { int a; a = L * W; return a; }

/*x and y are Actual parameters*/

/*L and W are Formal parameters*/

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

SAMPLE OUTPUT: 10 5 15 10 10 5 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: 10 5 15 10 15 10

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 Cs 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 sqrt(9.00) = 3.00 of a number fabs(x) Calculates the absolute fabs(11.00) = 11.00 value of a number fabs(-11.00) = 11.00 ceil(x) Rounds a number to the ceil(11.25) = 12 smallest integer which is not less than the original number floor(x) Rounds a number to the floor(11.25) = 11 largest integer which is not greater than the original number sin(x) Calculates the trigonometric sin(0.0) = 0.0 sine of a number cos(x) Calculates the trigonometric cos(0.0) = 1.0 cosine of a number tan(x) Calculates the trigonometric tan(0.0) = 0.0 tangent of a number pow(x,y) Calculates the value of x pow(2,3) = 8 raised to the yth power *Note: x and y are variables

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: 3 The square of 1 is 1 The square of 2 is 4 The square of 3 is 9 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. 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)!) 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. Write a program containing a function that will convert a given measure in kilometers to meters using the following conversion factor (1 km = 1000m). Write a program containing a function that will return the smallest of 3 floatingpoint numbers. 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. 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. Write a program containing a function that will return the largest of 3 floatingpoint numbers. 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.

2. 3. 4. 5. 6. 7. 8. 9. 10.

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 ifclause. This contains the condition that should be satisfied at one point of execution to terminate the repetitive process done by the recursive function. 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.

b)

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: 4 * factorial (4-1) 3 * factorial (3-1) 2 * factorial (2-1) Simplifying the expressions: 4 * factorial (4-1) = 24 3 * factorial (3-1) = 6 2 * factorial (2-1) = 2 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;

else return (solve(a-1) + 2); } SAMPLE OUTPUT: Enter a value: 5 The new value is 10 This is the tracing part assuming that the value of a=5: solve (5-1) + 2 solve (4-1) + 2 solve (3-1) + 2 solve (2-1) + 2 Simplifying the expressions: solve (5-1) + 2 = 10 solve (4-1) + 2 = 8 solve (3-1) + 2 = 6 solve (2-1) + 2 = 4 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); }

SAMPLE OUTPUT: Enter a value: 4 The new value is 7 This is the tracing part assuming that the value of a=4: solve (4-1) + 2 solve (3-1) + 2 solve (2-1) + 2

Simplifying the expressions: solve (4-1) + 2 = 7 solve (3-1) + 2 = 5 solve (2-1) + 2 = 3

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

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: Enter a value: 5 2 4 6 8 10 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.

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: solve2 (5-1) + 2 solve (4-1) + 2 solve2 (3-1) + 2 solve (2-1) + 2 Simplifying the expressions: solve2 (5-1) + 2 = 10 solve (4-1) + 2 = 8 solve2 (3-1) + 2 = 6 solve (2-1) + 2 = 4 Therefore, when a = 5 the values 2 4 6 8 10 will be printed on screen.

PROGRAMMING EXERCISES 1. 2. 3. 4. 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) 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. 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) 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. 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.

5.

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 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 Array1 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: 11 163 11 163

Array1[0] Array1[1] Array1[2] Array1[3] Array1[4] 7.3 Array Declaration

= = = = =

25 5 7 11 163

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:

type array_name[size];

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.

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] result[1] result[2] result[3] = = = = 87 85 76 90

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] n[1] n[2] n[3] n[4] n[5] n[6] n[7] n[8] n[9] = = = = = = = = = = 5 26 0 0 0 0 0 0 0 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] exam[1] exam[2] exam[3] exam[4] = = = = = 88 89 90 60 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: Element 0 is 5 Element 1 is 10 Element 2 is 15 Element 3 is 20 Element 4 is 25 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: The sum is 39

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.