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

Size: px
Start display at page:

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

Transcription

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

2 Lin/ August 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.

3 Lin/ August 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

4 Lin/ August 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.

5 Lin/ August 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.

6 Lin/ August 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

7 Lin/ August 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>

8 Lin/ August 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 ( ) 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

9 Lin/ August 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 #define Deg_to_Rad #define Rad_to_Deg PI/ /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( Degree) = cos( Degree) = tan( Degree) = tan( Degree) = e-001 atan(1.0) gives angle = radians Ongle is PI/4 = radians

10 Lin/ August Example 3-2: A program for testing various math functions. /* logex.c */ #include <math.h> #include <stdio.h> #define PI 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( ) = %lf\n", ceil( )); printf("ceil(99.4) = %lf\n", ceil(99.4)); printf("ceil( ) = %lf\n", ceil( )); printf("floor( )= %lf\n", floor( )); printf("floor(99.4) = %lf\n", floor(99.4)); printf("floor( )= %lf\n", floor( )); 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) = log(1000.0) = exp(1) = pow(2,16) = sqrt(9) = ceil( ) = ceil(99.4) = ceil( ) = floor( )= floor(99.4) = floor( )=

11 Lin/ August 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)

12 Lin/ August 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:

13 Lin/ August 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

14 Lin/ August 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*/

15 Lin/ August 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

16 Lin/ August 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

17 Lin/ August 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:

18 Lin/ August 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) A grade = 'A'; B else if (score >84) C grade = 'B'; 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,

19 Lin/ August 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

20 Lin/ August 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

21 Lin/ August 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

22 Lin/ August 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>

23 Lin/ August 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 > && x < 0.001) continue; /* start next iteration */ y = sqrt(x); printf("%f\n", y); Output of break0.c Enter a number: Enter second number: Enter a number: Enter second number: Enter a number: Enter second number: Enter a number: -0.1

24 Lin/ August 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

25 Lin/ August 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;

26 Lin/ August 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 \: * Hit any key to continue 3-6 Data Array Processing Array Characteristics

27 Lin/ August 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

28 Lin/ August 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;

29 Lin/ August 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] = " "; static char phone1[] = " "; void main()

30 Lin/ August 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

31 Lin/ August 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, 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>

32 Lin/ August #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

33 Lin/ August 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] = , d[6] = data[7] = , d[7] =

34 Lin/ August 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] = $ saving[1] = $ saving[2] = $ saving[3] = $ saving[4] = $ saving[5] = $ saving[6] = $ saving[7] = $ saving[8] = $ saving[9] = $ Total saving is $ Hit any key to continue

35 Lin/ August 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

36 Lin/ August Programming Applications Arithemetic Mean of N Numbers Arithemtic mean of n numbers is defined as n 1 mean = xi = n i= 1 x1 + x2 + x 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;

37 Lin/ August 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 = e+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 Enter a number: 12 Factorial is Enter a number: 13 Factorial is 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: x x x x x sin x = x ! 5! 7! 9! 11!

38 Lin/ August 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 #define DEG_TO_RAD (180.0/PI) /* */ #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 E-06 which is slightly larger than the sin(90) function from the C math function. Output

39 Lin/ August Deg Radians Sine Series Sin(x) Error e e e e e e e e e e e e e e e e e e e-006

40 Lin/ August 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(;;)

41 Lin/ August 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 Enter a Hex number string of up to 8 digits for converting to decimal number: Example: FFFF Enter: FFFF 65535

42 Lin/ August 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( ); 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

43 Lin/ August 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 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 ;

44 Lin/ August 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 () = 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

45 Lin/ August Note that the inputs a, b, and c for testing will be provided by user through scanf() function. 7. Given the following expressions π = 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, degrees and to include its axes. 10. Write a C program to print a multiplication table as shown below: * _

ECET 264 C Programming Language with Applications. C Program Control

ECET 264 C Programming Language with Applications. C Program Control ECET 264 C Programming Language with Applications Lecture 7 C Program Control Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin Lecture 7 - Paul I. Lin

More information

ECET 264 C Programming Language with Applications

ECET 264 C Programming Language with Applications ECET 264 C Programming Language with Applications Lecture 10 C Standard Library Functions Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin Lecture 10

More information

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

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR 1 Functions Functions are everywhere in C Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Introduction Function A self-contained program segment that carries

More information

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

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction Functions Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur Programming and Data Structure 1 Function Introduction A self-contained program segment that

More information

ECET 264 C Programming Language with Applications

ECET 264 C Programming Language with Applications ECET 264 C Programming Language with Applications Lecture 6 Control Structures and More Operators Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin Lecture

More information

ECET 264 C Programming Language with Applications

ECET 264 C Programming Language with Applications ECET 264 C Programming Language with Applications Lecture 9 & 10 Control Structures and More Operators Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.ecet.ipfw.edu/~lin

More information

Functions. Systems Programming Concepts

Functions. Systems Programming Concepts Functions Systems Programming Concepts Functions Simple Function Example Function Prototype and Declaration Math Library Functions Function Definition Header Files Random Number Generator Call by Value

More information

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

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 Functions 1 Function n A program segment that carries out some specific, well-defined task n Example A function to add two numbers A function to find the largest of n numbers n A function will carry out

More information

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

6-1 (Function). (Function) !*+!#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x (Function) -1.1 Math Library Function!"#! $%&!'(#) preprocessor directive #include !*+!"#!, Function Description Example sqrt(x) square root of x sqrt(900.0) is 30.0 sqrt(9.0) is 3.0 exp(x) log(x)

More information

C Programs: Simple Statements and Expressions

C Programs: Simple Statements and Expressions .. Cal Poly CPE 101: Fundamentals of Computer Science I Alexander Dekhtyar.. C Programs: Simple Statements and Expressions C Program Structure A C program that consists of only one function has the following

More information

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

Functions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa Functions Autumn Semester 2009 Programming and Data Structure 1 Courtsey: University of Pittsburgh-CSD-Khalifa Introduction Function A self-contained program segment that carries out some specific, well-defined

More information

Introduction to C Language

Introduction to C Language Introduction to C Language Instructor: Professor I. Charles Ume ME 6405 Introduction to Mechatronics Fall 2006 Instructor: Professor Charles Ume Introduction to C Language History of C Language In 1972,

More information

C Functions. 5.2 Program Modules in C

C Functions. 5.2 Program Modules in C 1 5 C Functions 5.2 Program Modules in C 2 Functions Modules in C Programs combine user-defined functions with library functions - C standard library has a wide variety of functions Function calls Invoking

More information

Programming in C Quick Start! Biostatistics 615 Lecture 4

Programming in C Quick Start! Biostatistics 615 Lecture 4 Programming in C Quick Start! Biostatistics 615 Lecture 4 Last Lecture Analysis of Algorithms Empirical Analysis Mathematical Analysis Big-Oh notation Today Basics of programming in C Syntax of C programs

More information

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

Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries Hazırlayan Asst. Prof. Dr. Tansu Filik Computer Programming Previously on Bil 200 Low-Level I/O getchar, putchar,

More information

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

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Lecture 9 Functions Dr M Kasim A Jalil Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Objectives In this chapter, you will learn: To understand how to construct programs modularly

More information

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

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from INTRODUCTION TO C++ FUNCTIONS Original slides are from http://sites.google.com/site/progntut/ Dept. of Electronic Engineering, NCHU Outline 2 Functions: Program modules in C Function Definitions Function

More information

ANSI C Programming Simple Programs

ANSI C Programming Simple Programs ANSI C Programming Simple Programs /* This program computes the distance between two points */ #include #include #include main() { /* Declare and initialize variables */ double

More information

CSE123. Program Design and Modular Programming Functions 1-1

CSE123. Program Design and Modular Programming Functions 1-1 CSE123 Program Design and Modular Programming Functions 1-1 5.1 Introduction A function in C is a small sub-program performs a particular task, supports the concept of modular programming design techniques.

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Lecture 4 Input & Output Lecturer : Ebrahim Jahandar Borrowed from lecturer notes by Omid Jafarinezhad Outline printf scanf putchar getchar getch getche Input and Output in

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi CE 43 - Fall 97 Lecture 4 Input and Output Department of Computer Engineering Outline printf

More information

Calling Prewritten Functions in C

Calling Prewritten Functions in C Calling Prewritten Functions in C We've already called two prewritten functions that are found in the C library stdio.h: printf, scanf. The function specifications for these two are complicated (they allow

More information

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

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4 BIL 104E Introduction to Scientific and Engineering Computing Lecture 4 Introduction Divide and Conquer Construct a program from smaller pieces or components These smaller pieces are called modules Functions

More information

Preview from Notesale.co.uk Page 2 of 79

Preview from Notesale.co.uk Page 2 of 79 COMPUTER PROGRAMMING TUTORIAL by tutorialspoint.com Page 2 of 79 tutorialspoint.com i CHAPTER 3 Programming - Environment Though Environment Setup is not an element of any Programming Language, it is the

More information

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

بسم اهلل الرمحن الرحيم بسم اهلل الرمحن الرحيم Fundamentals of Programming C Session # 10 By: Saeed Haratian Fall 2015 Outlines Examples Using the for Statement switch Multiple-Selection Statement do while Repetition Statement

More information

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

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University ITC213: STRUCTURED PROGRAMMING Bhaskar Shrestha National College of Computer Studies Tribhuvan University Lecture 07: Data Input and Output Readings: Chapter 4 Input /Output Operations A program needs

More information

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

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

More information

Structured Programming. Dr. Mohamed Khedr Lecture 4

Structured Programming. Dr. Mohamed Khedr Lecture 4 Structured Programming Dr. Mohamed Khedr http://webmail.aast.edu/~khedr 1 Scientific Notation for floats 2.7E4 means 2.7 x 10 4 = 2.7000 = 27000.0 2.7E-4 means 2.7 x 10-4 = 0002.7 = 0.00027 2 Output Formatting

More information

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

Assoc. Prof. Dr. Tansu FİLİK Assoc. Prof. Dr. Tansu FİLİK Computer Programming Previously on Bil 200 Midterm Exam - 1 Midterm Exam - 1 126 students Curve: 49,78 Computer Programming Arrays Arrays List of variables: [ ] Computer Programming

More information

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

LESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long LESSON 5 ARITHMETIC DATA PROCESSING The arithmetic data types are the fundamental data types of the C language. They are called "arithmetic" because operations such as addition and multiplication can be

More information

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

sends the formatted data to the standard output stream (stdout) int printf ( format_string, argument_1, argument_2,... ) ; INPUT AND OUTPUT IN C Function: printf() library: sends the formatted data to the standard output stream (stdout) int printf ( format_string, argument_1, argument_2,... ) ; format_string it is

More information

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

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been

More information

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

IECD Institute for Entrepreneurship and Career Development Bharathidasan University, Tiruchirappalli 23. Subject code - CCP01 Chapt Chapter 1 INTRODUCTION TO C 1. A group of software developed for certain purpose are referred as ---- a. Program b. Variable c. Software d. Data 2. Software is classified into

More information

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

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University Lesson #3 Variables, Operators, and Expressions Variables We already know the three main types of variables in C: int, char, and double. There is also the float type which is similar to double with only

More information

Computer Science & Engineering 150A Problem Solving Using Computers

Computer Science & Engineering 150A Problem Solving Using Computers Computer Science & Engineering 150A Problem Solving Using Computers Lecture 03 - Stephen Scott (Adapted from Christopher M. Bourke) 1 / 41 Fall 2009 Chapter 3 3.1 Building Programs from Existing Information

More information

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

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University Fundamental Data Types CSE 130: Introduction to Programming in C Stony Brook University Program Organization in C The C System C consists of several parts: The C language The preprocessor The compiler

More information

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

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions Computer Science & Engineering 150A Problem Solving Using Computers Lecture 03 - Functions Stephen Scott (Adapted from Christopher M. Bourke) Fall 2009 1 / 1 cbourke@cse.unl.edu Chapter 3 3.1 Building

More information

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

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University C Programming Notes Dr. Karne Towson University Reference for C http://www.cplusplus.com/reference/ Main Program #include main() printf( Hello ); Comments: /* comment */ //comment 1 Data Types

More information

Chapter 2. Outline. Simple C++ Programs

Chapter 2. Outline. Simple C++ Programs Chapter 2 Simple C++ Programs Outline Objectives 1. Building C++ Solutions with IDEs: Dev-cpp, Xcode 2. C++ Program Structure 3. Constant and Variables 4. C++ Operators 5. Standard Input and Output 6.

More information

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

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. C How to Program, 6/e 1992-2010 by Pearson Education, Inc. An important part of the solution to any problem is the presentation of the results. In this chapter, we discuss in depth the formatting features

More information

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

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University AN OVERVIEW OF C, PART 3 CSE 130: Introduction to Programming in C Stony Brook University FANCIER OUTPUT FORMATTING Recall that you can insert a text field width value into a printf() format specifier:

More information

Lecture 2:- Functions. Introduction

Lecture 2:- Functions. Introduction Lecture 2:- Functions Introduction A function groups a number of program statements into a unit and gives it a name. This unit can then be invoked from other parts of the program. The most important reason

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

Primitive Data Types: Intro

Primitive Data Types: Intro Primitive Data Types: Intro Primitive data types represent single values and are built into a language Java primitive numeric data types: 1. Integral types (a) byte (b) int (c) short (d) long 2. Real types

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number

More information

1001ICT Introduction To Programming Lecture Notes

1001ICT Introduction To Programming Lecture Notes 1001ICT Introduction To Programming Lecture Notes School of Information and Communication Technology Griffith University Semester 1, 2015 1 M Environment console M.1 Purpose This environment supports programming

More information

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

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

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

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

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code CS102: Standard I/O Our next topic is standard input and standard output in C. The adjective "standard" when applied to "input" or "output" could be interpreted to mean "default". Typically, standard output

More information

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

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University Overview of C, Part 2 CSE 130: Introduction to Programming in C Stony Brook University Integer Arithmetic in C Addition, subtraction, and multiplication work as you would expect Division (/) returns the

More information

Standard I/O in C and C++

Standard I/O in C and C++ Introduction to Computer and Program Design Lesson 7 Standard I/O in C and C++ James C.C. Cheng Department of Computer Science National Chiao Tung University Standard I/O in C There three I/O memory buffers

More information

Fundamentals of Computer Programming Using C

Fundamentals of Computer Programming Using C CHARUTAR VIDYA MANDAL S SEMCOM Vallabh Vidyanagar Faculty Name: Ami D. Trivedi Class: FYBCA Subject: US01CBCA01 (Fundamentals of Computer Programming Using C) *UNIT 3 (Structured Programming, Library Functions

More information

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

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 5. Playing with Data Modifiers and Math Functions Getting Controls Readin from and Writint to Standart I/O BIL104E: Introduction to Scientific and Engineering Computing Lecture 5 Playing with Data Modifiers and Math Functions Getting Controls Pointers What Is a Pointer?

More information

Computers Programming Course 7. Iulian Năstac

Computers Programming Course 7. Iulian Năstac Computers Programming Course 7 Iulian Năstac Recap from previous course Operators in C Programming languages typically support a set of operators, which differ in the calling of syntax and/or the argument

More information

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

Chapter 3. Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus. Existing Information. Chapter 3 Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus Lecture 03 - Introduction To Functions Christopher M. Bourke cbourke@cse.unl.edu 3.1 Building Programs from Existing

More information

Computers Programming Course 5. Iulian Năstac

Computers Programming Course 5. Iulian Năstac Computers Programming Course 5 Iulian Năstac Recap from previous course Classification of the programming languages High level (Ada, Pascal, Fortran, etc.) programming languages with strong abstraction

More information

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

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 18 I/O in C Standard C Library I/O commands are not included as part of the C language. Instead, they are part of the Standard C Library. A collection of functions and macros that must be implemented

More information

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

These are reserved words of the C language. For example int, float, if, else, for, while etc. Tokens in C Keywords These are reserved words of the C language. For example int, float, if, else, for, while etc. Identifiers An Identifier is a sequence of letters and digits, but must start with a letter.

More information

Fundamentals of Programming & Procedural Programming

Fundamentals of Programming & Procedural Programming Universität Duisburg-Essen PRACTICAL TRAINING TO THE LECTURE Fundamentals of Programming & Procedural Programming Session Eight: Math Functions, Linked Lists, and Binary Trees Name: First Name: Tutor:

More information

C Programming

C Programming 204216 -- C Programming Chapter 3 Processing and Interactive Input Adapted/Assembled for 204216 by Areerat Trongratsameethong A First Book of ANSI C, Fourth Edition Objectives Assignment Mathematical Library

More information

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

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan. Functions Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2009 Fall Outline 5.1 Introduction 5.3 Math Library Functions 5.4 Functions 5.5

More information

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

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming. Programming Fundamentals for Engineers - 0702113 7. Functions Muntaser Abulafi Yacoub Sabatin Omar Qaraeen 1 Modular programming Your program main() function Calls AnotherFunction1() Returns the results

More information

Reserved Words and Identifiers

Reserved Words and Identifiers 1 Programming in C Reserved Words and Identifiers Reserved word Word that has a specific meaning in C Ex: int, return Identifier Word used to name and refer to a data element or object manipulated by the

More information

Built-in Types of Data

Built-in Types of Data Built-in Types of Data Types A data type is set of values and a set of operations defined on those values Python supports several built-in data types: int (for integers), float (for floating-point numbers),

More information

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.

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. Chapter-12 FUNCTIONS Introduction 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. Types of functions There are two types

More information

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

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 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 Header files: stdio.h conio.h C input/output revolves around

More information

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

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered )   FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING ( Word to PDF Converter - Unregistered ) http://www.word-to-pdf-converter.net FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING INTRODUCTION TO C UNIT IV Overview of C Constants, Variables and Data Types

More information

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

INTRODUCTION TO C++ C FORMATTED INPUT/OUTPUT. Dept. of Electronic Engineering, NCHU. Original slides are from INTRODUCTION TO C++ C FORMATTED INPUT/OUTPUT Original slides are from http://sites.google.com/site/progntut/ Dept. of Electronic Engineering, NCHU Outline 2 printf and scanf Streams (input and output)

More information

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

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

More information

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

n Group of statements that are executed repeatedly while some condition remains true Looping 1 Loops n Group of statements that are executed repeatedly while some condition remains true n Each execution of the group of statements is called an iteration of the loop 2 Example counter 1,

More information

Course Outline Introduction to C-Programming

Course Outline Introduction to C-Programming ECE3411 Fall 2015 Lecture 1a. Course Outline Introduction to C-Programming Marten van Dijk, Syed Kamran Haider Department of Electrical & Computer Engineering University of Connecticut Email: {vandijk,

More information

THE FUNDAMENTAL DATA TYPES

THE FUNDAMENTAL DATA TYPES THE FUNDAMENTAL DATA TYPES Declarations, Expressions, and Assignments Variables and constants are the objects that a prog. manipulates. All variables must be declared before they can be used. #include

More information

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs PDS Lab Section 16 Autumn-2017 Tutorial 3 C Programming Constructs This flowchart shows how to find the roots of a Quadratic equation Ax 2 +Bx+C = 0 Start Input A,B,C x B 2 4AC False x If 0 True B x 2A

More information

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

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee C Language Part 1 (Minor modifications by the instructor) References C for Python Programmers, by Carl Burch, 2011. http://www.toves.org/books/cpy/ The C Programming Language. 2nd ed., Kernighan, Brian,

More information

Engineering Problem Solving with C++, Etter/Ingber

Engineering Problem Solving with C++, Etter/Ingber Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs C++, Second Edition, J. Ingber 1 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input

More information

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

Outline. Computer Programming. Preprocessing in C. File inclusion. Preprocessing in C Outline Computer Programming The greatest gift you can give another is the purity of your attention. Richard Moss Preprocessing in C Function vs macro Conditional compilation Constant identifiers Standard

More information

Lecture 04 FUNCTIONS AND ARRAYS

Lecture 04 FUNCTIONS AND ARRAYS Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions

More information

Multiple Choice Questions ( 1 mark)

Multiple Choice Questions ( 1 mark) Multiple Choice Questions ( 1 mark) Unit-1 1. is a step by step approach to solve any problem.. a) Process b) Programming Language c) Algorithm d) Compiler 2. The process of walking through a program s

More information

Lecture 9 - C Functions

Lecture 9 - C Functions ECET 264 C Programming Language with Applications Lecture 9 C Functions Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin Lecture 9- Prof. Paul I. Lin

More information

Chapter 7. Basic Types

Chapter 7. Basic Types Chapter 7 Basic Types Dr. D. J. Jackson Lecture 7-1 Basic Types C s basic (built-in) types: Integer types, including long integers, short integers, and unsigned integers Floating types (float, double,

More information

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

The C Programming Language Part 2. (with material from Dr. Bin Ren, William & Mary Computer Science) The C Programming Language Part 2 (with material from Dr. Bin Ren, William & Mary Computer Science) 1 Overview Input/Output Structures and Arrays 2 Basic I/O character-based putchar (c) output getchar

More information

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

Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011 Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011 Autumn 2015 Lecture 3, Simple C programming M. Eriksson (with contributions from A. Maki and

More information

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

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed C Overview C OVERVIEW Goals speed portability allow access to features of the architecture speed C fast executables allows high-level structure without losing access to machine features many popular languages

More information

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

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

More information

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

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure C Overview Basic C Program Structure C OVERVIEW BASIC C PROGRAM STRUCTURE Goals The function main( )is found in every C program and is where every C program begins speed execution portability C uses braces

More information

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions C++ PROGRAMMING SKILLS Part 3 User-Defined Functions Introduction Function Definition Void function Global Vs Local variables Random Number Generator Recursion Function Overloading Sample Code 1 Functions

More information

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

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU CSE101-lec#12 Designing Structured Programs Introduction to Functions Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU Outline Designing structured programs in C: Counter-controlled repetition

More information

Data types, variables, constants

Data types, variables, constants Data types, variables, constants Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers 2.4 Memory Concepts 2.5 Arithmetic in C 2.6 Decision

More information

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

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants Data types, variables, constants Outline.1 Introduction. Text.3 Memory Concepts.4 Naming Convention of Variables.5 Arithmetic in C.6 Type Conversion Definition: Computer Program A Computer program is a

More information

UNIT-I Input/ Output functions and other library functions

UNIT-I Input/ Output functions and other library functions Input and Output functions UNIT-I Input/ Output functions and other library functions All the input/output operations are carried out through function calls. There exists several functions that become

More information

2. Numbers In, Numbers Out

2. Numbers In, Numbers Out COMP1917: Computing 1 2. Numbers In, Numbers Out Reading: Moffat, Chapter 2. COMP1917 15s2 2. Numbers In, Numbers Out 1 The Art of Programming Think about the problem Write down a proposed solution Break

More information

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

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords. Chapter 1 File Extensions: Source code (cpp), Object code (obj), and Executable code (exe). Preprocessor processes directives and produces modified source Compiler takes modified source and produces object

More information

Fundamentals of Programming Session 8

Fundamentals of Programming Session 8 Fundamentals of Programming Session 8 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

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

The cin Object. cout << Enter the length and the width of the rectangle? ; cin >> length >> width; The cin Object Short for console input. It is used to read data typed at the keyboard. Must include the iostream library. When this instruction is executed, it waits for the user to type, it reads the

More information

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

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3). cs3157: another C lecture (mon-21-feb-2005) C pre-processor (1). today: C pre-processor command-line arguments more on data types and operators: booleans in C logical and bitwise operators type conversion

More information

9 C Language Function Block

9 C Language Function Block 9 C Language Function Block In this chapter, we focus on C language function block s specifications, edition, instruction calling, application points etc. we also attach the common Function list. 9-1.Functions

More information

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

C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee C Language Part 2 (Minor modifications by the instructor) 1 Scope Rules A variable declared inside a function is a local variable Each local variable in a function comes into existence when the function

More information

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

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010 CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011 Lectures 1-22 Moaaz Siddiq Asad Ali Latest Mcqs MIDTERM EXAMINATION Spring 2010 Question No: 1 ( Marks: 1 ) - Please

More information

Standard Library Functions Outline

Standard Library Functions Outline Standard Library Functions Outline 1. Standard Library Functions Outline 2. Functions in Mathematics #1 3. Functions in Mathematics #2 4. Functions in Mathematics #3 5. Function Argument 6. Absolute Value

More information

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

Pointers cause EVERYBODY problems at some time or another. char x[10] or char y[8][10] or char z[9][9][9] etc. Compound Statements So far, we ve mentioned statements or expressions, often we want to perform several in an selection or repetition. In those cases we group statements with braces: i.e. statement; statement;

More information