Loop Controls, Decision Making, Functions, and Data Array Processing

Similar documents
ECET 264 C Programming Language with Applications. C Program Control

ECET 264 C Programming Language with Applications

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction

ECET 264 C Programming Language with Applications

ECET 264 C Programming Language with Applications

Functions. Systems Programming Concepts

Function. specific, well-defined task. whenever it is called or invoked. A function to add two numbers A function to find the largest of n numbers

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

C Programs: Simple Statements and Expressions

Functions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa

Introduction to C Language

C Functions. 5.2 Program Modules in C

Programming in C Quick Start! Biostatistics 615 Lecture 4

Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

ANSI C Programming Simple Programs

CSE123. Program Design and Modular Programming Functions 1-1

Fundamentals of Programming

Fundamental of Programming (C)

Calling Prewritten Functions in C

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

Preview from Notesale.co.uk Page 2 of 79

بسم اهلل الرمحن الرحيم

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

C++ Programming: From Problem Analysis to Program Design, Third Edition

Structured Programming. Dr. Mohamed Khedr Lecture 4

Assoc. Prof. Dr. Tansu FİLİK

LESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long

sends the formatted data to the standard output stream (stdout) int printf ( format_string, argument_1, argument_2,... ) ;

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

IECD Institute for Entrepreneurship and Career Development Bharathidasan University, Tiruchirappalli 23.

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

Computer Science & Engineering 150A Problem Solving Using Computers

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

Chapter 2. Outline. Simple C++ Programs

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

Lecture 2:- Functions. Introduction

Fundamental of Programming (C)

Primitive Data Types: Intro

Chapter 3 - Functions

1001ICT Introduction To Programming Lecture Notes

C Input/Output. Before we discuss I/O in C, let's review how C++ I/O works. int i; double x;

UNIT- 3 Introduction to C++

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

Standard I/O in C and C++

Fundamentals of Computer Programming Using C

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 5. Playing with Data Modifiers and Math Functions Getting Controls

Computers Programming Course 7. Iulian Năstac

Chapter 3. Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus. Existing Information.

Computers Programming Course 5. Iulian Năstac

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Fundamentals of Programming & Procedural Programming

C Programming

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming.

Reserved Words and Identifiers

Built-in Types of Data

A function is a named group of statements developed to solve a sub-problem and returns a value to other functions when it is called.

Lecture 4. Console input/output operations. 1. I/O functions for characters 2. I/O functions for strings 3. I/O operations with data formatting

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered ) FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

INTRODUCTION TO C++ C FORMATTED INPUT/OUTPUT. Dept. of Electronic Engineering, NCHU. Original slides are from

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

n Group of statements that are executed repeatedly while some condition remains true

Course Outline Introduction to C-Programming

THE FUNDAMENTAL DATA TYPES

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Engineering Problem Solving with C++, Etter/Ingber

Outline. Computer Programming. Preprocessing in C. File inclusion. Preprocessing in C

Lecture 04 FUNCTIONS AND ARRAYS

Multiple Choice Questions ( 1 mark)

Lecture 9 - C Functions

Chapter 7. Basic Types

The C Programming Language Part 2. (with material from Dr. Bin Ren, William & Mary Computer Science)

Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

Lecture 14. Daily Puzzle. Math in C. Rearrange the letters of eleven plus two to make this mathematical statement true. Eleven plus two =?

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

Data types, variables, constants

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

UNIT-I Input/ Output functions and other library functions

2. Numbers In, Numbers Out

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

Fundamentals of Programming Session 8

The cin Object. cout << "Enter the length and the width of the rectangle? "; cin >> length >> width;

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

9 C Language Function Block

C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

Standard Library Functions Outline

Pointers cause EVERYBODY problems at some time or another. char x[10] or char y[8][10] or char z[9][9][9] etc.

Transcription:

3 Loop Controls, Decision Making, Functions, and Data Array Processing 3-1 Standard Input and Output 3-1 3-2 Standard Mathematics and Utility Functions 3-5 3-3 Flow of Control 3-10 3-4 Decision Making 3-16 3-5 Multiple Decision Making 3-23 3-6 Data Array Processing 3-26 3-7 Programming Applications 3-35 - Arithmetic mean of N numbers - Factorials - Calculating sine function using series - A calculator for hex to decimal conversion

Lin/ August 2008 3-1 3-1 Standard Input and Output Functions To ensure the portability of the C language, the input and output routines, math functions, etc that we found in other languages are not parts of the language, but rather they can be found in a set of standard libraries. The names of text-based devices for interacting with user are: stdin (standard input device, or keyboard input device), stdout (standard output device, namely the monitot screen), and stderr (standard error device, same device as the monitor screen) Writting to the Screen and Reading from Keyboard Devices getchar() /* Get a char from keyboard */ getch() /* Reads character without echo */ getche() /* Reads character and echo */ putchar() /* Display a char on screen */ putch() /* Put a char to the consol */ gets() /* Input string */ puts() /* Output string */ putc() /* Write a char to stream */ scanf() /* Formatted input from keyboard */ printf() /* Formatted output on screen */ An Example: #include <stdio.h> char getchar(void); /* reads a char from standard input device: keyboard */ void main() char c; c = getchar();.. putchar(c) ; /* display a char at screen */ String I/O The gets() function reads a line of string from the standard input device (stdin) and stores it in a buffer. The line consists of all characters and the first new-line character ('\n'). The gets() function then substitutes the '\n' with the null character '\0' before returning the line. The puts() function can be used to print a character string on the screen. It automatically eplaces the string terminating null char ('\0') with a new line char ('\n') in the output stream.

Lin/ August 2008 3-2 An Example: #include <stdio.h> void main(void) char line[80]; char *destination; /* a character pointer */ gets(line); /* Read a line of string from keyboard */ printf("%s\n", line); puts("this is the output from puts():"); puts(line); Formatted Input Function: printf() The printf() function uses format specifiers in the format string for printing formats references. It sends the data to be printed with appropriate display format on the standard output device (stdout) or monitor screen. Some basic characteristics of this function are Writes character string and values of variables, formatted, to stdout int printf (const char *format, ); printf format specification: %[Flag][Width].[Precision]]Addr.Mode][/size][Type] * Format string contains any combination of characters and formatting codes Format Specifiers %c --- character %d, %o, %u, %x, %X --- integer: decimal, octal, unsigned, hex (a-f or A-F) ld, lo, lu, lx, lx if type long %f --- floating pointer, decimal notation(default 6 digits) %lf --- double floating-point number %e --- floating-point scientific notation %le --- double floating-point scientifc notation %g --- maximum number of characters to be printed either in %e or %f form %s --- string %% --- for printing a literal % symbol

Lin/ August 2008 3-3 It is possible to use flags between the % sign and conversion character to modify the printing format. An example Flags Meaning - Left justified printing + Print either + or - sign 0 Zero causes 0 s to be used for padding # Unsigned integer control which causes a 0 or 0x to be prefixed to the octal or hexadecimal value displayed Width (precision) Meaning %10d, %10s At least 10-char %.7s At most 7-char %14.8s 14-char in total, use only 8-char %-7d Left justify, min. field width 7 %8.2f Field width 8, precision 2 %05d Padding with zeros %-10.5e Left justified e format printf ( Hi! C is fun\n ); // passing a string constant // newline doesn t automatically generated static char name [ ] = C Workshop\n ; printf (name); // pass address of string array printf( x * y = %d * %d = %d\n, x, y, x*y); Formatted Input Function: scanf() The scanf() function inputs data from stdin (standard input device such as keyboard) into the locations given by arguments. The function is described below int scanf (format string [,pointers]) Reads a list of arbitrary length of arguments from keyboard Conversion of char into binary representation in case of %d, and use %hd for short integer Return 1 if successful, 0 otherwise It assumes that each argument must be a pointer to a variable with a type that corresponds to a type specifier. The symbol ampersand (&) preceding variable names is used to inform the compiler that the arguments are addresses of variables. The inputs from keyboard will be placed in memory locations that having those addresses.

Lin/ August 2008 3-4 The "%s", " %d", "%c", and " %f" as shown in scanf() functions are called the format string which ask the scanf() function to convert the keyboard inputs to the formats as specified: %s as string format, %d as integer format, %c as character format, and %f as floating-point number format. The converted values will be to be placed into the memory locations of reserved for those variables and are referred through address operator (&), namely the addresses of variables: id, grade, and point (&id, &grade, and &point). Since the string "name" by itself is an address the & operator is not needed. An Example #include <stdio.h> void main(void) int id; char grade; float point; printf("\nplease enter a name: "); scanf("%s", name); printf("\nplease the ID number: "); scanf("%d", &id); printf("\nplease the letter grade: "); scanf("%c", &grade); printf("\nplease enter the numerical grade : "); scanf("%f", &point);... Important notes about the scanf(): scanf ( %f, &data); First argument indicates the input format, the second argument specifies where the variable is located Always take pointers (&var) and pass the variable address to it Character array s name is the address itself scanf() reads the input stream until it finds a white space character: SPACE, TAB, or ENTER fflush (stdin) function can be used to clear keyboard s buffer which holds awaiting characters String input from the keyboard, gets() is generally preferable to scanf(), because gets() receives a line of character from the stdin and places the line in an array and add a \0.

Lin/ August 2008 3-5 3-2 Mathematics and Utility Functions To use C standard mathematics functions, we must include the header file <math.h> so that the proper interface to these functions is provided. We note that all the input augumnts and return value for math functiona are defined as double floating-point number data type by default. And the augument for trigonometric functions should be in the units of radians. Functions for nummber conversion, random number generation, absolute value, etc., are called utility functio. The header file <stdlib.h> contains needed definitions. An example of math function prototype or definition is depectied as the following: Return value type Function name double sin( double x); Argument type Paremeter name Absolute Value Calculation <stdlib.h> Int abs(int x); - Absolute value of an integer long labs(long x); double fabs(double x); - Absolute value of a long - Absolute value of x ASCII strings to Numerical Value Conversion <stdlib.h> double atof(const char *string); - Convert ASCII string to float-point number int atoi(const char *string); long atol(const char *string); - Convert ASCII string to integer number - Convert ASCII string to long integer Ceiling and Floor Values <math.h> double ceil(double x) - Calculate the ceiling of a value - returns a smallest integer that is greater than or equal to x. - It round up the digits after the decimal points double floor(double x) - returns a lergest integer that is less than or equal to x. - It round off the digits after the decimal points

Lin/ August 2008 3-6 Trigonomitric and Inverse Trigonomitric Functions <math.h> double cos(double x) - Cosine function takes the x of units in radians - The result is a value in the range 1 to 1 double sin(double x) - Sine function takes x of units in radians - The result is a value in the range 1 to 1 double tan(double x) - Tangent function takes x of units in radians - The result is a value in the range 1 to 1 double acos(double x) - Arc cosine function accetps x in the range 1 to 1 - The result is an angle with value between 0 to π double asin(double x) - Arc sine function accepts x in the range 1 to 1 - The result is an angle with value between -π/2 to π/2 double atan(double x) - Arc tangent function accepts x in the range 1 to 1 - The result is an angle with value between -π/2 to π/2 - If x is 0, atan() returns 0 double atan2(double y, double x) - The function accepts the argument in the form of y/x. - If both y and x parameters are 0, the result is 0 - The result is an angle with value between -π to π Hybobolic Functions <math.h> ( A special class of exponential functions) double cosh(double x) - Hyperbolic cosine - cosh x = (e x + e -x )/2 double sinh(double x) - Hyperbolic sine - sinh x = (e x - e -x )/2 double tanh(double x) - Hyperbolic tangent - tanh x = sinh x/ cos hx Logarithm Functions <math.h>

Lin/ August 2008 3-7 double log(double x) - log e x - Calculate natual logarithm, of a positive x; if x is negative it returns a NaN (not a number or infinite) double log10(double x) - log 10 x - Compute logarithm to the base 10 of a positive x Power and Square Root Functions <math.h> double sqrt(double x) - Square root of a nonnegative x or x 1/2 double pow(double x, double y) - Calculate x to the y power or x y double exp(double x) - Raise e (2.718281828..) to the power of x or e x Random Number Generator Functions <stdlib.h> Must include the standard library function #include <stdlib.h> Int rand(void) - Compute pseudo random number - The return number in the range 0 to RAND_MAX Void srand(unsigned int x) - Seed the random number generator for a random starting point - Call this function before rand() - To reinitialize the generator, use 1 as the seed argument

Lin/ August 2008 3-8 Example 3-1: Using standard math functions Two symbolic constants are defined using the identity 360 = 2π radians for converting between angle in the unit of degrees and in radians. We also define variable as double floating-point number type and print them using the %lf format specifier. As we examine the program output, we note that there are some precision issues related to these function and printing format. /* trigmath.c */ #include <math.h> #include <stdio.h> #define PI 3.14159 #define Deg_to_Rad #define Rad_to_Deg PI/180.0 180.0/PI void main(void) double theta = 45.0; double ysin, ycos, ytan; ysin = sin(theta * Deg_to_Rad); ycos = cos(theta * Deg_to_Rad); ytan = tan(theta * Deg_to_Rad); printf("sin(%lf Degree) = %lf\n", theta, ysin); printf("cos(%lf Degree) = %lf\n", theta, ycos); printf("tan(%lf Degree) = %lf\n", theta, ytan); printf("tan(%lf Degree) = %e\n", theta, ytan); printf("atan(1.0) gives angle = %lf radians\n", atan(1.0)); printf("ongle is PI/4 = %lf radians\n", PI/4.0); Output sin(45.000000 Degree) = 0.707106 cos(45.000000 Degree) = 0.707107 tan(45.000000 Degree) = 0.999999 tan(45.000000 Degree) = 9.999987e-001 atan(1.0) gives angle = 0.785398 radians Ongle is PI/4 = 0.785397 radians

Lin/ August 2008 3-9 Example 3-2: A program for testing various math functions. /* logex.c */ #include <math.h> #include <stdio.h> #define PI 3.14159 void main(void) double y; printf("log10(1000.0) = %lf\n", y); printf("log(1000.0) = %lf\n", log(1000.0)); printf("exp(1) = %lf\n", exp(1)); printf("pow(2,16) = %8.0lf\n", pow(2.0, 16.0)); printf("sqrt(9) = %lf\n", sqrt(9.0)); printf("ceil(99.9999) = %lf\n", ceil(99.9999)); printf("ceil(99.4) = %lf\n", ceil(99.4)); printf("ceil(99.0001) = %lf\n", ceil(99.0001)); printf("floor(99.9999)= %lf\n", floor(99.9999)); printf("floor(99.4) = %lf\n", floor(99.4)); printf("floor(99.0001)= %lf\n", floor(99.0001)); printf("atan(1.0) gives angle = %lf radians\n", atan(1.0)); printf("ongle is PI/4 = %lf radians\n", PI/4.0); Output log10(1000.0) = 3.000000 log(1000.0) = 6.907755 exp(1) = 2.718282 pow(2,16) = 65536 sqrt(9) = 3.000000 ceil(99.9999) = 100.000000 ceil(99.4) = 100.000000 ceil(99.0001) = 100.000000 floor(99.9999)= 99.000000 floor(99.4) = 99.000000 floor(99.0001)= 99.000000

Lin/ August 2008 3-10 3-3 Flow of Control The flow control statements allow iterations, repetition, or looping. They may be also used to specify the the normal sequence of execution and out-of-sequence computations. A loop is a form of iteration in which a sequence of statements is repreated a number of times. C provides several types of loop control structures for iteration: - for loop allows to repeat the statements for a fixed number of times - while loop needs to check the condition before the iteration - do while (same as while loop, except that it will execute the statements enclosed by the loop and then check for ending condition. So it does the loop at least once no matter what. for LOOP Basic format of the for loop: for(initialization; end_cond_checking; update); s1; s2; sn; Note there are three major components in the "for" loop construct: 1. Initialization is where we initialize the loop counter 2. end_cond_chekcing is where we check the ending condition 3. update is where the ending condition is evaluated such that incorrect endless loop execution can be prevented The "for" statement provides a leading-test construct with initialization and reinitialization provisions which imply that the termination testing is done at the top. If compound statements are used in the loop, a pai of braces are needed to include all the statements in the reapeating process. Form 1: Null Statement (no statements for execution) for (init; end_cond_checking; update); Form 2: Simple Statement (one statement for computation)

Lin/ August 2008 3-11 for (i = 0; i < 10; i++) sum += 1; Form 3: Compound Statement (many statements for evaluation) for (init; end_cond_ching; update) s1; s2; Form 4: Nested Loops for ( ; ;) /* End Less Loop */ for (init; end_cond_checkig; update) s1; s2; s3; for (init; end_cond_checking; update) s4; while Loop If there is a need to perform counting, adding, searching, sorting, monitoring, or other tasks that involve something over and over, "while" or "do while" may be used to do the repetitive actions. The "while" loop is a generalized looping structure that employs a variable or expression for testing the ending condition. It is the responsibility of the programmer to initialize and update the variables used in the loop control test. Note that the testing of termination condition is done at the top of the while loop. If condition is true, then the expression is evaluated. This cycle continues until the expression becomes false. A "for" loop example as shown below: for (exp1; exp2; exp3) statement; is equivalent to while loop:

Lin/ August 2008 3-12 exp1; while (exp2) statement; exp3; Some important remarks Variables used in the loop control testing must be initialized Testing for the termination condition is done at the top of the while() loop while (1) endless loop == for (;;) Form 1: Simple Statement while (condition) statement; Form 2: Compound Statements while (condition) s1; s2; s3;.. do while LOOP Executes its loop body; test the termination conditions Always executes its loop body at least once The "do while" statement is provided in C to complement the "while" statement and is guarateed that the "do" loop always executes its loop body at least once and then tests the termination condition. This is the main difference between the "while" and the "do while" loop. The do-while construct syntax has two forms as shown below: Form 1: Simple Statement

Lin/ August 2008 3-13 do statement; while (condition); Form 2: Compound Statements do s1; s2; s3; while (condition); Relational and logical operators are normally used in the flow of control constructs for evaluating the true or false value of the ending condition. As we remember that In C, zero is used to represent false and a value of nonzero means true. Therefore, the statement like while(1) statement; is used an endless loop because the condition for the checking is true all the time. Other examples of using these operators are listed below: while(a > b) /* a greater than b */ while(a <= b) /* a less or greater than b */ while(a!= b) /* a not eaual to b */ while(a == b) /* a equal to b */ while(a < (c + b)) /* a less than c + b */ while(!a) /* while not a */ while(a && b) /* while a and b are both nonzero or true */ while(a b) /* while either a or b is nonzero or true*/

Lin/ August 2008 3-14 Example 3-3: A simple for loop for controlling the activities of the keyboard input and screen output. /* char0.c */ #include <stdio.h> #define NEWLINE '\n' void main() char name[30]; int c; for(;;) /* Execute following forever, CTRL C to stop */ printf("\nplease enter your name: "); gets(name); puts("is this your name?"); puts(name); printf("\nplease enter a digit: "); c = getchar(); puts("\nis this the digit?"); putchar(c); putchar(newline); fflush(stdin); // Flush the keyboard buffer Output of char0.c: Please enter your name: Paul Lin Is this your name? Paul Lin Please enter a digit2 Is this the digit? 2 Please enter your name

Lin/ August 2008 3-15 Example 3-4: Generating seeded and unseeded pesudo random numbers /* randgen.c */ #include <stdio.h> #include <math.h> #include <stdlib.h> void main(void) int n; /* Generate 4 unseeded pseudo random numbers*/ for(n = 1; n < 5; n++) printf("%d\t", rand()); puts("\n"); /* Generate time() function seeded peudo random numbers */ srand((unsigned)time(null)); for(n = 1; n < 5; n++) printf("%d\t", rand()); puts("\n"); /* Reset peudo random generator */ srand(1); for(n = 1; n < 5; n++) printf("%d\t", rand()); puts("\n"); Output 41 18467 6334 26500 23925 14696 22825 6798 41 18467 6334 26500

Lin/ August 2008 3-16 3-4 Decision Making This section introduces the following decision-making statements: * if * if-else * else-if * switch If Statement The "if" statement is the simplest form of decision making. The baisc construct syntax of the if statement is If the expression exp is true, statement s1 is executed: if(exp) s1; which consists of an "if" statement followed by a test expression in the parentheses, and a single statement. The "if" portion tests for the logical true or false value of a given expression. If the expression is true (nonzero), the statement following the "if" is executed. Otherwise, the control is transferred to other statements outside the "if" construct. if-else Statement In a decision making process, an "if-else" statement is used to choose between alternative operations within a program. The construct of the if-else statement is shown below. If the expression exp is true, statement s1 is executed, otherwise statement s2 is executed: if(exp) s1; else s2; Nested if-else Statement A sequence of if-else statement can be used for a multi-way decision making. Nested else-if statements as shown below allows the expressions to be evaluated in order:

Lin/ August 2008 3-17 if (condition1).. else if (condition2): if(exp1) s1; else if(exp2) s2; else s3; Note that the properties of the else-if: - We use each else-if to select one from among the alternatives. - When any of the else-if conditions is satisfied, all the remainidng else-if's are skipped. - The last else, the one without if is the default case. An example that use else-if in formulating a program to give letter grade is shown below: Scores Grades if (score > 94) 95-100 A grade = 'A'; 85-94 B else if (score >84) 70-84 C grade = 'B'; 60-69 D else if (score >69) 0-59 F grade = 'C'; else if (score > 59) grade = 'D'; else grade = 'F'; Again, the relational, logical, and equality operators are normally used to form more complicate conditions for testing. The truth table as shown below may be used as a reference for forming more complicate logical relations. A B A &&B A B!A!B F F F F T T F T F T T F T F F T F T T T T T F F C language also provide two statements,

Lin/ August 2008 3-18 break ; continue; for interrpting the normal flow of execution and perorming an out of sequence execution. break Statement Send the execution out of immediate loop of decision making blocks: while(), for(), do-while, if, switch It provides an early exit Example while (1) // 1 is true always so this endless loop if (x < 0.01) break; // exit the while loop s1; s2; for (i = 0; i < 5; i++) if (j > 2) break; // exit the for loop if j > 2 is true j++; continue Statement Used inside the for, while, do-while, switch Immediately terminates the current block iteration of the innermost block; causes next iteration of a loop to begin Example: while (1) s1; s2; if (x >= 0.01) continue; // start over again else break; // exit the while loop now

Lin/ August 2008 3-19 Example 3-5: A simple example using if() to count the number of A, B, and C characters in a string. /* if0.c */ /* Counting A, B, C characters */ #include <stdio.h> #define SIZE 81 #define F "A = %d, B = %d, C = %d\n" void main() int i; int a, b, c; // counters char ch, s[size]; a = b = c = 0; for(;;) // Enter <Ctrl C> to exit puts("enter a string"); gets(s); for(i = 0; (ch = s[i])!= '\0'; i++) if((ch == 'A') (ch == 'a')) a++; if((ch == 'B') (ch == 'b')) b++; if((ch == 'C') (ch == 'c')) c++; printf(f,a,b,c); Output of if0.c Enter a string The C Programming Language. A = 3, B = 0, C = 1 Enter a string

Lin/ August 2008 3-20 Example 3-6: Testing various ASCII character classes. /* if3.c */ /* Char Class Testing */ #include <stdio.h> #include <ctype.h> static char s[] = "1aBY4*$%"; void main() char c; int i = 0; while((c = s[i++])!= '\0') if(islower(c)) printf("%c = ",c); puts("l_case"); if(isupper(c)) printf("%c = ",c); puts("u_case"); if(isgraph(c)) printf("%c = ",c); puts("printable"); if(isdigit(c)) printf("%c = ",c); puts("digit"); if(c % 2 == 0) puts("even number"); Output of if3.c 1 = PRINTABLE 1 = Digit a = L_CASE a = PRINTABLE B = U_CASE B = PRINTABLE Y = U_CASE Y = PRINTABLE 4 = PRINTABLE 4 = Digit Even number * = PRINTABLE $ = PRINTABLE % = PRINTABLE = PRINTABLE

Lin/ August 2008 3-21 Example 3-7: Counting blanks, digits, newlines, letters and others // ifelse1.c // Counting blanks, digits, newlines, letters and others // // EOF: end of file character is defined in <stdio.h> as -1 // Ctrl Z... MS-DOS system // Ctrl D... UNIX system // // To run this program to count the ifelse0.c source code // under the MS-DOS prompt you type: // C:\UNIT3\ifelse0 < ifelse0.c #include <stdio.h> void main() char ch; int b, d, n, l, others; b = d = n = l = others = 0; while((ch = getchar())!= EOF) if(ch == ' ') ++b; else if(ch >= '0' && ch <= '9') ++d; else if(ch >= 'a' && ch <= 'z' ch >= 'A' && ch <= 'Z') ++l; else if(ch == '\n') ++n; else ++others; printf("blanks = %d\t", b); printf("digits = %d\n", d); printf("newlines = %d\t", n); printf("letters = %d\n", l); printf("others = %d", others); Output of ifelse0.c D:\C&API\UNIT3>ifelse0 < ifelse0.c blanks = 201 digits = 9 newlines = 31 letters = 413 others = 190 D:\C&API\UNIT3>

Lin/ August 2008 3-22 Example 3-8: An example shows the effect of break and continue /* break0.c */ /* Example of using break and continue */ #include <stdio.h> #include <math.h> #define ZERO 0.0 void main() float x, y; while(1) printf("enter a number: "); scanf("%f", &x); if(x < ZERO) break; /* exit loop */ y = sqrt(x); printf("%f\n", y); printf("enter second number: "); scanf("%f", &x); if(x > - 0.001 && x < 0.001) continue; /* start next iteration */ y = sqrt(x); printf("%f\n", y); Output of break0.c Enter a number: 10 3.162278 Enter second number: 0.0001 Enter a number: 2 1.414214 Enter second number: -0.000001 Enter a number: 0 0.000000 Enter second number: 0.1 0.316228 Enter a number: -0.1

Lin/ August 2008 3-23 3-5 Multiple Decision Making The "siwtch" statement is often used to perform a multiway branch (the chain of if-else statement) that selects among several different cases. The "break" statement is used within a switch statement to end each "case" label and to exit switch statement. Its general form is given by switch(expression) case 1: statement i; break; case 2: statement j;.. break; case n: statement n; break; default:. break; where statement is typically a compound statement containing "case" label and optionally a "default" label. In a switch statement, first, the integeral expression after the switch() is evaluated. The value it yields is then matched, one by one, against the values, or labels, that following the case, and all subsequent case and default statements as well. If no match is found with any of these case labels, only the statement following the default keyword is executed. Notice that a "break" statement should be inserted at the end of each "case" statement. Example: The default case is not used in this example. Following the switch(i) statement, when i == 1 is matched, j = j + 5 is executed. When i == 2 or i == 3 is matched, the j = j + 3 is executed. Finally, when there is no match, the switch() is ended without executing any statement. switch(i) case 1: /* i = 1, j = j + 5 */ j = j + 5; /* is executed */ break; case 2: /* i = 2 or 3, j = j + 3 */ case 3: j = j + 3; break; * anything else -- none

Lin/ August 2008 3-24 Remarks on switch Multi-way branch (the chain of if-else statement) To select among several different cases break is used to end each case to exit the switch The default is optional General form of switch(n) n can be an integer, unsigned integer, or character type switch (n) case 0: statement0; break; case 1: statement1; break; default: statement;

Lin/ August 2008 3-25 Example 3-9: A calculator program using C++ console input (cin) and output (cout) streams. The source code is saved with.cpp as the extension and the <iostream.h> header file is included. We note that the cin and cout are more robust than the scanf(0 and printf(). /* switch0.cpp */ #include <stdio.h> #include <stdlib.h> #include <iostream.h> void main() float n1, n2, result; char op; while(1) // Enter <Ctrl C> to exit fflush(stdin); puts("hit any key to continue, Ctrl C to exit\n"); getchar(); // waiting for user to input printf("\nenter a number: "); cin >> n1; // Console input printf("\nenter second number: "); cin >> n2; // Console input printf("\nselect an operator +,-,*, x, / or \\: "); cin >> op; switch(op) case '+': result = n1 + n2; printf("%f\n", result); break; case '-': result = n1 - n2; printf("%f\n", result); break; case '*': case 'x': case 'X': result = n1 * n2; printf("%f\n", result); break; case '/': case '\\': result = n1 / n2; printf("%f\n", result); break; default: puts("wrong operator entered"); Output of switch0.c Hit any key to continue Enter a number: 12.0 Enter second number: 20.0 Select an operator +,-,*, x, / or \: * 240.000000 Hit any key to continue 3-6 Data Array Processing Array Characteristics

Lin/ August 2008 3-26 For grouping data of the same type under one name Elements of an array are stored sequentially in memory The size of the array must be known at the time the array is allocated Array s name is the base address or pointer to the beginning location of the array Elements are accessed through either subscripts (indexes)or pointers An array subscript is enclosed in a pair of brackets and is always counted from 0 to SIZE - 1 For a character array, the last location is reserved for \0 (null character) For integer and float arrays, all the locations can be used for holding data Out of array boundary checking is not checked by the C system Types of arrays Array of characters String array Array of integers Array of floating point numbers Array of pointers Multi-dimensional array type array_name[size][size]..[size]; Array Declarations: Arrays must be declared before use The purpose of defining integer arrays is to inform compiler the memory storage will be needed for array elements One-Dimensional Arrays char name[30]; // 29 characters char buffer[1024]; // 1023 characters unsigned char image[256][256]; /* 8-bit gray level, image array */ int rpm[100]; /* 100 elements */ int io_channel[10]; /* IO channel */ flloat pid[3]; // 3 parameters for Personal ID Number char device_name[10][10]; /* 10 string arrays */ char *device[10]; /* a pointer array */ Two Dimensional Arrays Here we define a 2-D character array that can be used for displaying 2-by-20 characters. #define SIZE 2 #define LEN 20

Lin/ August 2008 3-27 char display_lcd[size][len] &display_lcd[0][0] address of the element at row 0 col 0 &display_lcd[0][19] address of the element at row 0 col 19 &display_lcd[1][0] address of the element at row 1 col 0 &display_lcd[1][19] address of the element at row 1 col 19 #define ROW 2 #define COL 2 int data[row][col; &data[0][0] address of the element at row 0 col 0 &data[0][1] address of the element at row 0 col 1 &data[1][0] address of the element at row 1 col 0 &data[1][1] address of the element at row 1 col 1 Initializing Arrays Small one dimensional arrays can be initialized at the declaration time using static key word. For examples: static int d_array[3] = 1, 2, 3; static int parts_bin = 100, 120, 200, 300, 400, 120; Now parts_bin[] array has 6 elements and all are initialized. These elements can be accessed through parts_bin[0], parts_bin[1],.., parts_bin[5]. A small string array or 1-D character arrays can be initialzed through as either or static char string[5] = WXYZ ; static char string[5] = W, X, Y, Z, \0 ; Muit-dimensional arrays can be initialzed in the same way as the 1-D example: #define ROW 2 #define COL 2 static int data[row][col = 0, 1, 2, 3; /* Initialize Four 2-by-3 arrays */ static int my_array[4][2][3] = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24;

Lin/ August 2008 3-28 Initializing Array at run time can be done using loop control statements. For example, We may have to reinitialze all elements of the display_lcd[2](20] array to NULL or \0 before we send another set of characters for showing. /* Initialize a 2D character array */ #define SIZE 2 #define LEN 20 void main() char display_lcd[size][len]; int r, c; for(r = 0; r < ROW; r ++) for(c = 0; c < COL; c++) display_lcd[r][c] = \0 ; Typical 2-D character arrays may include a list of computer user name or a class roster. It is more convinient to treat them as a list of strings. We can define them using pointer to string and initialzed them: static *users[] = Paul, John, Dick ; Determining the Sizes of Arrays and Array Bounds Any time that storage for an array is allocated, we must know the the size of array so that we can prevent program form accessing out side the array boudary. The sizeof() operator can be used to determine the array size in the run time. For examples, to determine the size of the chartarer array display_lcd[][], we use the statement: sizeof(display_lcd)/sizeof(char) and the size of the integer data[][] array will be calculated as sizeof(data)/sizeof(int) Example 3-10: Manipulating character arrays. /* char1.c */ #include <stdio.h> #define SIZE 12 static char phone[size] = "219-4816339"; static char phone1[] = "219-4816338"; void main()

Lin/ August 2008 3-29 int i; char c; // A loop with counter for reading char array for(i = 0; i < SIZE ; i++) c = phone[i]; putchar(c); putchar('\n'); // A loop without a counter for reading char array until // the End of String delimeter: null character ('\0' or 00) // is encountered. for(i = 0; (c = phone1[i])!= '\0'; i++) putchar(c); Output 219-4816339 219-4816338

Lin/ August 2008 3-30 Example 3-11: Working with integer arrays. /* for0.c */ /* Initialize, copy and print contents */ /* of a[] and b[] arrays */ #include <stdio.h> #define SIZE 20 void main() int n, a[size], b[size]; // Initialize the a[] array with the index n: 0, 1, 2,.. 19 for(n = 0; n < SIZE; n++) a[n] = n; // Initialize the b[] array with a[n] + 2, namely, // 2, 3, 4, 5,... 21 for(n =0; n < SIZE; n++) b[n] = a[n] + 2; printf("a[%2d] = %2d, b[%2d] = %2d\n", n,a[n],n,b[n]); Output of for0.c: a[ 0] = 0, b[ 0] = 2 a[ 1] = 1, b[ 1] = 3 a[ 2] = 2, b[ 2] = 4 a[ 3] = 3, b[ 3] = 5 a[ 4] = 4, b[ 4] = 6 a[ 5] = 5, b[ 5] = 7 a[ 6] = 6, b[ 6] = 8 a[ 7] = 7, b[ 7] = 9 a[ 8] = 8, b[ 8] = 10 a[ 9] = 9, b[ 9] = 11 a[10] = 10, b[10] = 12 a[11] = 11, b[11] = 13 a[12] = 12, b[12] = 14 a[13] = 13, b[13] = 15 a[14] = 14, b[14] = 16 a[15] = 15, b[15] = 17 a[16] = 16, b[16] = 18 a[17] = 17, b[17] = 19 a[18] = 18, b[18] = 20 a[19] = 19, b[19] = 21 Example 3-12: Working with character arrays. /* for1.c */ /* Print 'a'..'z', 'A'..'Z' */ /* Initialize lletter[], and uletter[] */ /* Print the contents of arrays */ #include <stdio.h>

Lin/ August 2008 3-31 #define NEWLINE '\n' void main() int n; int i = 0; char uletter[27], lletter[27]; // Initialize char 'a' through 'z' for a lower case letter array for(n = 'a'; n <= 'z'; n++) printf("%c", n); lletter[i++] = (char) n; // Type casting lletter[i] = '\0'; // Insert an End-of-string delimeter putchar(newline); i = 0; // Initialize char 'A' through 'Z' for a lower case letter array for(n = 'A'; n <= 'Z'; n++) printf("%c", n); uletter[i++] = (char) n; uletter[i] = '\0'; putchar(newline); // Reading two character arrays for(i = 0; uletter[i]!= '\0'; i++) putchar(uletter[i]); putchar(newline); for(i = 0; lletter[i]!= '\0'; i++) putchar(lletter[i]); putchar(newline); Output of for1.c abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz

Lin/ August 2008 3-32 Example 3-13: Accessing data arrays using a while() loop. /* while0.c */ #include <stdio.h> #define FORMAT "data[%d] = %d,\ d[%d] = %d\n", i,data[i],i,d[i] // define format string #define N 6 static int data[] = 1,2,3,4,5,6 ; // static array definition void main() int d[n],i,j,k; i = 0; j = 1; k = 2; while(i < N) d[i] = data[i] * 2; printf(format); i++; /* Try access the array outside its boundary */ printf(format); i++; printf(format); Output of while0.c data[0] = 1, d[0] = 2 data[1] = 2, d[1] = 4 data[2] = 3, d[2] = 6 data[3] = 4, d[3] = 8 data[4] = 5, d[4] = 10 data[5] = 6, d[5] = 12 data[6] = 1635017060, d[6] = 6618680 data[7] = 1566844251, d[7] = 4199065

Lin/ August 2008 3-33 Example 3-14: A do/while loop example that uses rand() function to generate testing data. /* dowhile0.c */ #include <stdio.h> #include <stdlib.h> #define SIZE 10 void main() int i; unsigned r; float sum, saving[size]; i = 0; sum = 0.0; /* Initialize the saving array of float type*/ for(r = 0; r < 10; r++) srand(r); // set seed number for rand() function i = 0; do saving[i] = rand() * 1.0; printf("saving[%d] = $%8.2f\n",i,saving[i]); i++; while(i < SIZE); i = 0; // summing saving array do sum += saving[i++]; while (i < SIZE); printf("total saving is $%8.2f\n", sum); puts("hit any key to continue"); getchar(); Output of dowhile0.c saving[0] = $ 38.00 saving[1] = $ 7719.00 saving[2] = $21238.00 saving[3] = $ 2437.00 saving[4] = $ 8855.00 saving[5] = $11797.00 saving[6] = $ 8365.00 saving[7] = $32285.00 saving[8] = $10450.00 saving[9] = $30612.00 Total saving is $133796.00 Hit any key to continue

Lin/ August 2008 3-34 Example 3-15: Using if() statement to check if swapping is need. /* if1.c */ /* Swapping elements of an array */ #include <stdio.h> #define SIZE 4 static int a[] = 2, 4, 9, 0 ; void main() int i, temp; // Print array before swapping for(i = 0; i < SIZE ; i++) printf("a[%d] = %d\t", i, a[i]); for(i = 0; i < SIZE -1; i++) if(a[i] < a[i+1]) temp = a[i]; a[i] = a[i+1]; a[i+1] = temp; // Print array after swapping puts("\n"); for(i = 0; i < SIZE ; i++) printf("a[%d] = %d\t", i, a[i]); Output of if1.c a[0] = 2 a[1] = 4 a[2] = 9 a[3] = 0 a[0] = 4 a[1] = 9 a[2] = 2 a[3] = 0

Lin/ August 2008 3-35 3-7 Programming Applications Arithemetic Mean of N Numbers Arithemtic mean of n numbers is defined as n 1 mean = xi = n i= 1 x1 + x2 + x3... + x n n If we assume that all the numbers for averageing are stored in the x[n] array which is predefined through the following program segment: #define N 100 float x[n], mean = 0.0; int i; The following for loop will then evaluate the average of 100 elements of the array x[n]: for(i = 1; i < N; i++) mean += x[i]; mean /= N;

Lin/ August 2008 3-36 Factorials Calculating the factorial of a number using while() loop. We recall that the factorial of n (denoted n!) is defined as the the product of n terms: n! = 123 ( n 1) n = i n i= 1 By defnition 0! = 0 and the factorial of a negative number is undefined. Here we will use a while loop to compute the factorial of a number. We should note that the for a 32-bit computer, the integer variable can hold a number less than 2 32-1 -1 = 2.147483648e+009 /* while1.c */ /* Factorial of a Number */ /* n! = 1 * 2 * 3 *...* (n-1)* n */ #include <stdio.h> #define TRUE 1 #define FOREVER while(true) void main() int n; unsigned long f; puts("enter CTRL C to stop"); FOREVER // will be replaced with while(true) printf("enter a number: "); scanf("%d", &n); f = 1; /* n! calculation */ while( n > 1) f *= n--; printf("factorial is %ld\n",f); Output of while1.c Enter CTRL C to stop Enter a number: 1 Factorial is 1 Enter a number: 2 Factorial is 2 Enter a number: 5 Factorial is 120 Enter a number: 8 Factorial is 40320 Enter a number: 12 Factorial is 479001600 Enter a number: 13 Factorial is 1932053504 Calculating Sine Function Using Series A Sine function repeats itself every 2π radians. Using the sine series for an approximation of the sin(x) function: 3 5 7 9 11 x x x x x sin x = x + + +... 3! 5! 7! 9! 11!

Lin/ August 2008 3-37 We will compute the sine using this series using only five terms. And we compare it with the results from using the sin() function of the C math library. To reduce the length of our program, we use macros for calculating x^2,.. x^9, and factorials. It is strongly recommended that we enclosed a pair of parentheses of every dummy parameter that we use on the right side of the macros to minimize potential errors. For instance, we use the following define constant without the parentheses, incorrect result was given for converting degree to radians: #define REG_TO_RAD 180.0/PI /* sinesr.c */ #include <math.h> #include <stdio.h> #define PI 3.14159 #define DEG_TO_RAD (180.0/PI) /* 57.29577951308232 */ #define x2(x) (x * x) /* Macro for x ^2 */ #define x3(x) (x * x * x) /* Macro for x^3 */ #define x5(x) (x*x*x*x*x) /* Macro for x^5 */ #define x7(x) (x*x*x*x*x*x*x) /* Macro for x^7 */ #define x9(x) (x*x*x*x*x*x*x*x*x) /* Macro for x^9 */ #define FAC3 (1*2*3) /* Factorial 3 */ #define FAC5 (1*2*3*4*5) /* Factorial 5 */ #define FAC7 (1*2*3*4*5*6*7) /* Factorial 7 */ #define FAC9 (1*2*3*4*5*6*7*8*9) /* Factorial 3 */ void main(void) double sinser, sinlib, error; double x, n; printf("deg Radians Sine Series Sin(x) Error\n"); printf(" \n"); for(n = 0.0; n <= 90.0; n+=5.0) x = n/deg_to_rad; /* convert degree to radians */ sinlib = sin(x); sinser = x - (x3(x)/fac3)+ (x5(x)/fac5)- (x7(x)/fac7)+ (x9(x)/fac9); error = sinser - sinlib; printf("%5.2lf %9.8lf %9.8lf %9.8lf %+.6e\n", n, x, sinlib, sinser, error); printf(" \n"); The output generated by this program shows that the maximum error is 3.542551E-06 which is slightly larger than the sin(90) function from the C math function. Output

Lin/ August 2008 3-38 Deg Radians Sine Series Sin(x) Error 0.00 0.00000000 0.00000000 0.00000000 +0.000000e+000 5.00 0.08726639 0.08715567 0.08715567 +0.000000e+000 10.00 0.17453278 0.17364803 0.17364803 +1.110223e-016 15.00 0.26179917 0.25881883 0.25881883 +9.936496e-015 20.00 0.34906556 0.34201987 0.34201987 +2.347011e-013 25.00 0.43633194 0.42261793 0.42261793 +2.730927e-012 30.00 0.52359833 0.49999962 0.49999962 +2.027972e-011 35.00 0.61086472 0.57357601 0.57357601 +1.104591e-010 40.00 0.69813111 0.64278716 0.64278716 +4.795073e-010 45.00 0.78539750 0.70710631 0.70710631 +1.750303e-009 50.00 0.87266389 0.76604397 0.76604397 +5.572419e-009 55.00 0.95993028 0.81915158 0.81915160 +1.588251e-008 60.00 1.04719667 0.86602496 0.86602500 +4.131496e-008 65.00 1.13446306 0.90630738 0.90630748 +9.953193e-008 70.00 1.22172944 0.93969227 0.93969249 +2.246074e-007 75.00 1.30899583 0.96592554 0.96592602 +4.790796e-007 80.00 1.39626222 0.98480755 0.98480852 +9.729044e-007 85.00 1.48352861 0.99619459 0.99619648 +1.892315e-006 90.00 1.57079500 1.00000000 1.00000354 +3.542551e-006

Lin/ August 2008 3-39 A Calculator for Hex to Decimal Conversion It is often necessry to provide a user interface for allowing conversion from hex number to decimal number. The example program as shown below use multiple decision making swtich to determine the range of the hex number and apply the correct conversion formula to get the correct result. We will allow the user to enter either upper case letter or lower case letter for representing hex numbers. The gets() function is used to instead of scanf() for reading the hex number string into the string array for further processing. Three conversion formula are obtained based on the knowledge of ASCII values. For example, the ASCII digits '0' through '9' are represented as 0x30 through 0x39 in hex. The data[i] - '0' subtraction will produce a decimal number. Accumulating partial Results Hex to Decimal conversion n = 16 * n + (data[i] - '0'); shift left one digit The same reasoning can be applied to hex numbers in upper case 'A', 'B',.. 'F' and in lower case 'a', b', 'f'. n = 16 * n +(data[i] - 55); /* for upper case 'A', 'B', 'F' */ n = 16 * n + (data[i] -87); /* for lower case 'a', 'b', 'f' */ /* hextoi.c*/ #include <stdio.h> #define EOS '\0' void main(void) static char data[20] = "FFFFFFFF"; /* Define an input buffer */ unsigned long value, n; int i; /* User input a Hex string of up to 8 digits */ /* htoi: converts a hex number into an integer */ for(;;)

Lin/ August 2008 3-40 puts("\n\nenter a Hex number string of up to 8 digits for "); puts(" converting to decimal number: Example: FFFF"); printf("\nenter: "); gets(data); n=0; i=0; while (data[i]!= EOS) switch (data[i]) case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': n = 16 * n + (data[i] - '0'); break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': n = 16 * n +(data[i] - 55); break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': n = 16 * n + (data[i] -87); break; default: printf("please try again"); break; i++; value = n; printf("%lu\n",value); Output Enter a Hex number string of up to 8 digits for converting to decimal number: Example: FFFF Enter: FFFFFFFF 4294967295 Enter a Hex number string of up to 8 digits for converting to decimal number: Example: FFFF Enter: FFFF 65535

Lin/ August 2008 3-41 Learning Checks What will the following statements print? a. printf("%d", 7 >= 1); b. The abs(x) is used to compute the absolute value of an integer. A simple if statement written as is equivalent to the abs(x) function. We may also use the conditional operator to form the statement that will do the same job as the previous two. The following statement will allow us to check the property of variable n. When n% 2 == 0 we know that remainder is 0 so that n holds an even number, otherwise it will be an odd number. The statements for this checking this property and print it on the screen should be:. The following declaration reserves an array of type. For a 32-bit C compiler, the memory storage needed for the array will be bytes. To move a zero into the last element of the array, we should write the statement as. If we want to read the value of the first element and place it into k variable, the statement should be. int k; static int n[10] = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9; Use the sizeof() operator to determine the number of bytes reserved for the n[10] array as shown in the previous question. A character string array is a one dimensional array. If we declare the array as StreetName[40], the maximum number of elements for holding the name will be and the last location is normally used for holding. A two dimensional array called name can be declared as so that it can be used to store a list of 100 names with each name up to 30 characters. The statement for testing the x greater than 5 and less than or equal to 100 is. Knowing that the ceil(x) function will return the smallest value that is greater than or equal to x. The statement y = ceil(1.04) will return a value of to y. While the statement y1 = ceil(-1.04) will return a value of to y1. Given the definition of the floor(x) function as that it returns the largest value that is less than or equal to x. What are the return values for the following function calls? y = floor(1.8204); y1 = floor(-1.8204); The conditional expression is needed if we want to keep while loop repeat itself as long as the variable n is not equal to m. (while( n!= m) ) Review Questions

Lin/ August 2008 3-42 1. Assume that x, y, and z and all float data type. Rewrite the following statement so that the divide-byzero error can be prevented. z = y /x; 2. Translate the following math equations into equivalent C expressions: a. I 2 R b. E sin(2πft) c. fc = 1/(2πfc) 1/2 d. 2 12 e. x y -1 f. Vc = 5(1 e -t/rc ) 3. Determine that if the two following program segemnts are equivalent: int n; int n = 1; flot sum = 0.0; flot sum = 0.0; for(n = 1; n <= 10; n++) while(i++ <= 10) sum = sum + (float) n ; sum = sum+ (float) n; 4. Define a two dimensional array called GRADE for holding grades of four exams. We assume that the class size is 30 students and currently we have only enrolled 20 students in the class. 5. Write a C condition for each of the cases listed below that describe a technical staff in a company who meets all the conditions as listed below: a. is eraning over $50,000 nannualy, b. is an experience C programmer, and c. is married with at least two children, 6. What is an error with the test of the following while loop? while( x = 7) 7. Identify errors of the following programs. #include <stdio.h> void main() int x = 3; while(x <= 100) n = x + 3; Programming Exercises 1. Enter the following program, compile and build the program. Execute the program and observe its effect. /* pr1.c */ void main() char ch = g ;

Lin/ August 2008 3-43 while(1) if( ch == Q ch == q ) break; putchar(ch); putchar( \n ); ch = getchar(); 2. Write a simple program that will prompt a user to print 1 to 80 start symbols * on the screen. 3. Write a C program to simulate the rolling of two dices that can produce the patterns of two number ranged: (1,1), (1,2), (1,3), (1,4), (1,5), (1,6) (2,1), (2,2), (2,3), (2,4), (2,5), (2,6) (3,1), (3,2), (3,3), (3,4), (3,5), (3,6) (4,1), (4,2), (4,3), (4,4), (4,5), (4,6) (5,1), (5,2), (5,3), (5,4), (5,5), (5,6) (6,1), (6,2), (6,3), (6,4), (6,5), (6,6) (a). The program should prompt the user to hit any key to roll two dices. (b). It will then generate the numbers and print as (num1,num2). (c). It repeat step (a) forever. 4. Write a C program to evaluate the expression Et () = 110 2 sin( 2πft+ ) 4 for t = 0, 0.1, 0.2,.., 20 ms, where f = 60 Hz. π 5. Using the C math library functions SIN and COS, tabulate the function 2 2 y = sin x+ cos x for x = 0.0, 0.1, 0.2,, 1.0 radians 6. The roots of the following quadratic equation 2 ax + bx + c = 0 can be calculated using the formula b b ac x = ± 2 4 2a Write a C program which will examine conditions and compute the roots for the following different cases Case 1. One root, if a == 0. Case 2. Distinct real roots, if a 0 and b 2 4ac is not negative. Case 3. Equal roots Case 4. Complex roots

Lin/ August 2008 3-44 Note that the inputs a, b, and c for testing will be provided by user through scanf() function. 7. Given the following expressions π 32 1 1 1 1 1 1 = + + +... 1 3 3 3 5 3 7 3 9 3 11 3 Write a C program to compute an approximation of PI using thirty-three terms of the series. 8. Write a rogram that computes and prints the first 20 partial sums of the series 1 x = 0 x! that used to approxiamte e, the base of natural logarithms. 9. Write a program using for loop, sin() and printf() functions to plot the function: sin(x), for x = 0, 10, 20,.. 360 degrees and to include its axes. 10. Write a C program to print a multiplication table as shown below: * _1 2 3 4 5 6 7 8 9 1 1 2 3 4 5 6 7 8 9 2 2 4 6 8 10 12 14 16 18 3 3 6 9 12 15 18 21 24 27 4 4 8 12 16 20 24 28 32 36 5 5 10 15 20 25 30 35 40 45 6 6 12 18 24 30 36 42 48 54 7 7 14 21 28 35 42 49 56 63 8 8 16 24 32 50 48 56 64 72 9 9 18 27 36 45 54 63 72 81