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 6 - P. Lin 1 Lecture 6 Control Structures and Operators Review Nested Control Structures Example 1: Nested Control Structures Example 2: Testing ASCII Characters Example 3: Counting Various ASCII Characters More C Operators Bit-wise operators: AND, OR, NOT, EX-OR Truth Tables Example 4: Bit-Operations Example 5: Clear Memory Locations Using EX-OR Operations Conditional Operators Sizeof Operator Example 6: Sizeof Example Example 7: Char and Character Array Size Address and Indirection Operators Example 8: Address Operator and Pointers Summary Lecture 6 - P. Lin 2 1
Example 1 Nested Control Structures Problem Statement Write a C program to produce a summary of the exam results for ten students using nested control structures. If more than 8 students pass, a message of raising tuition is displayed. Analysis Need to include <stdio.h> Read input one at a time (1 passed, 2 failed) Use WHILE control structure Needs two or three counters? Output To display each exam entered, the results, and a message of raising tuition when more than 8 students passed. Lecture 6 - P. Lin 3 Example 1 (continue) Nested Control Structures Formulating Algorithm: Analyze student s exam results and decide if tuition should be raised Define and initialize variables: COUNTERS: passed, failed, student result Input the exam results, count passes and failures while the counter is not exceed 10 Input the next exam result If the student passed, add one to passed COUNTER else add one to failed COUNTER add one to the student COUNTER Print a summary of the exam, and include a message Raise tuition if more than 8 students is passed Lecture 6 - P. Lin 4 2
Example 1 (continue) Nested Control Structures /* Analysis of examination results */ #include <stdio.h> /* function main begins program execution */ int main() { /* initialize variables in definitions */ int passes = 0; /* number of passes */ int failures = 0; /* number of failures */ int student = 1; /* student counter */ int result; /* one exam result */ /* process 10 students using counter-controlled loop */ while (student <= 10) {/* prompt user for input and obtain value fom user */ printf("enter result (1=pass,2=fail): " ); scanf( "%d", &result ); Lecture 6 - P. Lin 5 Example 1 (continue) Nested Control Structures /* if result 1, increment passes */ if ( result == 1 ) { passes = passes + 1; /* end if */ else { /* otherwise, increment failures */ failures = failures + 1; /* end else */ student = student + 1; /*increment student counter */ /* end while */ /* termination phase; display number of passes and failures */ printf( "Passed %d\n", passes ); printf( "Failed %d\n", failures ); Lecture 6 - P. Lin 6 3
Example 1 (continue) Nested Control Structures /* if more than eight students passed, print "raise tuition" */ if ( passes > 8 ) { printf( "Raise tuition\n" ); /* end if */ return 0; /* indicate program ended successfully */ /* end function main */ Lecture 6 - P. Lin 7 Example 1 (continue) Nested Control Structures Lecture 6 - P. Lin 8 4
Example 1 (continue) Nested Control Structures Lecture 6 - P. Lin 9 Example 2 Testing ASCII Characters /* if3.c - Char Class Testing - Testing various ASCII character classes. */ #include <stdio.h> #include <ctype.h> static char s[] = "1aBY4*$%"; /* Character array s[] contains the following characters: l, a, B, Y, 4, *, $, %,, and \0 which is the EOS (End of String Character) */ 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"); Lecture 6 - P. Lin 10 5
Example 2 (continue) Testing ASCII Characters if(isgraph(c)) { printf("%c = ",c); puts("printable"); if(isdigit(c)) { printf("%c = ",c); puts("digit"); if(c % 2 == 0) puts("even number"); Lecture 6 - P. Lin 11 Example 2 (continue) Testing ASCII Characters Lecture 6 - P. Lin 12 6
Example 3 Counting Various ASCII Characters /* 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; Lecture 6 - P. Lin 13 Example 3 (continue) Counting Various ASCII Characters puts( Please continue to enter from keyboard; Enter Ctrl Z to exit the loop ); 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); Lecture 6 - P. Lin 14 7
Example 3 (continue) Counting Various ASCII Characters Output: Please continue to enter from keyboard; Enter Ctrl Z to exit the loop 1234 testing testing <Enter> key ^Z blanks = 2 digits = 4 newlines = 1 letters = 14 others = 0Press any key to continue Lecture 6 - P. Lin 15 Bit-wise operators: &,, ^, ~, >>, Bitwise data manipulations are machine dependent Conditional Operators exp1? exp2: exp3; For example (x > 0)? puts( X is positive\n ): puts( X is negative ); Sizeof operator Sizeof(short) is 2byte Sizeof(int) is 4 bytes More C Operators Address operator & address operator for reference to variable directly Lecture 6 - P. Lin 16 8
It works with character and unsigned integer types Bit-wise Operators Applications: Windows operators, computer circuit simulation, digital circuit operations, etc. Operator Meaning & Two input AND gate operation Two input OR gate operation ^ Two input Ex-OR gate operation ~ Complement (NOT) or inverter >> Shift variable s content to the right << Shift variable s content to the left Lecture 6 - P. Lin 17 Truth Tables Input Outputs A B A & B A B A ^B --------------------------------------- 0 0 0 0 0 0 1 0 1 1 1 0 0 1 1 1 1 1 1 0 AND OR EX-OR Lecture 6 - P. Lin 18 9
Bit-wise Operators (continue) Bit-Wise AND Example: If we define bit, b, and c as a unsigned character variables: unsigned char b = 0x2F, c = 0xF3, bit; bit = b & c; /* bit = 0x23 */ In terms of binary numbers: b = 0010 1111 AND & c = 1111 0011 -------------- bit = 0010 0011 Lecture 6 - P. Lin 19 Bit-wise Operators (continue) Bit-wise OR example: unsigned char b = 0x2F, c = 0xF3, bit; bit = b c; /* bit = 0xFF */ In terms of binary numbers: b = 0010 1111 (OR) c = 1111 0011 ---------------------- bit = 1111 1111 Lecture 6 - P. Lin 20 10
Bit-wise Operators (continue) Bit-wise EXOR example: unsigned char b = 0x2F, c = 0xF3, bit; bit = b ^ c; /* bit = 0xDC */ In terms of binary numbers: b = 0010 1111 EXOR ^ c = 1111 0011 --------------- bit = 1101 1100 It is no surprise to see b = b ^ b = 0x00 Lecture 6 - P. Lin 21 Bit-wise Operators (continue) Operator Meaning Example &= bit-wised AND and assign b &= 0x01; b = b & 0x01; = bit-wised OR and assign b = 0x0E; b = b 0x0E; ^= bit-wised EX-OR and assign b ^= a; b =b^ a; Lecture 6 - P. Lin 22 11
Example 4: Bit-Operations /* bit_wised_ops.c */ #include <stdio.h> void main() { unsigned short A_in1 = 1, A_in2 = 0, A_out; unsigned short O_in1 = 1, O_in2 = 0, O_out; unsigned short exor_in1 = 1, exor_in2 = 0, exor_out; unsigned short register1 = 0x0001, register2 = 0x1000; // Not Gate (Inverter) printf("a_in2 = %x\n", A_in2); printf("~a_in2 = %x\n", ~A_in2); // No bit masking A_in2 = 1; printf("a_in2 = %x\n", A_in2); A_in2 = ~A_in2; printf("~a_in2 = %x\n", A_in2); // Masking off bit 15-bit0 A_in2 &= 0x0001; printf("after Maksing: ~A_in2 = %x\n", A_in2); // AND Gate A_out = A_in1 & A_in2; // 2- input AND gate printf("%x & %x = A_out = %x\n", A_in1, A_in2, A_out); printf("\ntruth Table - 2 input AND Gate\n"); printf("--------------------------------- \n"); printf("0 & 0 = %x\n", 0 & 0); printf("0 & 1 = %x\n", 0 & 1); printf("1 & 0 = %x\n", 1 & 0); printf("1 & 1 = %x\n", 1 & 1); Lecture 6 - P. Lin 23 Example 4 Bit-Operations (continue) // OR Gate O_out = O_in1 & O_in2; // 2- input OR gate printf("%x %x = O_out = %x\n", O_in1, O_in2, O_out); printf("\ntruth Table - 2 input OR Gate\n"); printf("--------------------------------- \n"); printf("0 0 = %x\n", 0 0); printf("0 1 = %x\n", 0 1); printf("1 0 = %x\n", 1 0); printf("1 1 = %x\n", 1 1); // EXOR printf("\ntruth Table - 2 input EX-OR Gate\n"); printf("------------------------------- --\n"); printf("0 ^ 0 = %x\n", 0 ^ 0); printf("0 ^ 1 = %x\n", 0 ^ 1); printf("1 ^ 0 = %x\n", 1 ^ 0); printf("1 ^ 1 = %x\n", 1 ^ 1); /* end of main */ Lecture 6 - P. Lin 24 12
Example 4 Bit-Operations (continue) Output A_in2 = 0 ~A_in2 = ffffffff A_in2 = 1 ~A_in2 = fffe After Maksing: ~A_in2 = 0 1 & 0 = A_out = 0 Truth Table - 2 input AND Gate --------------------------------- 0 & 0 = 0 0 & 1 = 0 1 & 0 = 0 1 & 1 = 1 1 0 = O_out = 0 Truth Table - 2 input OR Gate --------------------------------- 0 0 = 0 0 1 = 1 1 0 = 1 1 1 = 1 Truth Table - 2 input EX-OR Gate --------------------------------- 0 ^ 0 = 0 0 ^ 1 = 1 1 ^ 0 = 1 1 ^ 1 = 0 Press any key to continue Lecture 6 - P. Lin 25 Example 5 Clear Memory Locations Problem Statement Write a C program to show all possible methods of clearing or resetting integer type numerical variables Analysis Possible integer type numerical variables including char, short, int, and long Analysis (cont.) Memory clearing or resetting methods may include, for example: unsigned short n = 0xFFFF; //or 65535 Method 1, assign zero n = 0; Method 2, subtraction n = n - n; Method 3, using Exclusive OR n ^=n; Lecture 6 - P. Lin 26 13
Example 5 Clear Memory Locations (continue) /* bit_exor_clearm.c */ #include <stdio.h> void main() { unsigned short n1 = 0xFFFF; // 65535 unsigned short n2 = 0x1000; // 4096 unsigned short n3 = 0x0100; // 256 printf("original unsigned short n1 = %d\n", n1); printf("original unsigned short n2 = %d\n", n2); printf("original unsigned short n3 = %d\n", n3); // Method 1 n1 = 0; // Method 2 n2 = n2 - n2; // or n2 -= n2; // Method 3 n3 ^= n3; // or n3 = n3 ^ n3; printf("cleared: unsigned short n1 = %x\n", n1); printf("cleared: unsigned short n2 = %x\n", n2); printf("cleared: unsigned short n3 = %x\n", n3); /* End of main */ OUTPUT Original: unsigned short n1 = 65535 Original: unsigned short n2 = 4096 Original: unsigned short n3 = 256 Cleared: unsigned short n1 = 0 Cleared: unsigned short n2 = 0 Cleared: unsigned short n3 = 0 Press any key to continue Lecture 6 - P. Lin 27 Conditional Operators High-level language: if (a > b) max=a; else max =b; Conditional Operator: exp1? Exp2: exp3; Lecture 6 - P. Lin 28 14
Conditional Operators (continue) Examples: int a = 10, b = -10; max = (a > b)? a: b; /* max = 10*/ min = (a < b)? a: b; /* min = -10 */ v = (5)? 1: 2; // 5 is non-zero, true; v = 1 v = (0)? 1: 2; // 0 is zero, false; v = 2 Lecture 6 - P. Lin 29 sizeof Operator sizeof operator is a unary operator to find the number of bytes for storing the value of a variable in the memory Examples Len = sizeof(short); /* Len= 2, or 2 bytes */ Len = sizeof (n);/ * Len = 4, if n is a 32-bit integer */ Applications: CPU size checking Dynamic memory allocation at run time Data record size calculation etc Lecture 6 - P. Lin 30 15
Example 6 sizeof Problem Statement You are asked to write a simple C program to check the sizes of C data types, including char, short, int, long, float, and double. Analysis sizeof() and printf() functions are needed Correct data type names will be needed Lecture 6 - P. Lin 31 Example 6 (continue) sizeof The program that tell us the sizes of requested data types. /* sizeof_check.c */ #include <stdio.h> void main() { printf("sizeof(char) = %d Bytes\n", sizeof(char)); printf("sizeof(short) = %d Bytes\n", sizeof(short)); printf("sizeof(int) = %d Bytes\n", sizeof(int)); printf("sizeof(long) = %d Bytes\n", sizeof(long)); printf("sizeof(float) = %d Bytes\n", sizeof(float)); printf("sizeof(double) = %d Bytes\n", sizeof(double)); Lecture 6 - P. Lin 32 16
Output Example 6 (continue) sizeof sizeof(char) = 1 Bytes sizeof(short) = 2 Bytes sizeof(int) = 4 Bytes sizeof(long) = 4 Bytes sizeof(float) = 4 Bytes sizeof(double) = 8 Bytes Lecture 6 - P. Lin 33 Example 7 Char and Character Array Size Problem Statement: Write a program that shows and prints the size of a character and a character array. The sizeof operator should be used to evaluate the size of variables or objects and it return a number with the unit of bytes. Output Requirement The output of the program should be textbased, with heading info, and actual byte size for user. Lecture 6 - P. Lin 34 17
Example 7 (continue) Char and Character Array Size Analysis This program will be written using Microsoft Visual C++ 2008 and for running under DOS virtual machine Testing Data We will use the following data for testing: A char variable which contains a character T, and a character array which contains a string T which contains two characters, namely, T and a null character \0. Format Specifiers: %c for printing signal character %d -- for printing a decimal number %s -- for printing a string of characters Lecture 6 - P. Lin 35 Example 7 (continue) Char and Character Array Size /* charstr.c */ #include <stdio.h> void main() { char ch = 'T'; /*Define a single character variable ch*/ /*Evaluate the size of character type variable ch*/ /*The ch variable is a local variable within the main()*/ printf("sizeof(ch) = %d\n", sizeof(ch)); /* Evaluate the size of a string constant "T"*/ printf("%s\n", "T"); Lecture 6 - P. Lin 36 18
Example 7 (continue) Char and Character Array Size /*To display a double quote, a back slash is needed*/ /*Because a pair of double quote is used to enclose*/ /* the format string in the printf() function */ printf("sizeof(\"t\") = %d\n",sizeof("t")); Output: sizeof(ch) = 1 T sizeof( T") = 2 Lecture 6 - P. Lin 37 Address and Indirection Operators & Obtain address of a variable * Access the contents of a memory (using pointer or indirection) Examples: int a = 10; int *ptr; /* define a pointer variable called ptr of pointer type */ ptr = &a; /* assign the address of a variable to pointer ptr */ (*ptr)++; /* Access memory directory using pointer variable, a = 11 after this line */ Lecture 6 - P. Lin 38 19
Example 8 Address Operator and Pointers /* pointer1.c - This program explains how to use address operator and pointers. */ #include <stdio.h> void main() { int a = 10; int *ptr; /*A variable that holds the address of another r variable */ ptr = &a; printf("a = %d\n", a); printf("(*ptr) = %d\n", (*ptr)); (*ptr)++; printf("(*ptr)++ = %d\n", (*ptr)); printf("&a = %x\n", &a); printf("ptr = %x\n", ptr); Lecture 6 - P. Lin 39 Example 9 8 (continue) Address Operator and Pointers Lecture 6 - P. Lin 40 20
Summary Review Nested Control Structures More C Operators Bit-wise operators Conditional Operators sizeof operator Address operator C Examples Next More C Program Control Lecture 6 - P. Lin 41 Question? Answers lin@ipfw.edu Lecture 6 - P. Lin 42 21