1.64k likes | 1.84k Views
Composed for SE 115 C programming Faculty of Engineering & Computer Sciences Izmir University of Economics. Assoc. Prof. Dr. Süleyman Kondakci Suleyman.kondakci@ieu.edu.tr http://homes.ieu.edu.tr/skondakci. Summary of C Operations. Arithmetic : int i = i+1; i++; i--; i *= 2;
E N D
Composed for SE 115 C programmingFaculty of Engineering & Computer Sciences Izmir University of Economics Assoc. Prof. Dr. Süleyman Kondakci Suleyman.kondakci@ieu.edu.tr http://homes.ieu.edu.tr/skondakci
Summary of C Operations • Arithmetic: • int i = i+1; i++; i--; i *= 2; • +, -, *, /, %, • Relational and Logical: • <, >, <=, >=, ==, != • &&, ||, &, |, ! • Flow Control: • if ( ) { } else { } • while ( ) { } • do { } while ( ); • for(i=1; i <= 100; i++) { } • switch ( ) {case 1: … } • continue; break;
Relational,equality, and logical operators Relational Operator: Less than: < Greater than: > Less than or equal: <= Greater than or equal: >=
Equality and Logical Operators EqualityOperators: Equal: == Not equal: != Logical Operators: Negation: ! Logical and: && Logical or: ||
Example: Conditional Operators int main() { int x=0, y=10, w=20, z, T=1, F=0; z = (x == 0); /*** logical operator; result --> 0 or 1 ***/ z = (x = 0); /*** assignment operator; result --> ***/ z = (x == 1); z = (x = 15); z = (x != 2); z = (x < 10); z = (x <= 50); z = ((x=y) < 10); /*** performs assignment, compares with 10 ***/ z = (x==5 && y<15); z = (x==5 && y>5 && w==10); z = (x==5 || y>5 && w==10); z = (T && T && F && x && x); /*** ==> F; ***/ z = (F || T || x || x); /*** ==> T; ***/ /*** value of x doesn't matter ***/ return 0; }
Input to & Output From Program Input: scanf ("format specifier", variable) Output: printf ("format specifier", variable) Format specifiers %c = as a character %d = as a decimal integer %e = as a floating-point number in scientififc notation %f = as a floating-point number %g = in the e-format or f-format, whichever is shorter %s = as a string of characters
Small Sample Programs /*hello.c - traditional zeroeth program*/ #include <stdio.h> int main() { printf("Hello world!\n"); return 0; } On the screen Hello world!
\a \f \b bell backspace formfeed \\ \v \t horizontal tab vertical tab backslash \' \" \ooo single quote double quote octal number \xhh \? \n newline question mark hexadecimal number \r carriage return Escape Sequences Escaped characters produce visual and audible effects
Character Argument Type; Printed As d, I int; decimal number o int; unsigned octal number (without a leading zero) x, X int; unsigned hexadecimal number (without a leading Ox or OX, using abcdef or ABCDEF for 10,...,15) u int; unsigned decimal number c int; single character s char; print characters from the string until a '\0' or the number of charachters given by the precision f double; [-]m.dddddd, where the number of d's is given by the precision (default is 6) e, E double; [-]m.dddddde ± xx or [-]m.ddddddE ± xx where the number of d's is given by the precision (default is 6) g, G double; use %e or %E if the exponent is less than -4 or greater than or equal to the precision; otherwise use %f; trailing zeros and a trailing decimal point are not printed p void *; pointer (implementation-dependent representation) % no argument is converted; print a % The Output Function (printf)
Character Input Data; Argument Type d decimal integer; int * I integer; int * ; the integer may be in octal (leading 0) or hexadecimal (leading 0x or 0X) o octal intger (with or without leading zero); int * u unsigned decimal integer; unsigned int * x hexadecimal number (with or without a leading 0x or 0X); int * c characters; char *. The next input characters (default 1) are placed at the indicated spot. The normal skip over white space is suppressed; to read the next non-white space character, use %1s s character string (not quoted); char * ; pointing to an array of characters large enough for the string and a terminating `\0' that will be added e, f, g floating-point number with optional sign, optional decimal point, and optional exponent; float * % literal %; no assignment is made The Input Function (scanf)
Small Sample Programs /*fahr.c (several versions) - convert Fahrenheit to Celsius. */ int main() { int fahr = 42, cels; cels = 5*(fahr-32)/9; printf("%d degrees Fahrenheit is %d degrees Celsius\n", fahr, cels); return 0; }
C Programming Control Structures
The if Statement The if statement has two forms: if(expression 1) statement1; else if (expression 2) statement 2; else statement 3
Nested if Statement if (expression) { if (expression) { statements if (expression) { statements } } } else { statements }
The ?: operator expression1?expression2:expression3 Same as if(expression1) expression2 else expression3
Example: The ? and : operators X = 12; y = (x < 5) ? 5 : 10; Same as if (x < 5) y = 5; else y = 10;
C Language Blocks and Styling single block { Statements } { { ... { } } } outer block inner block Multiple nested block structure
Example: Single Block for (i=0; i<=10; i++) { printf("index is: %d", i); } if (a == b && a <= c || c >0) printf("Aha!! \a\a"); You can aslo write like this: if (a == b && a <= c || c >0) { printf("Aha!!\a\a"); } Or if (a == b && a <= c || c >0) printf("Aha!!\a\a");
Example: Multiple (nested) Blocks int a=2; int b=30; int c=11; if(a==b){ if( b<=c && c >10){ c= a-b; while (a <=10) { printf("Value of a: %d", a); B = a*c; } a = a-1; } }else{ printf("That is all folks!"); }
Small Sample Programs /* Uses scanf() to get input */ /* Uses printf() to shw the result */ #include <stdio.h> int main() { int fahr, cels; printf("How many degrees? "); scanf("%d", &fahr); cels = 5*(fahr-32)/9; printf("%d degrees Fahrenheit is %d degrees Celsius\n", fahr, cels); return 0; }
Small Sample Programs /*same, but with reals instead of integers*/ #include <tdio.h> int main() { double fahr, cels; printf("How many degrees? "); scanf("%lf", &fahr); cels = 5.0*(fahr-32.0)/9.0; printf("%.3f degrees Fahrenheit is %.3f degrees Celsius\n", fahr, cels); return 0; }
Small Sample Programs /*fahrcels.c (several versions) - use a conditional statement to select one of two calculations.*/ #include <stdio.h> int main() { double fahr, cels; int unit; /*'C' for Celsius input, 'F' for Fahrenheit*/ /*get input type*/ printf("Type C to convert Celsius to Fahrenheit, or F to go the other way: "); unit = getchar(); /*get input, and do the appropriate calculation*/ printf("degrees? "); if(unit == 'C') { scanf("%lf", &cels); fahr = 9.0*cels/5.0+32.0; } else { scanf("%lf", &fahr); cels = 5.0*(fahr-32.0)/9.0; } printf("%.3f degrees Fahrenheit is %.3f degrees Celsius\n", fahr, cels); return 0; }
Small Sample Programs /*uses logical OR to handle lowercase*/ #include <stdio.h> int main(){ double fahr, cels; int unit; /*'C' for Celsius input, 'F' for Fahrenheit*/ /*get input type*/ printf("Type C to convert Celsius to Fahrenheit, or F to go the other way: "); unit = getchar(); /*get input, and do the appropriate calculation*/ printf("degrees? "); if((unit == 'C') || (unit == 'c')) { scanf("%lf", &cels); fahr = 9.0*cels/5.0+32.0; } else { scanf("%lf", &fahr); cels = 5.0*(fahr-32.0)/9.0; } printf("%.3f degrees Fahrenheit is %.3f degrees Celsius\n", fahr, cels); return 0; }
Small Sample Programs /*uses a conditional expression as well as a conditional statement*/ #include <stdio.h> #include <ctype.h> int main() { double fahr, cels; int unit; /*'C' for Celsius input, 'F' for Fahrenheit*/ /*get input type*/ printf("Type C to convert Celsius to Fahrenheit, or F to go the other way: "); unit = toupper(getchar()); /*get input, and do the appropriate calculation*/ printf("degrees? "); scanf("%lf", (unit=='C')? &cels: &fahr); if(unit == 'C') fahr = 9.0*cels/5.0+32.0; else cels = 5.0*(fahr-32.0)/9.0; printf("%.3f degrees Fahrenheit is %.3f degrees Celsius\n", fahr, cels); return 0; }
Small Sample Programs #include <stdio.h> #include <ctype.h> int main() { double fahr, cels; int unit; /*'C' for Celsius input, 'F' for Fahrenheit*/ /*get input type*/ printf("Type C to convert Celsius to Fahrenheit, or F to go the other way: "); unit = toupper(getchar()); /*get input, and do the appropriate calculation*/ printf("degrees? "); if(unit == 'C') { scanf("%lf", &cels); fahr = 9.0*cels/5.0+32.0; } else { scanf("%lf", &fahr); cels = 5.0*(fahr-32.0)/9.0; } printf("%.3f degrees Fahrenheit is %.3f degrees Celsius\n", fahr, cels); return 0; }
C Programming Loops (Iterations)
The for Loop Syntax for (initialize; check; update) { statements }
Example: forLoop #include <stdio.h> #include <stdlib.h> int main(){ int i; for(i = 0; i <= 10; i++){ // Inside the loop printf("loop count = %d\n", i); } // End of the loop return 0; }
The while Loop Syntax while(expression) Statement; Or like this! while(expression) { Statements }
Example: while Loop include <stdio.h> #include <stdlib.h> int main(){ int input_c; /* The Classic Bit */ while( (input_c = getchar()) != EOF){ printf("%c was read\n", input_c); } return 0; }
The do-while Loop Syntax do { statements } while(expression); while(expression) { statements }
Example: forand while Loops #include <stdio.h> #include <stdlib.h> int main(){ int i; i = 0; while(i <= 10){ printf("%d\n", i); i++; } return 0; } #include <stdio.h> #include <stdlib.h> int main(){ int i; for(i = 0; i <= 10; i++){ printf("%d\n", i); } return 0; }
Example: do-while Loop #include <stdio.h> #include <stdlib.h> int main(){ int i; i = 0; /* check */ do { printf("%d\n", i); /* increment i */ i++; } while(i <= 10); return 0; }
The switch Statement expression = some_value; /* can be the result of another expression or a user defined value. */ some_value can be const1, const2,..., const100 or else switch (expression){ case const1: statements ; break; case const2: statements; break; ... case const100: statements; break default: statements; break; }
Example: switch Statement #include <stdio.h> #include <stdlib.h> int main(){ int i; for(i = 0; i <= 3; i++){ switch(i){ case 1: printf("1 \n"); break; case 2: printf("2 \n"); break; case 3: printf("3 \n"); break; default: printf("default\n"); break; } } return 0; } #include <stdio.h> #include <stdlib.h> int main(){ int i; for(i = 0; i <= 3; i++){ if (i == 1) printf("1 \n"); else if (i == 2) printf("2 \n"); else if (== 3) printf("3 \n"); else printf("default\n"); } return 0; }
The break statemet #include <stdio.h> #include <stdlib.h> int main(){ int i; for(i = 0; i < 100000000; i++){ printf("Press s to stop"); if(getchar() == 's') break; printf("%d\n", i); } return 0; }
The continue Statement #include <stdio.h> int main(){ int i; for(i = -10; i < 10; i++){ if(i == 0 || i==6 || i == 9 ) // do not print 0, 6, and 9, continue with others continue; printf("%d \n", i); // Other statements ..... } return 0; }
C Programming Functions
If a program is too long Modularization – easier to code debug Code reuse Passing arguments to functions By value By reference Returning values from functions By value By reference Functions - why and how ?
Definition and Usage of Functions #include <stdio.h> #include <stdlib.h> /** function prototype declarations start here**/ int add(int a, int b); int GetPosinteger(void); // or just int GetPosinteger(); /** End of function prototype declarations **/ int main() { int x, y, z; x = GetPosinteger(); y = GetPosinteger(); printf("%d + %d = %d\n", x, y, add(x,y)); return 0; } int add(int a, int b){ return a+b; } int GetPosinteger(void) { int a; do { printf("Enter a positive integer: "); scanf("%d", &a); } while (a <= 0); return a; }
Functions are subprograms! • The syntax for declaring a function: • return-type function-name (argument declarations){local variable declarationsStatements • } • Signature (or prototype) of a function: • return-type function-name (argument list)
Void in void out voidprint_message(void) // Inputs are void! { // Here void means no input parameter and no return value printf("hello"); // No return } intadd(int a, int b) // We have two int inputs a & b { int sum; sum = a + b; return sum; // This is the output }
Functions – Call by Value • #include <stdio.h> • int sum(int a, int b); • /* function prototype at start of file */ • void main(void){ • int total = sum(4,5); /* call to the function */ • printf("The sum of 4 and 5 is %d", total); • } • int sum(int a, int b){ /* the function itself • - arguments passed by value*/ • return (a+b); /* return by value */ • }
Functions- Call by Reference(later!!) #include <stdio.h> /* function prototype at start of the code */ int sum(int *pa, int *pb); // Pointer references as input void main(void){ int a=4, b=5; int *ptr = &b; int total; total = sum(&a,ptr); /* call to the function */ printf("The sum of 4 and 5 is %d", total); } int sum(int *pa, int *pb){ /* the function definition here - arguments passed by reference */ return (*pa+*pb); /* return by ref */ }
C Programming User Interface
Making Menus for Users void menu () { printf("The following options\n"); printf("R ==> Register a book\n "); printf("D ==> Display data about all books\n "); printf("F ==> Find and show a book\n "); printf("Enter [R,D,F] or [Q] to Quit: "); }
Using functions with Menu void main(void) { char opt; menu(); opt=getchar(); do { switch (opt) { case 'r'| R': Register(); break; case 'f'|'F': Find(); break; case 'd'|'D': Show_data(); break; case 'd'|'D': break(); default: menu(); opt=getchar();break; } }while (opt != 'q' && opt != 'Q'); }
Example Pseudo-code # include<stdio.h> # typedef enum {worse=-1, bad=0, good=1, best=2} credit; /* Some global constant definitions, if required ... */ /* Start of function defs */ void register();void list();void find_disp(); void delete();void change();int get_option(); // End of function Defs /* End of function Defs */ /* Start of main(), Action definitions */ int main() { /* Some local variable and constant defs */ short int opt; do { opt=get_option(); switch(opt) { case 1: register(); break; case 2: list(); break; case 3: find_disp(); break; case 4: delete(); break; case 5: change(); break; case 6: exit(); /* exit the loop, hence the program */ } } while(1); /* End of while */ return 0; } /* End of main() */
C Programming Recursive Functions
Recursion Recursion = a function calls itself as a function for unknown times. We call this recursive call for (i = 1 ; i <= n-1; i++) sum++; int sum(int n) { if (n <= 1) return 1 else return (n + sum(n-1)); }