1 / 102

Programming Concepts and C Language

Programming Concepts and C Language. For I semester BE VTU Slides prepared by Prathima A S. Introduction to C. Derived from BCPL (Basic Combined Programming Language) in 1972 by Dennis Ritchie at Bell Labs Sample C program main() { /* printing the message */

rock
Download Presentation

Programming Concepts and C Language

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Programming Concepts and C Language For I semester BE VTU Slides prepared by Prathima A S I semester BE, SJCE Mysore.

  2. Introduction to C • Derived from BCPL (Basic Combined Programming Language) in 1972 by Dennis Ritchie at Bell Labs • Sample C program • main() • { • /* printing the message */ • printf(“Hello World”); • } I semester BE, SJCE Mysore.

  3. Name of program is main( ) • Execution begins here • main( ) tells computer where program begins • Only one main • { - begin of function • } – end of function • /* */ - comment : ignored by compiler. • printf( ) – standard C function. • Distinction between uppercase and lowercase I semester BE, SJCE Mysore.

  4. Constants, Variables and Data Types • Character Set : • Letters : A..Z, a..z • Digits : 0..9 • Special characters : , . : ; ? ’ “ ! | / \ ~ -_ $ % # & ^ * + - < > ( ) { } [ ] • White space : blank space, horizontal tab, vertical tab,carriage return, new line, form feed. I semester BE, SJCE Mysore.

  5. C tokens : individual units. • Keyword – float, while, for, int,…. • Identifier – main( ) , amount, sum, … • Constants – -13.5, 500, … • Strings – “ABC”, “MCA”, … • Operators – + - * % … • Special Symbols – [ ] { }… I semester BE, SJCE Mysore.

  6. Keywords • Fixed meaning, cannot be changed • Basic building block • Lowercase • eg. Break, int, do, for,… • Identifiers • Refers to names of variables, functions,… • User defined names • Uppercase and lowercase • Constants • Fixed values • Do not changes during execution of program • Numeric constant – Integer (decimal, octal, hexadecimal) and Real • Character constant : • Single character constant • String constant • Backslash character constant I semester BE, SJCE Mysore.

  7. Variables • Data name used to store data value • May take different values at different times during execution • Chosen by the programmer • Letters, digits and ‘_’ allowed • Data Types • Primary data types • User defined data type • Derived data type (array, function, structure,..) • Empty data set I semester BE, SJCE Mysore.

  8. Type Size (bytes) Range char or signed char 8 -128 to 127 unsigned char 8 0 to 256 int or signed int 16 -32678 to 32767 unsigned int 16 0 to 65535 short int or signed short int 8 -128 to 127 unsigned short int 8 0 to 255 long int or signed long int 32 -2147483648 to 1247483647 unsigned long int 32 0 to 4294967295 float 32 3.4 E –38 to 3.4 E + 38 double 64 1.7 E –308 to 1.7 E + 308 long double 80 3.4 E –4832 to 1.1 E +4932 • Primary Data Type • int, float, char, double. • Extended data type – e.g., long int, short int,… I semester BE, SJCE Mysore.

  9. Declaration of variables • General form: Data_type v1,v2,v3,… vn; • E.g., int base, height ; float area ; • Data type keywords- Char or signed char, unsigned char, signed int or int, unsigned int or unsigned, short int or short or signed short int, long int or signed long int or long, float, double, long double I semester BE, SJCE Mysore.

  10. User defined data type • Type definition • Define an identifier that would represent an existing data type • This user defined data type can be used to declare variables • General Form : typedef type identifier ; • E.g., typedef float marks ; • marks physics, maths ; • enum • General form : enum identifier {value1, value2,…. ValueN}; • Variables can be declared as, enum identifier v1,v2,…vN : • Enumerated variables v1,v2,..vN can have one of the values of value1,value2,..valueN • E.g., enum flavor {vanilla, pista, chocolate}; • enum flavor icecream, milkshake ; I semester BE, SJCE Mysore.

  11. Storage class • Auto • Static • Extern • Register • Assigning values to variables • Var_name = constant ; • C convertstype of RHS to type of LHS during assigning. • Assign a value during declaration also allowed • E.g., int base =10, height = 20 ; • float marks = 45.50 ; • Multiple assign operators also allowed. • E.g., a = b = c = 0; I semester BE, SJCE Mysore.

  12. Declaring a variable as constant • const int no_student = 60 • Declaring a variable as volatile • Volatile int date ; • var may be both volatile and constant • volatile constant int location ; • Overflow and underflow of data • Value too big or too small for the datatype to hold. • Declaring Symbolic constants • Constant values assigned to these names at the beginning of the program • Values automatically substituted at the appropriate places • Defined as- #define NO_STUDENTS 50 #define PI 3.1415 I semester BE, SJCE Mysore.

  13. Operators and Expressions • Operator • Symbol that tells the computer to perform certain manipulations • Manipulate data and variables • Part of logical expression • Different types of Operators • Arithmetic operators • + - / * % • Integer arithmetic • Real arithmetic • Relational operators • < <= > >= == != • Simple relational expression (only one relational operator) • Evaluates to true ( greater than 0) or false (0) • E.g., a+b >= c-d I semester BE, SJCE Mysore.

  14. Operand 1 Operand 2 Op1 && op2 Op1 || op2 ! op1 Non-zero Non-zero 1 1 0 Non-zero 0 0 1 0 0 Non-zero 0 0 1 0 0 0 0 1 • Logical operators • && (AND) || (OR) ! (NOT) • && and || used when more than one condition is to be tested • Evaluates to 0 or 1 • Truth table e.g., - 10 > 5 && !(10 < 9) || 3 <= 4 if(marks >= 60 && marks <= 70) printf(“first class”); I semester BE, SJCE Mysore.

  15. Assignment operator • = • Short hand assignment operators • sum = sum + 10 ; can be written as • sum += 10; • Similarly we have • -=, *=, %=, /=, • Increment and Decrement operators • ++ and – adds and subtracts one from operand • E.g x++ and ++x will add one to x • Prefix will increment or decrement operation before obtaining the value of the operand for use in the expression, ie., increment / decrement is done first then assigns the value to RHS. I semester BE, SJCE Mysore.

  16. Conditional operator • Ternary operator pair ? : • exp1 ? exp2 : exp3 • exp1 evaluated first , if true then exp2 is evaluated else exp3 is evaluated • E.g., main() { int a,b ,x,y; a = 10; b = 20; x = (a>b) ? (a+b) : (b+5) ; /* x=25*/ y = (a<=b) ? (a+5) : (b+5) ; /* y=15*/ } I semester BE, SJCE Mysore.

  17. Bitwise Operators • Used for • Testing • Setting • Shifting • char or int data types only • Operations are applied to individual bits of the operand • Same truth table as logical operators. • Bitwise AND (&) • Bitwise OR (| ) • Bitwise NOT (~) • Bitwise EXOR (^) • E.g., x= 13 ; 0000 0000 0000 1101 • y= 25; 0000 0000 0001 1001 • x & y = 0000 0000 0000 1001 = 9 • x | y = 0000 0000 0001 1101 = 29 • x ^ y = 0000 0000 0001 0100 = 20 • ~x = 1111 1111 1111 0010 • Bitwise left shift op << no_of bits_to_shift • Bitwise right shift op >> no_of_bits_to_shift I semester BE, SJCE Mysore.

  18. Special operators • Comma , • To link related expressions together • Evaluated from left to right • The value of the right most expression is the value of the combined expression • E.g., z = (x=10, y=5, x+y) ; • Z will be 15 • Can be used if for loops • Sizeof( ) operator • Compile time operator • Returns number of byte the operand occupies • Operand may bevariable ,m = sizeof(sum); • constant , m = sizeof(235L); • data type m= sizeof(long int); I semester BE, SJCE Mysore.

  19. Expressions • Combination of variables, constants and operators arranged as per the syntax of the language • Precedence of Arithmetic Operators • Left to right evaluation • High priority * / % • Low priority + - • E.g., x = 9 – 12/3 + 3 * 2 –1 • First pass (high priority operators are applied) • x = 9 - 4 + 6 –1 • second pass (low priority operators are applied) • x = 10 • Order of evaluation can be changed using parenthesis • E.g., x = 9 – 12 / (3 + 3) * (2 – 1 ) • Parenthesis gets highest priority : • x = 9 – 12 / 6 * 1 • 2nd pass x = 9 – 2 • 3rd pass x = 7 I semester BE, SJCE Mysore.

  20. Type conversion in Expressions • If constants and variables are of mixed type they are converted to the same type • Compiler converts all operands up to the type of the largest operand – type promotion. • All conversions are done operation by operation. • The final result converted to the operand on the left of the assignment operator • During final assignment if – • Float is assigned to int : truncation of fractional part • Double to float : causes rounding off of digits • Long int to int : higher order bits are dropped. • To force a type conversion – casting a value • E.g., b = (double) sum / m; • a = (int) a + b ; I semester BE, SJCE Mysore.

  21. Precedence of Operators. • Highest priority to lowest priority - • ( ) [ ] -> . • ! ~ ++ -- - (type) * & sizeof() • * / % • + - • << >> • < <= > >= • == != • & • ^ • | • && • || • ?: • += -= *= %= != &= <<= >>= • , • In case of &&, if 1st operand is zero the 2nd operand is not evaluated • In case of || if the first operand is 1 the 2nd operand is not evaluated I semester BE, SJCE Mysore.

  22. Mathematical functions • C compiler support basic math functions like cos, sin, sqrt,.. • #include<math.h> • Functions- • log(x) , acos(x), asin(x), atan(x), cos(x), sin(x), log10(x), pow(x,y), sqrt(x), csoh(x), sinh(x), tann(x), ceil(x), floor(x), exp(x), fabs(x) , fmad(x,y) • Redundant parenthesis do not cause errors or slow down the execution of an expression • Use parenthesis to clarify the exact order of evaluation I semester BE, SJCE Mysore.

  23. Decision making and Branching • To change the order of execution based on certain conditions or repeat a group a statements until certain specified conditions are met • ANSI C has the following categories of statements • Selection – if, switch • Iteration – for, do, while • Jump – continue, break, goto, return • Label – case, default, (goto) label statement • Expression – valid expression • Block – { … } (also called compound statements) I semester BE, SJCE Mysore.

  24. if statement • 2 way decision statement • simple if statement if(expression) { statement block ; } • if .. else statement if(exp) { st block 1 ; } else { St block2; } I semester BE, SJCE Mysore.

  25. nested if .. else statement if(cond1) { if(cond2) { st 1; } else { st 2; } } else { st 3; } I semester BE, SJCE Mysore.

  26. if .. else .. if ladder if(cond1) st 1; else if(cond2) st 2; else if(cond3) st 3; . . else if(cond n) st n ; else default st; I semester BE, SJCE Mysore.

  27. switch • Multiple branch selection statement • Tests the value of an expression against a list of integer or char constants • When a match is found, then statement associated with that constant is executed. switch(exp) { case const1 : st seq ; break ; case const2 : st seq ; break ; : : default : st seq ; } I semester BE, SJCE Mysore.

  28. goto statement • Unconditional branch goto label ; : : label : • Programs become unreadable • Label can be before (backward looping) or after (jumping) a goto • E.g., x=1; /* to print 1 to 100 */ loop1 : printf(“%d”,x); x++; if(x<100) goto loop1; I semester BE, SJCE Mysore.

  29. Looping • C supports three loop constructs • for • while • do .. while • The while loop keeps repeating an action until an associated test returns false. This is useful where the programmer does not know in advance how many times the loop will be traversed. • The do while loops is similar, but the test occurs after the loop body is executed. This ensures that the loop body is run at least once. • The for loop is frequently used, usually where the loop will be traversed a fixed number of times. It is very flexible, and novice programmers should take care not to abuse the power it offers. I semester BE, SJCE Mysore.

  30. for syntax: for (<exp1>; <exp2>; <exp3>) statement; <exp1>: initialization, evaluated once. <exp2>: loop control, zero value means exit. <exp3>: counter, evaluated at end of body. • Design issues: • Expressions can be statements or statement sequences (separated by commas). • No explicit loop var. • Everything can be changed in the loop. • Pretest. I semester BE, SJCE Mysore.

  31. Example to calculate total of an array main( ) { float total = 0.0; int i; for(i = 0; i < count; i++) total += array[i]; } I semester BE, SJCE Mysore.

  32. The while has the form:   while (expression) statement ; • For example:   int x=3;   main( ) { while (x>0) { printf("x=%d n",x); x--; } } • ...outputs: •   x=3 x=2 x=1 ...to the screen. I semester BE, SJCE Mysore.

  33. C's do-while statement has the form:   do statement; while (expression); • For example: int x=3; main( ) { do { printf("x=%d n",x--); } while (x>0); } • ..outputs:- •   x=3 x=2 x=1 • NOTE: The postfix x-- operator which uses the current value of x while printing and then decrements x. I semester BE, SJCE Mysore.

  34. break and continue • C provides two commands to control how we loop: • break -- exit form loop or switch. • continue -- skip 1 iteration of loop. • Consider the following example where we read in integer values and process them according to the following conditions. If the value we have read is negative, we wish to print an error message and abandon the loop. If the value read is great than 100, we wish to ignore it and continue to the next value in the data. If the value is zero, we wish to terminate the loop. •   program next slide I semester BE, SJCE Mysore.

  35. while (scanf( ``%d'', &value ) == 1 && value != 0) {   if (value < 0) { printf(``Illegal value n''); break; /* Abandon the loop */ }   if (value > 100) { printf(``Invalid value n''); continue; /* Skip to start loop again */ }   /* Process the value read */ /* guaranteed between 1 and 100 */ ....;   ....; } /* end while value != 0 */ I semester BE, SJCE Mysore.

  36. Input and Output • To use these facilities, your program must include these definitions by adding the line This is done by adding the line • #include <stdio.h> near the start of the program file. • Character Input / Output • This is the lowest level of input and output. It provides very precise control, but is usually too fiddly to be useful. Most computers perform buffering of input and output. This means that they'll not start reading any input until the return key is pressed, and they'll not print characters on the terminal until there is a whole line to be printed. • getchar • putchar I semester BE, SJCE Mysore.

  37. getchar • As an example, here is a program to count the number of characters read until an EOF is encountered. EOF can be generated by typing Control - d. #include <stdio.h> main( ) { int ch, i = 0; while((ch = getchar()) != EOF) i ++; printf("%d\n", i); } I semester BE, SJCE Mysore.

  38. putchar • putchar puts its character argument on the standard output (usually the screen). • The following example program converts any typed input into capital letters. To do this it applies the function toupper from the character conversion library ctype.h to each character in turn. #include <ctype.h> /* For definition of toupper */ #include <stdio.h> /* For definition of getchar, putchar, EOF */ main( ) { int ch; while((ch = getchar()) != EOF) putchar(toupper(ch)) } I semester BE, SJCE Mysore.

  39. Formatted Input / Output • printf • Scanf • The printf function is defined as follows: int printf(char *format, arg list ...) -- prints to stdout the list of arguments according specified format string. Returns number of characters printed. • The format string has 2 types of object: • ordinary characters -- these are copied to output. • conversion specifications -- denoted by % and listed in Table  I semester BE, SJCE Mysore.

  40. Format Spec (%) Type Result c char single character i,d int decimal number o int octal number x,X int hexadecimal number lower/uppercase notation u int unsigned int s char * print string terminated by 0 f double/float format -m.ddd... e,E " Scientific Format -1.23e002 g,G " e or f whichever is most compact % - print % character I semester BE, SJCE Mysore.

  41. Between % and format char we can put: • - (minus sign) • -- left justify. • integer number • -- field width. • m.d • -- m = field width, d = precision of number of digits after decimal point or number of chars from a string. • So:           printf("%-2.3f n",17.23478); The output on the screen is:           17.235 and:           printf("VAT=17.5%% n"); ...outputs:           VAT=17.5% I semester BE, SJCE Mysore.

  42. scanf •    int scanf(char *format, args....) -- reads from stdin and puts input in address of variables specified in args list. Returns number of chars read. • Format control string similar to printf • Note: The ADDRESS of variable or a pointer to one is required by scanf.    scanf(``%d'',&i); • We can just give the name of an array or string to scanf since this corresponds to the start address of the array/string.  char string[80]; scanf(``%s'',string); I semester BE, SJCE Mysore.

  43. Whole Lines of Input and Output • Where we are not too interested in the format of our data, or perhaps we cannot predict its format in advance, we can read and write whole lines as character strings. This approach allows us to read in a line of input, and then use various string handling functions to analyse it at our leisure. • gets • puts I semester BE, SJCE Mysore.

  44. gets • gets reads a whole line of input into a string until a newline or EOF is encountered. It is critical to ensure that the string is large enough to hold any expected input lines. • When all input is finished, NULL as defined in stdio.h is returned. • puts • puts writes a string to the output, and follows it with a newline character. • Example: Program which uses gets and puts to double space typed input. I semester BE, SJCE Mysore.

  45. #include <stdio.h> • main( ) • { • char line[256]; /* Define string sufficiently large to store a line of input */ while(gets(line) != NULL) /* Read line */ • { • puts(line); /* Print line */ • printf("\n"); /* Print blank line */ • } • } • Note that putchar, printf and puts can be freely used together. So can getchar, scanf and gets. I semester BE, SJCE Mysore.

  46. Arrays • An array is a collection of variables of the same type. Individual array elements are identified by an integer index. • In C the index begins at zero and is always written inside square brackets. • We have already met single dimensioned arrays which are declared like this int results[20]; • Arrays can have more dimensions, in which case they might be declared as int results_2d[20][5]; int results_3d[20][5][3]; • Each index has its own set of square brackets. I semester BE, SJCE Mysore.

  47. As an example, here is a simple program to add up all of the integers in a single dimensioned array. • main( ) • { • int i; • int total = 0; • for(i = 0; i < size; i++) • total += array[i]; • printf(“%d”,total); • } I semester BE, SJCE Mysore.

  48. Strings • In C Strings are defined as arrays of characters. For example, the following defines a string of 50 characters: •   char name[50]; • C has no string handling facilities built in and so the following are all illegal: • char firstname[50],lastname[50],fullname[100];   • firstname= "Arnold"; /* Illegal */ lastname= "Schwarznegger"; /* Illegal */ fullname= "Mr"+firstname +lastname; /* Illegal */ I semester BE, SJCE Mysore.

  49. However, there is a special library of string handling routines which we will come across later. • To print a string we use printf with a special %s control character: •    printf(“s”,name); • NOTE: We just need to give the name of the string. • In order to allow variable length strings the \0 character is used to indicate the end of a string. • So we if we have a string, char NAME[50]; and we store the “DAVE” in it its contents will look like: I semester BE, SJCE Mysore.

  50. String handling functions • strcat(str1,str2) – concatenates two strings • strcmp(str1,str2) – compares two strings • strcpy(str1,str2) – copies str2 to str1 • strlen(str) – returns length of str • Other string functions like- • strlwr( ), strupr( ), strncat( ), stricmp( ),.. are also defined in string.h I semester BE, SJCE Mysore.

More Related