ES03 Lab Manual

March 22, 2018 | Author: HanzhellJ.Campugan | Category: Subroutine, C (Programming Language), Control Flow, Parameter (Computer Programming), Data Type


Comments



Description

XAVIER UNIVERSITYAteneo 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 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 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 6 Data Types There are five elementary data types in C: character (char). double floating point (double) and void. It is used to display various compiler or linker meassages. A modifier is used to alter the meaning of the base type to fit the needs of various situations more precisely. 3.4E-38 to 3. Type char int float double void Type Modifiers Except type void. Compiler message window . 2. Text Editor . floating point (float). the basic data types may have various modifiers preceding them. 1. Values of type char are used to hold ASCII characters or any 8-bit quantity. Hotkeys . and runs the program currently loaded in the environment.- instructs C to do something as indicated in the list of menu.7E-308 to 1. integer (int). The list of modifiers includes the following: signed unsigned Bidwidth 8 16 32 64 0 Range 0 to 255 -32768 to 32767 3. 4. Run – used to compile (check for errors). File – used to load and save files in C. It refers to shortcut or shorthand for selecting a menu. The type void has three uses: The first is to declare explicitly a function as returning no value. The third is to create generic pointers.It is where you type your program and where you see the current line and column of the text you typed.It is located beneath the middle of main menu and text editor. 3. Basic commands of C 1.4E+38 1.7E+308 valueless . The second is to declare explicitly a function as having no parameters. Variables of type int are use to hold integer quantities. Compile – used to compile the program currently in the environment. Values of type float and double are used to hold real numbers. 2. links.It is located below the text editor. Real numbers have both an integer and fractional component. Reserved words are words “reserved” by the programming language for expressing various statements and constructs.4E-38 to 3.7 Keywords Keywords in C are reserved words that have a special meaning.7E+308 1.7E+308 .8 Identifiers Identifiers are composed of a sequence of letters. and the special character underscore. digits. thus. these may not be redefined by the programmer.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 1. List of 32 Keywords/Reserved words as defined by the ANSI standard auto break case char const continue default do 1. Limit the identifiers from 8 to 15 characters only.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.7E-308 to 1. Avoid using names that are too short or too long.7E-308 to 1. 1. Variables are identifiers that can store a changeable value. short i. meaning uppercase is not equal to the lowercase. Example: ans ≠ Ans ≠ aNs ≠ anS ≠ ANs ≠ ANS 5. These can be different data types. 7. The general form of declaration is shown here: Type variable list. Example: printf. num_1 (correct) 2. Example: 1name.2 int i. Do not call your variable/identifier by the same name as other functions. j. It is case sensitive. 1. Example: 1. Two kinds of variable A. Do not include embedded blanks. Example:_duh.9. and underscore.1 Variable Declaration All variables must be declared before they may be used.h> . k. An identifier defined in the C standard library should not be redefined. j. k. scanf (incorrect) 4. digits. It must consist only of letters. It can only be referenced by statements that are inside the block in which the variables are declared. Example: large num (incorrect) 6.9. Do not use any of the C language keywords as your variable/identifier. It should not begin with a digit. Example: #include<stdio. Rules for defining or naming identifiers/variables: 1. 3to3 (incorrect) 3. Local Variables Variables that are declared inside a function are called local variables. main( ) { int a. b. Example: #include<stdio.1 Arithmetic Operators Operator + Action Addition . } 1. 1. main( ) { ________. ________. } B. Example: const int count = 100. Logical. c. Relational.10 Constants Constants are identifiers/variables that can store a value that cannot be changed during program execution. logical and relational and bitwise. There are three classes of operators in C: arithmetic. Global variables are created by declaring them outside of any function.11 Arithmetic. Where integer count has a fixed value of 100 1. and Bitwise Operators Operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.11.h> int a. Global Variables Global variables are known throughout the entire program and may be used by any piece of code. b. ________. ________. ________. c. ________. 1 Relational Operators Operator > >= < <= == != 1. the word relational refers to the relationship values can have with one another. setting or shifting of the actual bits in a byte or a word.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.2.3 Bitwise Operator NOT Bitwise operations are the testing.* / % -++ Subtraction Multiplication Division Modulus Divisor Decrement a value Increment a value 1.2 Relational and Logical Operators In the term relation operator.11. 1.11. which corresponds to C’s standard char and int data types and .11.2. The key to the concept of relational and logical operators is the idea of true or false.11. the word logical refers to the ways these relationships can be connected together using the rules of formal logic. In the term logical operator. void or other more complex types.(unary) ++ (prefix) -.12 Evaluation of Expression Action AND OR Exclusive OR (XOR) One’s complement Shift right Shift left Expression refers to anything that evaluates to a numeric value. else y = 200. (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 . double. Bitwise operators cannot be used on type float. long double. Operator precedence and associativity Operators () ++ (postfix) -.(prefix) * / % + < <= > >= == != && || ?: = += -= *= /= etc . 1. Operator & | ^ ~ >> << 1. Example: y = x > 9 ? 100:200 is equivalent to if (x > 9) y = 100.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.variants.(postfix) + (unary) .11. k = 3 .A. Given: z = 5. Given : x = 3. c = 4. y = 3.13 Converting Mathematical Formula to C Expression To solve mathematical problems using the computer. y = 2. j = 5. z = 2.0 + 2. y = 4. y = -5. Evaluate the following expressions and determine whether they yield a value of TRUE or FALSE 1. Expression : (x – y) <= (j – k = = 3) (3 – 2) <= (5 – 3 = = 3) 1 <= (2 = = 3) 1 <= 0 0 FALSE 1.0 >= 3. Expression: z – (a * b / 2) + w * y 5 – (3 * 9 / 2) + 2 * -5 5 – (27 / 2) + -10 5 – 13 – 10 -8 – 10 -18 2.0 – 2. Expression : ! dei || (y + z >= x – z) ! 0 || (4.0) 1 || (6. Expression: (a * b + 2) * -y / (c + x) (5 * 2 + 2) * -3 / (4 + 1) (10 + 2) * -3 / 5 12 * -3 / 5 -36 / 5 -7 B. Given : a = 5. the formula should be translated to the programming language to be used. b = 9. a = 3. x = 1 .0 >= 1. Arithmetic computation should be written as C expressions. Given: dei = 0. b = 2.0. w = 2.0.0. Evaluate the following: 1. . x = 3.0) 1 || 1 1 TRUE 2. . To use the computer to solve such problems. these conditions should be converted to the C. #include directive – contains information needed by the program to ensure the correct operation of C’s standard library functions. alloc.16 Commonly used include files in C language 1.0 1. Variable declaration section – it is the place where you declare your variables. – also used to define constants and aliases. Example: x and y are greater than z can be converted to x > z && y > z x is equal to 1. D.Example: b2 – 4ac = b * b – 4 * a * c a + b = (a + b) / (c + d) c+d 1. Example: #define g gotoxy C.15 Structure of a simple C program <#include directive> <#define directive> main( ) { <variable declaration section> statements .0 || x = = 3.14 Converting English Conditions to C Expressions Solutions to problems may sometimes depend on a set of conditions. #define directive – used to shorten the keywords in the program.0 or 3.. 1. Example: #include<stdio. All statements should be written inside the { and } braces.0 can be converted to x = = 1. Body of the program – start by typing main( ) and the { and } (open and close braces). } A.h> B.h – declares memory management functions . stdio.open curly brace signifies begin .is a line char used to move the cursor to the next line .h – contains information used by the classification and character conversion macros. ctype.double quote is used for two or more character .close curly brace signifies end . 6.h – declares several string manipulation and memory manipulation routines.single quote is used for single character/letter . conio. math. 1.indirection operator/pointer .h – declares various functions used in calling IBM-PC ROM BIOS 3. string.h – declares prototype for the math functions. 4.2.h – defines types and macros needed for standard I/O. 5.address of operator .17 \n ‘‘ ““ { } & * Important Symbols . getche – a function used to input a single character from the keyboard. Example: ch = getche( ). 1. the character pressed echoed on the monitor. identifier). spaces are accepted. &num). 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. Syntax: getche( ). terminated by pressing ENTER key. execute.LESSON 2: INPUT AND OUTPUT STATEMENTS Objectives • To be able to create. Example: ch = getchar( ). getchar – a function used to input a single character from the keyboard. the character pressed echoed on the monitor.1 Input Statement A statement used to input a single character or a sequence of characters from the keyboard. it needs the control string codes in able to recognized. Syntax: getch( ). terminated by pressing enter key. 3. Example: scanf(“%d”. Example: gets(ch). 4. gets – a function used to input sequence of character from the keyboard. 2.2 Output Statement . Spaces are not accepted upon inputting. Example: ch = getch( ). 5. Terminated by pressing spacebar. Syntax: getchar( ). getch – a function used to input a single character from the keyboard without echoing the character on the monitor. like the READLN in PASCAL. 2. Syntax: gets( ). Syntax: scanf(“control string codes”. scanf – a function used to input single character or sequence of characters from the keyboard. printf(“%e”.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. printf(“%c”. &pesos). Syntax: puts( ). %s. printf – a function used to display the argument list on the monitor. you are %d years old”. 2. 1. %o – octal number scanf(“%o”. pesos). &value). Syntax: putchar( ). Example: printf(“Hello. List of commonly used format specifiers: %c – used for single char in C scanf(“%c”. 2. It sometimes needs the control string codes to help display the remaining argument on the screen.A statement used to display the argument list or string on the monitor. name. Syntax: printf(“control string codes”. Example: puts(“hello”). result). %d – decimal number (whole number) scanf(“%d”. puts – a function used to display the argument list or string on the monitor. . 3. printf(“%f”. age). %f – number with floating or decimal point scanf(“%f”. &ch). It is like overwriting a character. It does not need the help of the control string codes. putchar – a function used to display the argument list or string on the monitor. argument list). &result). ch). printf(“%d”. Example: putchar(tolower (ch)). %e – scientific notation/exponential form scanf(“%e”. num). &num). nos). value). Create the traditional first program in honor of Dennis Ritchie. %% .newline .prints question mark .h> main() { printf("Hello World!\n"). value). %x – hexadecimal number scanf(“%x”. %u – unsigned number scanf(“%u”. %X – capital number for hexadecimal number scanf(“%X”.prints single quotes . printf(“%s”. printf(“%X”. value). //this line is only needed under windows } Output Hello World! . printf(“%%”. str).print a percent sign scanf(“%%”. nos). system("pause"). /* The traditional first program in honor of Dennis Ritchie who invented C at Bell Labs in 1972 */ #include <stdio. List of commonly used escape sequences: \\ \’ \” \? \n Examples: 1. &value).printf(“%o”. printf(“%x”.prints backslash . str). &nos). printf(“%u”. &nos).prints double quotes . &value). %s – string of characters scanf(“%s”. 2. The waters off the reef are about 7 fathoms deep. printf(“\n Hello %s. occurred off the reef of Norman’s Woe near Gloucester. scanf(“%d”. Prod. printf(“\nFirst number:”). age). #include<stdio. printf(“Its depth at sea in different units:\n”). fathoms). Write a program based on the wreck of the ship Hesperus. #include<stdio. Output First number: 5 Second number: 6 Sum of two numbers: 11 Product of two numbers: 30 . Make a program that will compute and display the sum and product of two numbers. name). printf(“Second number:”). Sum. scanf(“%d”. } 3. feet). 7 fathoms fathoms = 7. inches). Create a program that accepts and displays a person’s name and age. &A). in 1839. Massachusetts. you are 3 years old char name[10]. printf(“ %d inches\n”. printf(“\n Enter Name:”). } 4. printf(“ %d fathoms\n”. printf(“ %d feet\n”. feet. printf(“\n Enter Age:”). you are %d years old”. scanf(“%s”. This calamity at sea. printf(“Wreck of the Hesperus:\n”). B. fathoms.h> main( ) { int A. 504 inches inches = 12 * feet. &age). In the program we convert this depth to other units of measure. #include <stdio. getch( ).h> Output main( ) Wreck of the Hesperus: { Its depth at sea in different units: int inches.h> Output main( ) Enter Name: Paul { Enter Age: 3 int age. system("pause"). 42 feet feet = 6 * fathoms. Hello Paul. name. which was made famous in a poem by Henry Wadsworth Longfellow. Write a program in which the user is prompted to input his/her initials followed by the age. system(“pause”). age + 1). middle. printf(“\nGreetings %c.%c.scanf(“%d”. Next year your age will be 26 printf(“Input your three initials and your age: ”). &B). last. Prod). Prod = A * B. first. Sum). printf(“\nProduct of two numbers: %d”. &last.p.h> main( ) { char first. last. &first. Output Input your three initials and your age: Greetings f. #include <stdio. Sum = A + B.%c. getch( ).a. int age. printf(“\nSum of two numbers: %d”. } 5. &age). scanf(“%c%c%c%d”. &middle. } . %s %d.\n”. middle. “Next year your age will be”. 10. where R is the radius. 4. 2. Recall that the formula to compute for the area is AREA = Pi x R2. The output must be similar to the one below. 9. Hint: 1000 m2 = 1 ha 3. Make a program the will accept a number in square meters (m 2) and display its equivalent measure in hectares (has). 5. 8.) 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. 7. Make a program that will convert an inputted number in inches (in. Write a program that asks the user to enter the radius of a circle and then computes for its area. Create a program that will compute and display the area of a square. The area of the circle with radius 2 cm is 12. Create a program that asks for a distance in kilometers and converts it into its metric equivalent. Write a program that inputs two real numbers then exchanges their values. Recall that the formula to compute the AREA = S2 where S is the side of the square. Create a program that converts a Fahrenheit measure to a Celsius measure (C = 5/9 x (F–32)).56 cm2. 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.PROGRAMMING EXERCISES 1. Create a program that will input a number in kilowatt and display its equivalent measure in watts. 6. Compute and display the area of the rectangle. . The general form of the if statement with block of statements is: if (expression) { statement_sequence. if the expression evaluates to TRUE (1). the program will ignore the statement or the block of statements. the statement or the block of statements that forms the target of the if statement will be executed.1 The IF statement The general form of the if statement is: if (expression) statement. } In an if statement. Note: Never place a semicolon after the expression in an If statement.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. 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. Otherwise. In C the following are the types of conditional statements: 3. main( ) { Output Enter student grade: 95 Congratulations you PASSED! printf(“Enter student grade:”). else statement_2.h> int grade. if(price > 1000) { discount = price * 0. &price). if (grade >= 60) printf(“Congratulations you PASSED!”).2f”. } Example 2. getch( ). #include<stdio. } getch( ). #include<stdio. Write a program that will output “Congratulations you PASSED!” if the student’s grade is greater than or equal to 60. discount). printf(“Discount is %. compute a 10% discount from the original price.Example 1. discount. Enter value for price: 2000 main( ) Discount is 200. scanf(“%f”. Display the computed discount. Write a program that will ask for a price.h> Output float price.00 { printf(“Enter value for price:”). where: . scanf(“%d”. If the price is greater than 1000.2 The IF-ELSE statement The general form of the if-else statement is: if (expression) statement_1.10. } 3. &grade). 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 statement or block of statements in the else statement will be executed. else printf(“Sorry you FAILED!”). } else { statement_sequence. The general form of the if-else statement with block of statements is: if (expression) { statement_sequence. otherwise. scanf(“%d”. Otherwise output. “Sorry you FAILED!” Output Enter student grade: 50 Sorry you FAILED! #include<stdio. if the expression is TRUE (1). &grade). } In an if-else statement. main( ) { printf(“Enter student grade:”). the statement or block of statements after the if statement will be executed. never both. Write a program that will output “Congratulations you PASSED!” if the student’s grade is greater than or equal to 60. Example 3. getch( ). if (grade >= 60) printf(“Congratulations you PASSED!”). } . NOTE: Only the code associated with the if or the code that is associated with the else executes.h> int grade. if … … . The reason that nested ifs are so confusing is that it can be difficult to know what else associates with what if. 1.3 The NESTED-IF statement One of the most confusing aspects of the if statement in any programming language is nested ifs. 3. B and C and determine which is the largest. C provides a very simple rule for resolving this type of situation. 1. Example 4. 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.3. { 3. } 5. 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. Write a program that reads in three numbers A. A nested if is an if statement that is the object of either an if or else. 4. In C. else Notice that there is a pair of braces found in number 2 and number 4. if … 2. This is sometimes referred to as “an if within an if”. Fortunately. 2. 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. if … … if … … … else Situation 2 The else in number 5 is paired with the if in number 1. Therefore. This makes the if statement in number 1 the nearest if statement to the else statement in number 5. The general form of the if-else-if ladder statement is: if (expression_1) statement_1.4 The IF-ELSE-IF Ladder A common programming construct in C is the if-else-if ladder. else if (expression_3) statement_3.\n”).\n”). else if (expression_2) statement_2.#include<stdio. if (A > B) if (A > C) printf(“A is the largest. B. else printf(“C is the largest. scanf(“%d%d%d”.\n”). Enter three numbers: 7 11 5 main( ) B is the largest. C.h> Output int A. &A.\n”). } 3. else if (B > C) printf(“B is the largest. : : else statement_else. { printf(“Enter three numbers:”). &B. getch( ). where: if and else are reserve words in C expression_1. &C). expression_2 up to expression_n is relational or boolean expression that evaluates to a TRUE (1) or FALSE (0) value . else printf(“C is the largest. If all other conditions are false. Example 5. the final else is executed. else printf(“Day is not available!”). As soon as a true condition is found. In an if-else-if ladder statement. if (day = = 1) printf(“Sunday”). you may include this part if needed in the program or you may not include if not needed. The final else acts as a default condition. &day). else if (day = = 4) printf(“Wednesday”). If none of the condition is true. } 3. printf(“Enter an integer:”). output “Day is not available!” #include<stdio. the expressions are evaluated from the top downward. else if (day = = 6) printf(“Friday”). statement_2 up to statement_else may either be a single C statement or a block of C statements. else if (day = = 2) printf(“Monday”). Enter an integer: 4 Wednesday . the statement associated with it is executed. If the inputted number is not within 1-7. and the rest of the ladder will not be executed. Write a program that will ask the user to input an integer then output the equivalent day of the week. 1 is Sunday. else if (day = = 5) printf(“Thursday”). the last else statement is performed. If the final else is not present.h> Output main( ) Enter an integer: 4 { Wednesday int day. else if (day = = 7) printf(“Saturday”). scanf(“%d”. then no action takes place. 2 is Monday and so on. Note: The final else is optional.statement_1. getch( ).5 The SWITCH Statement The switch statement is a multiple-branch decision statement. else if (day = = 3) printf(“Tuesday”). you should jump to the end of the switch statement terminated by the symbol }. case constant2: statement sequence_2. 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. a variable is successively tested against a list of integer or character constants. NOTE: The break statement is used to terminate the statement sequence associated with each case constant. they are automatically converted to their integer values. . The default part of the switch is executed if no matches are found. No two case constants in the same switch can have identical values.The general form of the switch statement is: switch (variable) { case constant1: statement sequence_1. break. : : default: statement_sequence_default. If character constants are used in the switch. It is a C keyword which means that at that point of execution. a switch statement enclosed by an outer switch may have case constants that are the same. 3. If a match is found. } In a switch statement. a statement or block of statements is executed. Of course. 2. break. Rewrite the program in Example 5 using a switch statement. } case constant2: statement sequence.5. break. &day). printf(“Enter an integer:”). } Example 6. break. #include<stdio. scanf(“%d”.h> main( ) { int day. case 2: Output Enter an integer: 11 Day is not available! .1 Nested Switch Statement The general form of the nested switch statement is: switch (variable) { case constant1: { switch (variable) { case constant1: statement sequence. break. : : default: statement sequence. break. } break. switch (day) { case 1: printf(“Sunday”). case constant2: statement sequence.3. &num1). printf(“Enter a character for the operation:”). S – Subtraction printf(“Enter number 1:”). If the user inputs ‘A’ for the character. D – Division printf(“Enter number 2:”).h> Output main( ) Enter number 1: 10 { Enter number 2: 25 int num1. case 6: printf(“Friday”). The answer is: 35 printf(“A – Addition \n”). ans. A – Addition char operation. #include<stdio. case 5: printf(“Thursday”). &operation). Enter a character for the operation: A scanf(“%d”. default: printf(“Day is not available!”). num2. Write a program that will ask the user to input 2 integers and a character (A. break. case 7: printf(“Saturday”). break. M – Multiplication scanf(“%d”. if ‘S’ subtract the 2 numbers. printf(“M – Multiplication \n”). S. switch (operation) { case ‘A’: . printf(“S – Subtraction \n”). M or D). break. and if ‘D’ divide the numbers. } getch( ). case 4: printf(“Wednesday”). case 3: printf(“Tuesday”).printf(“Monday”). scanf(“%c”. break. add the 2 numbers. Output the computed value. printf(“D – Division \n”). if ‘M’ multiply. } Example 7. break. break. &num2). case ‘S’ : ans = num1 . break. case ‘D’: ans = num1 / num2.num2. break. break. } . } printf(“The answer is: %d”.ans = num1 + num2. getch( ). break. case ‘M’: ans = num1 * num2. ans). Write a program to determine the equivalent grade of each student in a class as follows: a. XYZ Company gives year-end bonus to its employees based on their number of years of service and their salary. 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. 8. Write a program that asks the user for the hours worked for the week and the hourly rate. ask for the measures of the base and height and compute for the area. Read in the student’s name. of hours > 35 and <=40 Bonus of 150 pesos Display the basic salary. and final exam ratings. Assume that there are no duplicate values. Assume that there are no duplicate values. 3. “I’TS HOT!” if the temperature is greater than 30. Write a program that finds the smallest among the five integers inputted by the user. If the area is wanted. Write a program that accepts three numbers from the user and displays the values from highest to lowest. Passing is 75%. minor exam. Write a program that accepts five numbers from the user and displays the highest and the lowest number. average of 3 short quizzes and the grade of the student. If the perimeter is wanted. bonus and the total salary (basic salary + bonus) for the week. Write a program segment that will ask the user if he wants to compute the perimeter of the area of a triangle. 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. ask the measure of the three sides and compute for the perimeter. Write a program that will display “I’TS COLD!” if the temperature is less than 20. 11. Assume that there are no duplicate values. “COOL CLIMATE!” otherwise. 10. Display the computed value. Write a program that accepts three numbers from the user and displays the highest and the lowest number. 9. 7. 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. 4. . The basic salary is computed as: Salary = hours worked * hourly rate Bonuses are given: No. Display also a message whether the student passed or failed. of hours > 40 and <=45 Bonus of 250 pesos No. a discount of 50 pesos if the shirt bought is L and the price is greater than 400. 6. 2. midterm grade. of hours > 45 Bonus of 500 pesos No.PROGRAMMING EXERCISES 1. 75 80 – 82 = 2. Sample Run: Enter month: 10 Enter day: 23 Enter year: 2000 October 23.75 92 – 94 = 3.b.25 60 – 63 = 1. 2000 . Determine the equivalent grade for the numerical value obtained by the following grade marks: 98 – 100 = 4.50 89 – 91 = 3.00 83 – 85 = 2.30 midterm grade + 0.60 of final exam c.00 below 60= 0.00 95 – 97 = 3.25 74 – 76 = 2.75 68 – 70 = 1.00 71 – 73 = 1. Determine the final grade of the student by the formula: Final grade = 0.25 86 – 88 = 3.10 minor exam + 0.00 Write a program that will read a date (month. day and year) in integer form and display the date in standard format.50 77 – 79 = 2.50 64 – 67 = 1. 12. The for loop contains a counter whose values determine the number of times the loop iterates. program execution resumes on the statement following the for loop. } 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).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.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. increment) { statement_sequence. or open-ended as in while and do-while. 4. The general form of the for statement is: for (initialization. Once FALSE (0). condition. . The iteration stops upon reaching the number of times specified in the loop. Example 2. Since the result of the condition is TRUE (1). getch( ). the value of x will be printed. the control of the program transfer to the condition to check whether the value of x is less than or equal to 10. #include<stdio. sum. x <= 10. After the initialization part. The control of the program transfers again to the condition part to determine if the result is TRUE (1) or FALSE (0). The process continues until the condition part evaluates to FALSE (0). Since condition is TRUE (1) the value of x will again be printed then the increment part will perform again. x + +) printf(“%d\n”. 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. for(x = 1. Write a program that will get the sum of all integers from 1 to 10. #include<stdio. } Output 1 2 3 4 5 6 7 8 9 10 In example 1. } . sum). x). x <= 10.h> int x. the increment part will be performed making the value of x equal to 2. main( ) { for(x = 1. getch( ). This is a logical error.h> Output int x. the counter of the for loop is x with the initial value of 1. c) The increment part of the for loop is execute after the first iteration of the loop. Example 1. The sum of 1 to 10 is 55 main( ) { sum = 0.NOTE: a) Never place a semi-colon right after the for header. printf(“The sum of 1 to 10 is %d\n”. x + +) sum = sum + x. Write a program that will print the numbers 1 to 10 using a for statement. After the first iteration of the loop. getch( ).2 The WHILE statement The while statement or while loop is an open-ended or event-controlled loop.4. The general form of the do-while statement is: Output 1 2 3 4 5 6 7 8 9 10 do { statement_sequence. while (x <= 10) { printf(“%d\n”. } 4. The general form of the while statement is: while (condition) { statement_sequence. the program control passes to the line after the loop code. main( ) { x = 1. } 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. When it becomes FALSE (0). The while loop iterates while the condition is TRUE (1). #include<stdio.h> int x. x). x + +. } while (condition) . Write a program that will print the numbers 1 to 10 using while statement.3 The DO-WHILE statement The second type of open-ended or event-controlled loop is the do-while statement or do-while loop. h> Output int x. In the do-while loop.00.50 float average. x = 1. The computed average is 5. Write a program that will get the average of all integers from 1 to 10 using do-while loop. but when FALSE (0). sum. #include<stdio. getch( ). Example 4. when the condition evaluates to TRUE (1).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. do { sum = sum + x. } while (x <= 10) average = sum / 10. average). main( ) { sum = 0. printf(“The computed average is %.2f\n”. x + +. } . This means that a do-while loop “always executes at least once”. program control proceeds to the next instruction after the do-while loop. the loop body will be executed. 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 n and display all the numbers from 1 to n on a single line. 6. Example: if n = 4. Example: if n = 4. 3 . 2.PROGRAMMING EXERCISES 1. the first 5 even numbers are 2. given the value of n. Write a program that will ask the user to enter a number and display all the factor of the number. given the value of n. 8 and 10. Example: if n = 5. . output * ** *** **** Write a program that will display the following pattern. Write a program that will compute for n! (n factorial) which is the product of all numbers form 1 to n. 12. given the value of n. given the value of n. Example: if n = 4. 5 . 7. 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. 4. Example: if n = 5. 6. 5. 3. 9. output 4321 321 10. output **** *** ** * Write a program that will display the following pattern. 8. 4. 7 and 9. output * ** *** **** Write a program that will display the following pattern. Write a program that will display the following pattern. Write a program that asks the user to enter a number n and display the first n even numbers. Example: if n = 4. Example: if n = 4. 11. Write a program that asks the user to enter a number n and display the first n odd numbers. the first 5 odd numbers are 1. 13. Write a program that will ask the user to enter a number n and display the sum of all numbers from 1 to n. given the value of n. output **** *** ** * Write a program that will display the following pattern. . Example: if n = 4. given the value of n. Example: if n = 5 and m = 6. Example: if n = 4 and m = 3. Example: if n = 5. output * *** ***** ****** ******** Write a program that will display the following pattern. output ***** * * * * * * * * ***** Write a program that will display the following pattern. output 1234 123 12 1 Write a program that will display the following pattern. given the value of n and m. 21 1 Write a program that will display the following pattern. Example: if n = 5. given the value of n and m. output ******** ******* ***** *** * 18. given the value of n. given the value of n. output **** **** **** Write a program that will display the following pattern. 15.14. 17. 16. . getch( ). Execution of the program begins with main( ) and also ends with the main( ) function. However. } greet1( ) { printf(“Hello!”). greet2( ). } greet2( ) { printf(“How are you?”). NOTE: The main( ) function should always be present in every C program. that is the main( ) function.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.h> main( ) { printf(“Hi!”). greet1( ). Write a program that will print the lines “Hi! Hello! How are you?” using several functions aside from the main function. Therefore we can say that we can create a program that is composed of other functions aside from the main function. Consider the program below: Example 1. Output Hi! Hello! How are you? #include<stdio. } The C program presented in example 1 is composed of 3 functions: the main function. the function greet1 and the function greet2. a C program can also be composed of other functions aside from main(). this time calling the function greet2( ). printing Hi! on the screen.5. Other functions aside from the main( ) can only be executed by the program through a function call. Therefore the control of the program transfers to the greet1( ) function executing the printf( ) statement of greet1( ). The next step is to go back to main( ).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. the execution of the program starts with the main( ) function. . Therefore. NOTE: Function call is a C statement that is used to call a function to execute C statements found inside the function body. A function is also called a subprogram or subroutine. It is a part of a C program that performs a task. 5. function_name is any valid identifier name which will name the function. Going back to example 1. After the clrscr( ) statement the first printf( ) statement will be performed. The next statement greet1( ). is an example of a function call. The control of the program again transfers to the main( ) function. The statement greet2( ).1 Functions Functions are the building blocks of C in which all program activity occurs. “How are you?” will be printed on the screen. calling the function greet1( ). is also a function call. operation or computation then may return a value to the calling part of the program. Hello! will be printed. then terminate the program after the getch( ) statement. In effect. } Example 3 is void function.3 Types of functions C functions are classified into two: 1. printf (“* *“). Notice that the function does not contain a return statement for the function to return a value. Example 3 shape ( ) { printf (“* * * * *”). int y) { int z.parameter list is a comma separated list of variables that receive the values when the function is called. which does not return any value when invoked. These three statements will be executed once the function subtractor is called through a function call. body of the function is composed of valid C statements that the function will execute. Example 2 int subtractor (int x. It is expected that x and y will receive values once the function is called. printf (“* * * * *”). . Void Functions. which means this function will return an integer of whole number value. z = x-y return (z) } Example 2 illustrates a sample of user-defined function. an assignment statement and a return statement. 2. The body of the function inside {} is composed of a local variable declaration for the variable z. Function that returns a value once invoked. printf (“* *“). 5. In the example above int is the function type. The name of the function is subtractor. The variables x and y are the two variables that make up the parameter list. 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.Example 4 int area { int A. area = Compute (x. a = L * W. int W) { int a. 5. x=25.h> main ( ) { int x. return (A). Formal parameters are the variables found in the function header that will receive values from the actual parameters. return a. area) } Compute (int L. Example 5 #include<stdio. y=10. } /*x and y are Actual parameters*/ /*L and W are Formal parameters*/ . printf (“%d”. A = L * W. this means that whatever is the computed value of A inside the body of the function will be returned after the function’s execution. } The function above is an example of a function that will return a value once invoked. y. area.y). Notice that the function contains a return a statement for the variable A. the actual parameters also pass their value to the formal parameters. } . printf(“%d%d/n”. b=b *2. This is because the actual address of the variables is passed using the address of operator (&) together with the pointer operator (*). printf (“%d %d/n”. the changes that happen to the values of the formal parameters inside the function will affect the values of the actual parameters. y .x. x=10. They will receive the values passed by the variables x and y. pass (x.x. 5. These variables will pass their values to the formal parameters of the function Compute ( ). the variables x and y are the actual parameters.In example 5.h> main ( ) { int x.b). the values of the actual parameters are passed to the formal parameters. But this time. y=5. the variables L and W are the formal parameters. On the other hand.y).y).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.a. In pass by value or call by reference. Example 6 #include<stdio. getch( ). In the method call by value. } pass (int a. Changes that happen to the values of the formal parameters inside the function will not affect the values of the actual parameters. int b) { a=a+5.y) printf(“%d%d/n”. Inside the function pass. The printf( ) statement inside the pass( ) will then print 15 10. Example 7 #include<stdio. Now. The first printf( ) statement displays the values of the variables x and y printing 10 5 on the screen. the values of a and change to 15 and 10.y). } SAMPLE OUTPUT: 10 5 15 10 15 10 .x.y) printf(“%d%d\n”. respectively. pass (x. The formal parameters a and b accept the values form x and y. the values of x and y remain unchanged. y=5.y). *b=*b *2. when control of the program transfers to the main( ) function.x. printf(“%d%d\n”.h> main ( ) { int x. y . *a. printf (“%d %d\n”. int b) { *a=*a+5. } pass (int a. getch( ). x=10. after executing the function pass( ). The program then calls the function pass. Therefore the old values of x and y of 10 and 5 will be printed by the last printf( ) statement. This is because the method that we use is call by value. *b).SAMPLE OUTPUT: 10 5 15 10 10 5 Example 6 illustrates call by value. the changes that happen to the formal parameters a and b will also take effect to the values of x and y. C also has built-in functions. The following table summarizes some commonly used built-in functions in C under math. The only difference will be on the values that will be printed on the last printf( ) statement.3) = 8 raised to the yth power *Note: x and y are variables . Notice the use of the address operator (&) in the actual parameters of the function call. Table 10.0 sine of a number cos(x) Calculates the trigonometric cos(0.y) Calculates the value of x pow(2.h) Function Name Use Example sqrt(x) Calculates the square root sqrt(9. Therefore.00) = 3.0) = 1.00) = 11. which were discussed earlier in this chapter. Built-in functions are predefined functions.The method pass by value or call by reference is illustrated in example 1. These functions are already defined in C so there is no need to redefine them because they are ready to use.0 cosine of a number tan(x) Calculates the trigonometric tan(0. once the control of the program transfers to main( ) after executing the body of the function pass( ). Since we use pass by the value. 5. and the pointer operator (*) in the formal parameters of the function heading of pass.00) = 11.00 ceil(x) Rounds a number to the ceil(11.0) = 0.00 of a number fabs(x) Calculates the absolute fabs(11. which can be used by the programmer to perform certain commands or tasks in the program. the values now of x and y are 15 and 10.00 value of a number fabs(-11.25) = 12 smallest integer which is not less than the original number floor(x) Rounds a number to the floor(11.1 Commonly Used Built-in Functions in C (math.6 C’s Built-in Functions Aside from user-defined functions. The execution of the program is just similar to that example of 6.25) = 11 largest integer which is not greater than the original number sin(x) Calculates the trigonometric sin(0.0 tangent of a number pow(x. respectively.0) = 0.h. 4. Write a program containing a function that will compute and display the combination of m taken n where: C(n. 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. 7. for displaying the result. 6. 10. Write a program containing a function that will return the largest of 3 floatingpoint numbers. if the number is 12345. 3. 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 that will illustrate the use of a function for computing the square of a number. 2. 8. which is the product of all numbers from 1 to n. .PROGRAMMING EXERCISES 1. 5. “C! – Poor” otherwise. “B! – Good” if grade is less than 90 and greater than or equal to 75. Write a program containing a function that will return the smallest of 3 floatingpoint numbers. For example. Write a program containing a function that returns the Greatest Common Divisor (GDC) of two integers.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. 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 takes a 5-digit integer and returns the number with its digit reversed. There must be three other functions aside from main( ). the function should return 54321. 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. the second for computation of squares and the third. The first function must be responsible for inputting the data. } The program segment in Example 1 illustrates a function containing a call to itself. 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. else return(n*factorial(n-1)). contains the function call for the factorial function.1 Recursion In C. factorial(int n) { if(n == 1|| n == 0) return1. the repetitive process by which a function calls itself is called recursion or circular definition. This contains the condition that should be satisfied at one point of execution to terminate the repetitive process done by the recursive function. we have seen that a user-defined function in C can call other functions through a function call. General Case – this is part of the recursive function that is found on the else-clause.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. Consider the program segment below: Example 1. A function is said to be recursive if a statement in the body of the function calls the function that contains it. a function in a C program can also call itself. This is a way of defining something in terms of itself. b) . But aside from calling other functions. The line else return(n*factorial(n-1)). This contains the function call of the recursive function to itself. 6. . #include<stdio. Give the output of the following program when the value entered for a=5. factorial( ) will be called with n-1 as the argument.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). 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. printf(“The new value is %d”. } solve(int a) { if(a == 1) return 2. b. This process will be repeated until such time that the condition in the if-clause is satisfied. printf(“Enter a value:”). when the value of n becomes 1 or 0. otherwise it returns the product of n*factorial(n-1). If the factorial function in Example 1 is called with an argument of 1 or 0. the final return value when n=4 is 24. Example 2. b = solve(a). This is shown in Example 1. To evaluate this expression.h> main( ) { int a. getch( ). 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). the function returns 1. b). scanf(“%d”. that is. printf(“Enter a value:”). b. } 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. } . } solve(int a) { if(a == 1) return 1.else return (solve(a-1) + 2). printf(“The new value is %d”. Example 3. else return (solve(a-1) + 2). getch( ). scanf(“%d”.h> main( ) { int a. Give the output of the following program when the value entered for a=4. the final return value when a=5 is 10. &a). b). b = solve(a). #include<stdio. another function will be defined to make the recursive call.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. recursive functions can also be called indirectly. &a). However.2 Indirect Recursion The examples presented on the earlier part of this chapter are examples of direct recursions. printf(“Enter a value:”).h> main( ) { int a. Direct recursions are recursive functions that call itself through a function call directly inside the body of the function. 6. . That is. printf(“The new value is %d”. b = solve(a). #include<stdio. Give the output of the following program when the value entered for a = 5. This is called indirect recursion. b). b. the final return value when a=4 is 7. scanf(“%d”. Consider the example below: Example 4. b). } } solve2(int a) { int b. Notice that the functions solve() and solve2() call each other. b). . This is an indirect way of having recursive definition. return b. if (a == 1) { b = 2. printf(“%d”. return b. printf(“%d”. } } SAMPLE OUTPUT: Enter a value: 5 2 4 6 8 10 Example 4 presents a C program containing indirect recursions. printf(“%d”. } else { b = solve (a-1) + 2. b). } else { b = solve2 (a-1) + 2. } solve(int a) { int b. b). return b. printf(“%d”.getch( ). if (a == 1) { b = 2. return b. . solve() and solve2() will alternately call each other until condition in their if-clause is satisfied. when a = 5 the values 2 4 6 8 10 will be printed on screen.Assuming that that value entered for the variable a in the main() function is 5. 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. The function solve() will be first called passing 5 as the parameter. when either solve() or solve2() will be called with the value one (1) as the passed parameter to a. That is. 1. 3. 5. 7 … given the value of n from 1 to positive infinity. . The Greatest Common Divisor (GCD) of two numbers is the largest integer that evenly divides the two numbers. 13. given the value for n. 1. find 23 = 2 * 2 * 2 = 8) Write a program containing the recursive function that will find the following series of numbers 2. (Example: if n=4 and m=3. Write a program containing a recursive function that computes and displays the nth Fibonacci number. 2. 5. 1.PROGRAMMING EXERCISES 1. 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 C program containing a recursive function that will raise a certain integer x to a certain positive integer n. 6. 5. 2. 4/3 = 1. 8. 3. Output 1) The Fibonacci series: 0. Write a C program containing a recursive function that will get the whole number quotient result of dividing two integers n and m. 4. 3. (Example: if x=2 and n=3. 4. 8. Write a program containing a recursive function that returns the GCD of two numbers. 25 5 7 Array1 Therefore the five elements in our array Array1 are the following: Array1[0]. the second element with a value of 5 has an index of 1. In our array example.2 Referencing Array Elements To reference individual elements of an array.1 Arrays An array is a collection of variables of the same data type that is referenced by a common name. 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. For arrays in C. Each of these values is called an array element. Array1[3]. Array1[4]. Notice that Array1 contains five whole number values. Array1[1]. Array1[2]. we have to specify the array name and the position number of element (subscript or index) that is enclosed in pair of square bracket [ ]. the first array element with a value of 25 has an index of 0. 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.LESSON 7: SINGLE-DIMENSIONAL ARRAYS Objectives • To learn about using arrays in programming • To apply arrays in programming 7. Consider the illustration below for the array Array1: 25 5 7 Array1 In the illustration above. The values of these elements are: 11 163 11 163 . The specific element in an array is accessed by a position number called an index or subscript. the name of the array is Array1. the third element with a value of 7 has an index of 2. The data type int is followed by the array name. . In the declaration above. Example 1. float A[10].3 Array Declaration = = = = = 25 5 7 11 163 Like ordinary variables. The size of 5 is enclosed in the pair of square brackets [ ] indicates that Array1 is capable of storing 5 integer values. the data type is int since Array1 holds whole number values.Array1[0] Array1[1] Array1[2] Array1[3] Array1[4] 7. which is Array1. The general form for an array declaration is as follows: type array_name[size]. the correct declaration for the array Array1 will be: int Array1[5]. This declaration declares that arrayA is capable of storing 10 floating-point numbers. Declare a ten-element floating-point array A. 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. arrays must be declared before they are used in a C program. we can have the following declarations: int number[100]. we say that: result[0] result[1] result[2] result[3] = = = = 87 85 76 90 We should remember the following things regarding array initialization: . In the declaration. 85. 163}. 7. 11 and 163. 163} is called the initializer list. The two declarations for arrays number and answer can be combined into a single declaration: int number[100]. Provide the declaration for the integer-array result with the following intial values: 87. 5. The initializer list provides the initial values for the array. int Array1[5] = {25. 76. Both are integer-arrays. 7. Consider the example below: Example 3. Example 4. 5. {25. This is called array initialization. 11. 90}. 76 and 90. 5.4 Array Initialization Arrays in C can be given initial values during the declaration. Each of the arrays should be separated by comma in the declaration. Provide the declaration for arrays number with a size of 100 and array answer with a size of 25. In the declaration for the array result. 85. int result[4] = {87. int answer[25]. NOTE: You can declare more than one array in a single declaration provided that the arrays are of the same data type.Example 2. Provide the declaration for the integer-array Array1 with the following initial values: 25. 7. The comma-separated list of values are enclosed in pairs of curly bracket { }. To answer the second example. answer[25]. 11. 7. 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. the declaration above is wrong because there are four initializers in the initializer list while the size of the array is only three. 67}.1. Based from the declaration. If there are fewer intializers than the size of the array. the number of elements in the array will be the number of elements in the initializer list. Example 5. 89. An initializer list that is greater than the array size is a syntax error. int exam[ ] = {88. the remaining elements are initialized to zero. int g[3] = {5. -3. 3. If the array size is omitted from a declaration with an initializer list. Therefore. Example 6. 16. 90. 78}. Example 7. 60. 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 . 26}. int n[10] = {5. 5} #include<stdio. 0. x++) printf(“Element %d is %d”. x++) sum += a[x]. 0. 2. 5. printf(“The sum is %d”. n[x]). x. } SAMPLE OUTPUT: The sum is 39 . sum = 0. 1. 4. sum). 25}. 20. 7.h> main( ) { int n[5] = {5. 15}. Write a C program that will compute and display the sum of the following array: int a[5] = {2. getch( ). 15. for (x = 0. 10. x <= 9. getch( ). x <= 4. 20. } SAMPLE OUTPUT: Element 0 is 5 Element 1 is 10 Element 2 is 15 Element 3 is 20 Element 4 is 25 Example 9. 5.Example 8.h> main( ) { int a[5] = {2. 7. 2. 1. 25]. 10. 3. 4. #include<stdio. for (x = 0. Write a C program that will print the values of the following array: int n[5] = {5. int x. int x. 15. 3. 10. sum. 10. . 4. 7. Write a program that will arrange the elements of a 10-integer array in ascending order. Write a program that will search for the largest value in an array of integers of length 10. 5. Display also the sum of the values found. 3. Write a program that will arrange the elements of a 10-integer array in descending order. Write a program that will search for the smallest value in an array of integers of length 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. 8.PROGRAMMING EXERCISES 1. Write a program that will compute and display the average of a 20-element array whose values are inputted by the user. Write a program that will output all the even numbers found in an array of 20 integers. 9. 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. 6. Write a program that will print the odd positioned elements in an array of 10 integers. Write a program that will print the even positioned elements in an array of 10 integers. 10. 2. Documents Similar To ES03 Lab ManualSkip carouselcarousel previouscarousel nextBE_Syllabus.pdfPSC Lecture NotesCompile-time stack requirements analysis with GCCMCQ Basics of CAs IEC 61131.8-2004 Programmable Controllers Guidelines for the Application and Implementation of ProgrammingC2Erefsu08 Oct Essentialofitcsl0102-0201ADSOScientific Computing With Python_Advanced Topics.pptDoc 42055ES03 Lab ManualWallIncompletion 2014 new CCP syllabusM39 DumpAlll Tables in MMFortran 95 Answers of ExercisesAdvanced_BASIC_and_Machine_Code_for_the_Commodore_64.pdfCleanroom Software Engineering-RawAPPLICA1slaa290C++ Function Templates Are Those Functions Which Can Handle DifferentFanuc FA System for PC OperatorScott_314Subsequent Function Requirementsromanowicz 1997 TOPMODEL in MATLAB.pdfC Language 3Day1-ABAP BW Handbook08 r05310505 Principles of Programming LangaugesBlg252e CompleteMore From HanzhellJ.CampuganSkip carouselcarousel previouscarousel nextCe 41 Soil Mechanics - Experiment 1 - A Basel ConventionCe 41 Soil Mechanics - Experiment 1 - B 01 CE225 Multi-Degree of Freedom SystemsMatthew 17Building Design 2_lecture 2HelloHe He Heheheh HeAng Sigwa (Sabayang Pagbigkas 2012)Solid Waste Management Act of 2000 RA 9003DATA CE 31Best Books About Control FlowC++ MCQs: Multiple Choice Questions and Answers (Quiz & Tests with Answer Keys)by Arshad IqbalProgramming with MATLAB: Taken From the Book "MATLAB for Beginners: A Gentle Approach"by Peter KattanLearning C# by Developing Games with Unity 5.x - Second Editionby Greg LukosekPROGRAMMING For BEGINNERSby iCodeAcademyAssembly Language:Simple, Short, And Straightforward Way Of Learning Assembly Programmingby Sherwyn AllibangCommon LISP: The Languageby Guy SteeleFooter MenuBack To TopAboutAbout ScribdPressOur blogJoin our team!Contact UsJoin todayInvite FriendsGiftsLegalTermsPrivacyCopyrightSupportHelp / FAQAccessibilityPurchase helpAdChoicesPublishersSocial MediaCopyright © 2018 Scribd Inc. .Browse Books.Site Directory.Site Language: English中文EspañolالعربيةPortuguês日本語DeutschFrançaisTurkceРусский языкTiếng việtJęzyk polskiBahasa indonesiaSign up to vote on this titleUsefulNot usefulMaster Your Semester with Scribd & The New York TimesSpecial offer for students: Only $4.99/month.Master Your Semester with a Special Offer from Scribd & The New York TimesRead Free for 30 DaysCancel anytime.Read Free for 30 DaysYou're Reading a Free PreviewDownloadClose DialogAre you sure?This action might not be possible to undo. Are you sure you want to continue?CANCELOK
Copyright © 2024 DOKUMEN.SITE Inc.