Mais conteúdo relacionado

cs8251 unit 1 ppt

  1. CS8251-PROGRAMMING IN C G.PRAVEENA, Associate Professor, Department of Computer Science & Engineering
  2. UNIT I BASICS OF C PROGRAMMING Introduction to programming paradigms - Structure of C program - C programming: Data Types – Storage classes - Constants – Enumeration Constants - Keywords – Operators: Precedence and Associativity - Expressions - Input/Output statements, Assignment statements – Decision making statements - Switch statement - Looping statements – Pre-processor directives - Compilation process
  3. Introduction to Programming Paradigm  a programming paradigm is a fundamental style of computer programming that defines how the structure and basic elements of a computer program will be built.
  4. • Classification of Programming Paradigms s.No Type Purpose 1. Monolithic Programming Emphasis on finding a solution 2. Procedural Programming Focus on modules 3. Structured Programming Specifies a series of well-structured steps and procedure 4. Object-Oriented Programming Focuses on classes and objects
  5. Monolithic Programming • In these types of programming language, the coding was written with a single function. • A program is not divided into parts; hence it is named as monolithic programming. • Example --BASIC(beginners all purpose symbolic Instruction code)it was developed to enable more people to write programs. --Assembly Language
  6. • Structured Programming structured programming facilities program understanding and modification and has top- down design approach, where a system is divided into compositional sub systems. example -- ALGOL (Algorithmic Language)-focused on being an appropriate to define algorithms,while using mathematical language terminology and targeting scientific and engg problems just like FORTRAN.
  7. • Procedural Programming In procedural programming is a programming paradigm, derived from structural programming, based upon the concept of the procedure call. • Example -FORTRON -COBOL(Common Business oriented language)-uses terms like file,move and copy.
  8. • Object Oriented Programming Programming Paradigm that views a computer program as a combination of objects which can exhange information in a standard manner and can be combined with one another as a module. • Example • ---C++
  9. • C – a general-purpose programming language, initially developed by Dennis Ritchie between 1969 and 1973 at AT&T Bell Labs. • Features of C Programming Language – C is a robust language with rich set of built-in functions and operators. – Programs written in C are efficient and fast. – C is highly portable, programs once written in C can be run on another machines with minor or no modification. – C is basically a collection of C library functions, we can also create our own function and add it to the C library. – C is easily extensible.
  10. • Advantages of C – C is the building block for many other programming languages. – Programs written in C are highly portable. – Several standard functions are there (like in- built) that can be used to develop programs. – C programs are basically collections of C library functions, and it’s also easy to add own functions in to the C library. – The modular structure makes code debugging, maintenance and testing easier. •
  11. • Disadvantages of C – C does not provide Object Oriented Programming (OOP) concepts. – There is no concepts of Namespace in C. – C does not provide binding or wrapping up of data in a single unit. – C does not provide Constructor and Destructor.
  12. • Basic Structure of a C Program
  14. Primary Data Types with Variable Names • After taking suitable variable names, they need to be assigned with a data type. This is how the data types are used along with variables: int age; char letter; float height, width;
  15. Derived Data Types C supports three derived data types: data types Description Arrays Arrays are sequences of data items having homogeneous values . They have adjacent memory locations to store values. Pointers These are powerful C features which are used to access the memory and deal with address Structure It is a package of variables of different types under a single name . This is doneto handle data efficiently. “struct” keyword is used to define a structure. Union These allow storing various data types in the same memory location. Programmers can define a union with different members but only a single
  16. User Defined Data Types • C allows the feature called type definition which allows programmers to define their own identifier that would represent an existing data type. Enum • Enumeration is a special data type that consists of integral constants and each of them is assigned with a specific name. “enum” keyword is used to define the enumerated data type.
  17. Data Types Memory Size Range char 1 byte −128 to 127 signed char 1 byte −128 to 127 unsigned char 1 byte 0 to 255 short 2 byte −32,768 to 32,767 signed short 2 byte −32,768 to 32,767 unsigned short 2 byte 0 to 65,535 int 2 byte −32,768 to 32,767 signed int 2 byte −32,768 to 32,767 unsigned int 2 byte 0 to 65,535 short int 2 byte −32,768 to 32,767 signed short int 2 byte −32,768 to 32,767 char 1 byte −128 to 127 signed char 1 byte −128 to 127 unsigned char 1 byte 0 to 255 short 2 byte −32,768 to 32,767
  18. Data Types Memory Size Range unsigned short int 2 byte 0 to 65,535 long int 4 byte -2,147,483,648 to 2,147,483,647 signed long int 4 byte -2,147,483,648 to 2,147,483,647 unsigned long int 4 byte 0 to 4,294,967,295 float double long double 4 byte 8 byte 10 byte unsigned short int 2 byte 0 to 65,535 long int 4 byte -2,147,483,648 to 2,147,483,647 signed long int 4 byte -2,147,483,648 to 2,147,483,647 unsigned long int 4 byte 0 to 4,294,967,295 float double long double 4 byte 8 byte 10 byte unsigned short int 2 byte 0 to 65,535 long int 4 byte -2,147,483,648 to 2,147,483,647
  19. Storage Classes A storage class defines the scope (visibility) and a location of variables and functions within a C Program.A storage class in C is used to describe the following things: • the variable scope. • The location where the variable will be stored. • The initialized value of a variable. • A lifetime of a variable. • Who can access a variable? Storage classes are auto, static, extern, and register. • A storage class can be omitted in a declaration and a default storage class is assigned automatically.
  20. auto • The variables defined using auto storage class are called as local variables. Auto stands for automatic storage class. A variable is in auto storage class by default if it is not explicitly specified. • The scope of an auto variable is limited with the particular block only. Once the control goes out of the block, the access is destroyed. This means only the block in which the auto variable is declared can access it.. Example, auto int age; int add(void) { int a=13; auto int b=48; return a+b;} extern • Extern stands for external storage class .Extern storage class is used when we have global functions or variables which are shared between two or more files.. • extern is used to declaring a global variable or function in another file to provide the reference of variable or function which have been already defined in the original file. • The variables defined using an extern keyword are called as global variables
  21. example, extern void display(); First File: main.c #include <stdio.h> extern i; main() { printf("value of the external integer is = %dn", i); return 0;}
  22. static • The static variables are used within function/ file as local static variables. They can also be used as a global variable • Static local variable is a local variable that retains and stores its value between function calls or block and remains visible only to the function or block in which it is defined. • Static global variables are global variables visible only to the file in which it is declared. Example: static int count = 10;
  23. #include <stdio.h> /* function declaration */ void next(void); static int counter = 7; /* global variable */ main(){ while(counter<10){ next(); counter++; } return 0;} void next( void ) { /* function definition */ static int iteration = 13; /* local static variable */ iteration ++; printf("iteration=%d and counter= %dn", iteration, counter);}
  24. • Register Storage Class in C The register storage class when you want to store local variables within functions or blocks in CPU registers instead of RAM to have quick access to these variables. For example, "counters" are a good candidate to be stored in the register. Example: register int age; register is used to declare a register storage class. The variables declared using register storage class has lifespan throughout the program
  25. Storage Class Declar ation Storage Default Initial Value Scope Lifetime auto Inside a functi on/bl ock Memory Unpredictable Within the function/blo ck Within the function/block register Inside a functi on/bl ock CPU Registers Garbage Within the function/blo ck Within the function/block extern Outsid e all functi ons Memory Zero Entire the file and other files where the variable is declared as extern program runtime
  26. Storage Class Declarat ion Storag e Default Initial Value Scope Lifetime Static (local) Inside a function /block Memor y Zero Within the function/blo ck program runtime Static (global) Outside all function s Memor y Zero Global program runtime
  27. Constants • C Constants are also like normal variables. But, only difference is, their values can not be modified by the program once they are defined. • Constants refer to fixed values. They are also called as literals • Constants may be belonging to any of the data type. Syntax: const data_type variable_name; (or) const data_type *variable_name;
  28. TYPES OF C CONSTANT: 1. Integer constants 2. Real or Floating point constants 3. Octal & Hexadecimal constants 4. Character constants 5. String constants 6. Backslash character constants
  29. Constant type data type (Example) Integer constants int (53, 762, -478 etc ) unsigned int (5000u, 1000U etc) long int, long long int (483,647 2,147,483,680) Real or Floating point constants float (10.456789) doule (600.123456789) Octal constant int (Example: 013 /*starts with 0 */) Hexadecimal constant int (Example: 0x90 /*starts with 0x*/) character constants char (Example: ‘A’, ‘B’, ‘C’) string constants char (Example: “ABCD”, “Hai”)
  30. 1. INTEGER CONSTANTS IN C: • An integer constant must have at least one digit. • It must not have a decimal point. • It can either be positive or negative. • No commas or blanks are allowed within an integer constant. • If no sign precedes an integer constant, it is assumed to be positive. • The allowable range for integer constants is -32768 to 32767. 2. REAL CONSTANTS IN C: • A real constant must have at least one digit • It must have a decimal point • It could be either positive or negative • If no sign precedes an integer constant, it is assumed to be positive. • No commas or blanks are allowed within a real constant. Eg: 2.5, 5.11, etc.
  31. 3. CHARACTER AND STRING CONSTANTS IN C: • A character constant is a single alphabet, a single digit or a single special symbol enclosed within single quotes. • The maximum length of a character constant is 1 character. • String constants are enclosed within double quotes. Eg: ‘a’, ‘8’,’_’etc. Eg: “Hello” ,”444”,”a” etc,.
  32. 4. BACKSLASH CHARACTER CONSTANTS IN C: • There are some characters which have special meaning in C language. • They should be preceded by backslash symbol to make use of special function of them.
  33. Backslash_character Meaning b Backspace f Form feed n New line r Carriage return t Horizontal tab ” Double quote ’ Single quote Backslash v Vertical tab a Alert or bell ? Question mark N Octal constant (N is an octal constant) XN Hexadecimal constant (N – hex.dcml cns
  34. EXAMPLE PROGRAM USING CONST KEYWORD IN C: #include <stdio.h> void main() { const int height = 100; /*int constant*/ const float number = 3.14; /*Real constant*/ const char letter = 'A'; /*char constant*/ const char letter_sequence[10] = "ABC"; /*string constant*/ const char backslash_char = '?'; /*special char cnst*/ printf("value of height :%d n", height ); printf("value of number : %f n", number ); printf("value of letter : %c n", letter ); printf("value of letter_sequence : %s n", letter_sequence); printf("value of backslash_char : %c n", backslash_char); }
  35. C – Tokens and keywords C TOKENS: • C tokens are the basic buildings blocks in C language which are constructed together to write a C program. • Each and every smallest individual units in a C program are known as C tokens. C tokens are of six types. They are, 1. Keywords (eg: int, while), 2. Identifiers (eg: main, total), 3. Constants (eg: 10, 20), 4. Strings (eg: “total”, “hello”), 5. Special symbols (eg: (), {}), 6. Operators (eg: +, /,-,*)
  36. C TOKENS EXAMPLE PROGRAM: int main() { int x, y, total; x = 10, y = 20; total = x + y; printf ("Total = %d n", total); } where, main – identifier {,}, (,) – delimiter int – keyword x, y, total – identifier main, {, }, (, ), int, x, y, total – tokens
  37. 2. IDENTIFIERS IN C LANGUAGE: • Each program elements in a C program are given a name called identifiers. • Names given to identify Variables, functions and arrays are examples for identifiers. eg. x is a name given to integer variable in above program. RULES FOR CONSTRUCTING IDENTIFIER NAME IN C: • First character should be an alphabet or underscore. • Succeeding characters might be digits or letter. • Punctuation and special characters aren’t allowed except underscore. • Identifiers should not be keywords.
  38. 3. KEYWORDS IN C LANGUAGE: Keywords are pre-defined words in a C compiler. Each keyword is meant to perform a specific function in a C program. Since keywords are referred names for compiler, they can’t be used as variable name. C language supports 32 keywords which are given below
  39. auto double int struct const float short unsigned break else long switch continue for signed void case enum register typedef default goto sizeof volatile char extern return union do if static while
  40. Operators in C • An operator is a symbol used to do a mathematical or logical manipulations. 1. Arithmetic operators 2. Relational Operators 3. Logical Operators 4. Assignment Operators 5. Increments and Decrement Operators 6. Conditional Operators 7. Bitwise Operators 8. Special Operators
  41. Arithmetic Operators Operator Meaning + Addition or Unary Plus – Subtraction or Unary Minus * Multiplication / Division % Modulus Operator
  42. Arithmetic Operations • Integer Arithmetic Let x = 27 and y = 5 x + y = 32 x – y = 22 x * y = 115 x % y = 2 x / y = 5 • Floating point Arithmetic Let x = 14.0 and y = 4.0 then x + y = 18.0 x – y = 10.0 x * y = 56.0 • Mixed mode Arithmetic 15/10.0 = 1.5
  43. Sample program include <stdio.h> int main() { int a=40,b=20, add,sub,mul,div,mod; add = a+b; sub = a-b; mul = a*b; div = a/b; mod = a%b; printf("Addition of a, b is : %dn", add); printf("Subtraction of a, b is : %dn", sub); printf("Multiplication of a, b is : %dn", mul); printf("Division of a, b is : %dn", div); printf("Modulus of a, b is : %dn", mod); }
  44. output Addition of a, b is : 60 Subtraction of a, b is : 20 Multiplication of a, b is : 800 Division of a, b is : 2 Modulus of a, b is : 0
  45. ASSIGNMENT OPERATORS IN C: values for the variables are assigned using assignment operators. For example, if the value “10” is to be assigned for the variable “sum”, it can be assigned as “sum = 10;” • There are 2 categories of assignment operators in C language. They are, 1. Simple assignment operator ( Example: = ) 2. Compound assignment operators ( Example: +=, - =, *=, /=, %=, &=, ^= )
  46. Operators Example/Description = sum = 10; 10 is assigned to variable sum += sum += 10; This is same as sum = sum + 10 -= sum -= 10; This is same as sum = sum – 10 *= sum *= 10; This is same as sum = sum * 10 /= sum /= 10; This is same as sum = sum / 10 %= sum %= 10; This is same as sum = sum % 10 &= sum&=10; This is same as sum = sum & 10 ^= sum ^= 10; This is same as sum = sum ^ 10
  47. include <stdio.h> int main() { int Total=0,i; for(i=0;i<10;i++) { Total+=i; // This is same as Total = Total+i } printf("Total = %d", Total); } Total = 45 OUTPUT:
  48. RELATIONAL OPERATORS IN C: • Relational operators are used to find the relation between two variables. i.e. to compare the values of two variables in a C program. Operators Example/Description > x > y (x is greater than y) < x < y (x is less than y) >= x >= y (x is greater than or equal to y) <= x <= y (x is less than or equal to y) == x == y (x is equal to y) != x != y (x is not equal to y)
  49. #include <stdio.h> int main() { int m=40,n=20; if (m == n) { printf("m and n are equal"); } else { printf("m and n are not equal"); }} OUTPUT: m and n are not equal
  50. LOGICAL OPERATORS IN C: • These operators are used to perform logical operations on the given expressions. Operators Example/Description && (logical AND) (x>5)&&(y<5) It returns true when both conditions are true || (logical OR) (x>=10)||(y>=10) It returns true when at-least one of the condition is true ! (logical NOT) !((x>5)&&(y<5)) It reverses the state of the operand “((x>5) && (y<5))” If “((x>5) && (y<5))” is true, logical NOT operator makes it false
  51. EXAMPLE PROGRAM FOR LOGICAL OPERATORS IN C: #include <stdio.h> int main() { int m=40,n=20; int o=20,p=30; if (m>n && m !=0) { printf("&& Operator : Both conditions are truen"); } if (o>p || p!=20) { printf("|| Operator : Only one condition is truen"); } if (!(m>n && m !=0)) { printf("! Operator : Both conditions are truen"); } else { printf("! Operator : Both conditions are true. " "But, status is inverted as falsen") } && Operator : Both conditions are true || Operator : Only one condition is true ! Operator : Both conditions are true. But, status is inverted as false
  52. BIT WISE OPERATORS IN C: These operators are used to perform bit operations. Decimal values are converted into binary values which are the sequence of bits and bit wise operators work on these bits. Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise NOT), ^ (XOR), << (left shift) and >> (right shift). BELOW ARE THE BIT-WISE OPERATORS AND THEIR NAME IN C LANGUAGE. 1. & – Bitwise AND 2. | – Bitwise OR 3. ~ – Bitwise NOT 4. ^ – XOR 5. << – Left Shift 6. >> – Right Shift
  53. EXAMPLE PROGRAM FOR BIT WISE OPERATORS IN C: #include <stdio.h> int main() { int m = 40,n = 80,AND_opr,OR_opr,XOR_opr,NOT_opr ; AND_opr = (m&n); OR_opr = (m|n); NOT_opr = (~m); XOR_opr = (m^n); printf("AND_opr value = %dn",AND_opr ); printf("OR_opr value = %dn",OR_opr ); printf("NOT_opr value = %dn",NOT_opr ); printf("XOR_opr value = %dn",XOR_opr ); printf("left_shift value = %dn", m << 1); printf("right_shift value = %dn", m >> 1); } o/p AND_opr value = 0 OR_opr value = 120 NOT_opr value = -41 XOR_opr value = 120 left_shift value = 80 right_shift value = 20
  54. Consider x=40 and y=80. Binary form of these values are given below. x = 00101000 y= 01010000 All bit wise operations for x and y are given below. x&y = 00000000 (binary) = 0 (decimal) x|y = 01111000 (binary) = 120 (decimal) ~x = 11111111111111111111111111 11111111111111111111111111111111010111 = -41 (decimal) x^y = 01111000 (binary) = 120 (decimal) x << 1 = 01010000 (binary) = 80 (decimal) x >> 1 = 00010100 (binary) = 20 (decimal)
  55. CONDITIONAL OPERATORS IN C: Conditional operators return one value if condition is true and returns another value is condition is false. This operator is also called as ternary operator. Syntax : (Condition? true_value: false_value); Example : (A > 100 ? 0 : 1); In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if else conditional statements. EXAMPLE PROGRAM FOR CONDITIONAL/TERNARY OPERATORS IN C #include <stdio.h> int main() { int x=1, y ; y = ( x ==1 ? 2 : 0 ) ; printf("x value is %dn", x); printf("y value is %d", y); } x value is 1 y value is 2
  56. Increment and Decrement Operators 1. ++ variable name (Pre Increment) 2. variable name++ (Post Increment) 3. – –variable name (Pre Decrement) 4. variable name– – (Post Decrement) . Syntax: Increment operator: ++var_name; (or) var_name++; Decrement operator: – -var_name; (or) var_name – -; Example: Increment operator : ++ i ; i ++ ; Decrement operator : – – i ; i – – ;
  57. EXAMPLE PROGRAM FOR PRE – INCREMENT OPERATORS IN C: /Example for increment operators #include <stdio.h> int main() { int i=0; while(++i < 5 ) { printf("%d ",i); } return 0; } 1 2 3 4 OUTPUT:
  58. Conditional or Ternary Operator It is used to checks the condition and execute the statement depending on the condition. The conditional operator consists of 2 symbols the question mark (?) and the colon (:) syntax: exp1 ? exp2 : exp3 a = 10; b = 15; x = (a > b) ? a : b
  59. Sample Program #include<stdio.h> #include <conio.h> void main ( ) { int a=5,b=8,c; clrscr( ); c = a>b?a:b; //Conditional operator printf(" n The Larger Value is%d",c); getch( ); } Output: The Larger Value is 8
  60. Bitwise Operators Operator Meaning & Bitwise AND | Bitwise OR ^ Bitwise Exclusive << Shift left >> Shift right  It is used to manipulate data at bit level.  Eg: a=5 i.e 0000 0101 b=4 i.e 0000 0100 Then a & b = 0000 0100 a | b = 0000 0101 etc,.
  61. Sample program #include<stdio.h> #include <conio.h> void main ( ) { int a=5,b=4,c; //char a=5,b=4,c; clrscr( ); c = a&b; printf(" n value a&b is:%d",c); getch( ); } Output: value a&b is:4
  62. Special Operator comma operator ( , ) sizeof operator pointer operator (& and *) member selection operators (. and ->). The Comma Operator -to link related expressions together. Eg: int x=5,y=10;
  63. Contd…sizeof #include<stdio.h> #include <conio.h> void main ( ) { int c; clrscr( ); printf(" n size of int is:%d",sizeof(c)); getch( ); } Output: size of int is: 2
  64. Expression  An expression represent data item such as variable, constant are interconnected using operators.  Eg: Expression C Expression a + b + c a + b + c a2+b2 a*a + b*b
  65. Operator Precedence & Associativity  The arithmetic expressions evaluation are carried out based on the precedence and associativity.  The evaluation are carried in two phases. First Phase: High Priority operators are evaluated. Second Phase: Low Priority operators are evaluated.
  66. Contd… Precedence Operator High * , / , % Low + , -
  67. Operator Type Operator Associatively Primary Expression Operators () [] . -> expr++ expr-- left-to-right Unary Operators * & + - ! ~ ++expr --expr (typecast) sizeof() right-to-left Binary Operators * / % left-to-right + - >> << < > <= >= == != & ^ | && || Ternary Operator ?: right-to-left Assignment Operators = += -= *= /= %= >>= <<= &= ^= |= right-to-left Comma , left-to-right Operator Precedence Chart
  68. Implicit type conversion • C allows mixing of constants and variables of different types in an expression. • C automatically converts intermediate values to the proper type so that the expression can be evaluated without loosing any significance. • Adheres to very strict rules and type conversion. • If operands are of different types then lower type is automatically converted to higher type before the operation proceeds. • The result is of higher type.
  69. Explicit Conversion • We want to force a type conversion that is different from automatic conversion. int female_students=30, male_students=50; Radio=female_students / male_students; Above gives wrong result Ratio = (float) female_students / male_students  Type Conversion: Converting the type of an expression from one type to another type.  Eg: x = (int)10.45
  70. Sample Program #include<stdio.h> #include <conio.h> void main ( ) { int a=30,b=50; float c; clrscr( ); c=(float)a/b; printf("nOutput is:%f",c); getch( ); } OUTPUT Output is: 0.6
  71. Character Test Function  It is used to test the character taken from the input.  isalpha(ch)  isdigit(ch)  islower(ch)  isupper(ch)  tolower(ch)  toupper(ch) etc,.
  72. Decision Making  It is used to change the execution order of the program based on condition.  Categories: Selection structure (or) conditional branching statements Looping structure (or) Iterative statements break, continue & goto statements
  73. Decision Making (cont) Sequential structure In which instructions are executed in sequence. Selection structure In which instruction are executed once based on the result of condition. Iteration structure In which instruction are executed repeatedly based on the result of condition.
  74. Conditional Branching  It allows the program to make a choice from alternative paths.  C provide the following selection structures if statement if - else statement if-else if statement Nested if-else statement switch-case
  75. if Statement Syntax if (condition is true) { Statements; } If condition False True Statements Example:1 (if) if (a>b) { printf (“a is larger than b”); }
  76. Example #include<stdio.h> #include <conio.h> void main ( ) { int a; clrscr( ); printf("nEnter the number:"); scanf("%d",&a); if(a>10) { printf(" n a is greater than 10"); } getch( ); } Output Enter the number: 12 a is greater than 10
  77. if…else Statement Syntax if (condition) { True statements; } else { False statements; } If Condition True False True statements False statements Example:2 (if-else) if(n > 0) average = sum / n; else { printf("can't compute averagen"); average = 0; }
  78. #include<stdio.h> #include <conio.h> void main ( ) { int a; clrscr( ); printf("nEnter the number:"); scanf("%d",&a); if(a>10) { printf(" n a is greater than 10"); } else { printf(" n a is less than 10"); } getch( ); } Output Enter the number: 2 a is less than 10
  79. if..else if statement Syntax if (condition1) { Tstatements; } else if (condition2) { Tstatements; } else if (condition3) { Tstatements; } else { Fstatements; }
  80. if..else if statement Condition 1 TStatements Condition 2 TStatements Condition 3 TStatements FStatements TRUE TRUE TRUE FALSE FALSE FALSE
  81. Example #include<stdio.h> #include<conio.h> void main() { int m1,m2,m3; float avg; printf("nEnter 3 marks:"); scanf("%d%d%d",&m1,&m2,&m3); avg=(m1+m2+m3)/3; printf("n The average is:%f",avg); printf("n The Grade is:"); if(avg>=60) { printf("First class"); } else if(avg>=50) { printf("Second class"); } else if(avg>=35) { printf("Thrid class"); } else { printf("Fail"); } getch(); } Output Enter 3 marks:65 75 70 The average is:70.000000 The Grade is: First class
  82. Example: 3 (if-else if-else) #include <stdio.h> void main() { int invalid_operator = 0; char operator; float number1, number2, result; printf("Enter two numbers and an operator in the formatn"); printf(" number1 operator number2n"); scanf("%f %c %f", &number1, &operator, &number2); if(operator == '*') result = number1 * number2; else if(operator == '/') result = number1 / number2; else if(operator == '+') result = number1 + number2; else if(operator == '-') result = number1 - number2; else invalid _ operator = 1; if( invalid _ operator != 1 ) printf("%f %c %f is %fn", number1, operator, number2, result ); else printf("Invalid operator.n"); }
  83. Nested if..else If Condition 2 True False True statements False statements If Condition 1 False Statements2 True Syntax if (condition1) { if (condition2) { True statements; } else { False statements; } } else { False statements2; }
  84. Example:4 (Nested-if) if(x > 0) { if(y > 0) printf("Northeast.n"); else printf("Southeast.n"); } else { if(y > 0) printf("Northwest.n"); else printf("Southwest.n"); }
  85. Switch Case • Multi way decision. It is well structured, but can only be used in certain cases; • Only one variable is tested, all branches must depend on the value of that variable. The variable must be an integral type. (int, long, short or char). • Each possible value of the variable can control a single branch. A default branch may optionally be used to trap all unspecified cases.
  86. switch-case structure case 1: case 2: default: switch(expression) Syntax switch (expression) { case constant 1: block1; break; case constant 2: block2; break; . . default : default block; break; }
  87. Example: switch-case #include<stdio.h> #include<conio.h> void main() { int i,n; printf("nEnter the Number:"); scanf("%d",&n); switch(n) { case 1: { printf("n Its in case 1"); break; } case 2: { printf("n Its in case 2"); break; } default: { printf("n Its in default"); break; } } getch(); } Output: Enter the Number:2 Its in case 2
  88. Looping structure  It is used to execute set of instructions in several time based on condition.  while – The while loop evaluates the test expression. – If the test expression is true (nonzero), codes inside the body of while loop is executed. The test expression is evaluated again. The process goes on until the test expression is false. – When the test expression is false, the while loop is terminated.  do…while – The code block (loop body) inside the braces is executed once. – Then, the test expression is evaluated. If the test expression is true, the loop body is executed again. This process goes on until the test expression is evaluated to 0 (false). – When the test expression is false (nonzero), the do...while loop is terminated.
  89. Looping structure for – The initialization statement is executed only once. – Then, the test expression is evaluated. If the test expression is false (0), for loop is terminated. But if the test expression is true (nonzero), codes inside the body of for loop is executed and the update expression is updated. – This process repeats until the test expression is false.
  90. while loop Syntax . while(condition) { . Body of the loop; . } Body of The loop condition False True
  91. do…while Loop Syntax do { Body of the loop } while (condition); Body of The loop condition False True
  92. Initialization condition false Body of the loop Inc / Decrement Syntax - for loop for (initialization; condition; Increment/Decrement) { Body of the loop } True
  93. Example: 6 (while) Example: 7 (for) int x = 2; while(x < 100) { printf("%dn", x); x = x * 2; } int x; for(x=2;x<100;x*=2) printf("%dn", x); Example: 8 (do-while) do{ printf("Enter 1 for yes, 0 for no :"); scanf("%d", &input_value); } while (input_value == 1);
  94. Calculate factorial using while & for #include<stdio.h> #include<conio.h> void main() { int i=1,fact=1,n; printf("nEnter the Number:"); scanf("%d",&n); while(i<=n) { fact =fact *i; i++; // i=i+1 } printf("n The value of %d! is:%d",n,fact); getch(); } Output Enter the Number:3 The value of 3! is: 6 for(i=1;i<=n;i++) { fact =fact *i; }
  95. // add numbers until user enters zero using do-while #include <stdio.h> void main() { double number, sum = 0; do { printf("Enter a number: "); scanf("%lf", &number); sum += number; } while(number != 0.0); printf("Sum = %.2lf",sum); }
  96. goto Syntax goto label; ... .. ... ... .. ... label: statement; Syntax label: statement; ... .. ... ... .. ... goto label; -used to alter the normal sequence of a C program. -The label is an identifier. -When goto statement is encountered, control of the program jumps to label: and starts executing the code.
  97. The break Statement • It is used to exit from a loop or a switch, • Control passing to first statement beyond the loop or switch. • Force an early exit from the loop • Protected by an if statement The continue Statement • It only works within • Force an immediate jump to loop control statement. • In a while loop & do while loop, jump to the test statement. • In a for loop, jump to increment/decrement then test, and perform the iteration. • Protected by an if statement.
  98. Example: 9 (continue & break) int i; for (i=0;i<10;i++) { if (i==5) continue; printf("%d",i); if (i==8) break; } This code will print 1 to 8 except 5.
  99. Input/Output Function Input/output Function Unformatted Formatted Output printf() fprintf() Input scanf() fscanf() Input getc() gets() getchar() Output putc() puts() putchar()
  100. IO Statements The Standard Input Output File • Character Input / Output – getchar, getc – putchar, putc • Formatted Input / Output – printf – scanf • Whole Lines of Input and Output – gets – puts
  101. Formatted Input/Output  C uses two functions for formatted input and output.  Formatted input : reads formatted data from the keyboard.  Formatted output : writes formatted data to the monitor.
  102. Formatted Input and Output
  103. Format of printf Statement
  104. Formatted Input (scanf) The standard formatted input function in C is scanf (scan formatted). scanf consists of :  a format string .  an address list that identifies where data are to be placed in memory. scanf ( format string, address list ); (“%c….%d…..%f…..”, &a,….&i,…..,&x…..)
  105. Format of scanf Statement
  106. printf • More structured output than putchar. • Arguments: a control string (which controls what gets printed) and a list of values to be substituted for entries in the control string Example: int a,b; printf(“ a = %d,b=%d”,a,b); • possible to insert numbers into the control string to control field widths for values to be displayed. Example  %6d would print a decimal value in a field 6 spaces wide  %8.2f would print a real value in a field 8 spaces wide with room to show 2 decimal places. • Display is left justified by default, but can be right justified by putting a - before the format information Example %-6d, a decimal integer right justified in a 6 space field
  107. scanf • Formatted reading of data from the keyboard. • Arguments-control string, followed by the list of items to be read. • Wants to know the address of the items to be read, the names of variables are preceded by & sign. • Character strings are an exception to this. Example: int a,b; scan f(“%d%d”, &a, &b);
  108. getchar • It returns the next character of keyboard input as an int. • If there is an error then EOF (end of file) is returned instead. • Always compare this value against EOF before using it. • If the return value is stored in a char, it will never be equal to EOF, so error conditions will not be handled correctly. • 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.
  109. Example: (getchar) #include <stdio.h> void main() { int ch, i = 0; while((ch = getchar()) != EOF) i ++; printf("%dn", i); }
  110. putchar • It puts the character argument on the standard output (usually the screen). • The following example program converts any typed input into capital letters. #include <ctype.h> #include <stdio.h> void main() { char ch; while((ch = getchar()) != EOF) putchar (toupper(ch)); }
  111. gets • It reads a whole line of input into a string until a new line 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 studio is returned. #include <stdio.h> main() { char ch[20]; gets(x); puts(x); }
  112. puts • It writes a string to the output, and follows it with a new line character. • putchar, printf and puts can be freely used together #include <stdio.h> main() { char line[256]; /* large to store a line of input */ while(gets(line) != NULL) /* Read line */ { puts(line); /* Print line */ printf("n"); /* Print blank line */ } }
  113. C - PREPROCESSOR • The C preprocessor, often known as cpp C Source code PreprocessorCompiler • It is a macro preprocessor (allows you to define macros, which are brief abbreviations for longer constructs) that transforms your program before it is compiled. • These transformations can be inclusion of header file, macro expansions etc. • Begins with a # symbol. • The C preprocessor is intended to be used only with C, C++, and Objective-C source code. Eg: #define PI 3.14
  114. Common Uses of cpp • Inclusion of Header files • Macros • Conditional Compilation • Diagnostics • Line control • Pragmas
  115. Include Syntax • Both user and system header files are included using the preprocessing directive `#include'. • Replace the file inclusion line with content of included file #include <file name> • This variant is used for system header files. • It searches for a file named file in a standard list of system directories. Eg: #include<stdio.h> #include "file name" • This variant is used for header files of your own program. • It searches for a file named file first in the directory containing the current file, then in the quote directories and then the same directories used for <file>. Eg: #include “user_header.h”
  116. Macros using #define #define PI 3.14 X=PI*2; expanded like X=3.14*2; #define NUMBERS 1, 2, 3 int x[] = { NUMBERS }; expanded like int x[] = { 1, 2, 3 }; #define circleArea(r) (3.1415*r*r) X=circleArea(5); expands to X=3.1415*5*5;
  117. Assign currently in effect #define TABLESIZE BUFSIZE #define BUFSIZE 1024 #define BUFSIZE 1020 #define TABLESIZE BUFSIZE #undef BUFSIZE #define BUFSIZE 37
  118. Function-like Macros #include <stdio.h> #define PI 3.1415 // #define circleArea(r) (PI*r*r) void main() { float radius, area; printf("Enter the radius: "); scanf("%d", &radius); area = PI*radius*radius; // area = circleArea(radius); printf("Area=%.2f",area); }
  119. Conditional Compilation • Instruct preprocessor whether to include certain chuck of code or not • Similar like a if statement. But big difference exist. (if- block of code gets executed or not; conditional if-block of code is included/ skipped for execution) • Use different code depending on the machine, OS • Compile same source file in two different programs • To exclude certain code from the program but to keep it as reference for future purpose
  120. Conditional directives #ifdef MACRO conditional codes #endif #if expression conditional codes #elif expression1 conditional codes if expression is non-zero #else conditional if expression is 0 #endif
  121. #if defined BUFF_SIZE && BUFF_SIZE >= 2048 conditional codes
  122. Predefined Macros Predefined macro Value __DATE__ String containing the current date __FILE__ String containing the file name __LINE__ Integer representing the current line number __STDC__ If follows ANSI standard C, then value is a nonzero integer __TIME__ String containing the current date.
  123. #include <stdio.h> void main() { printf("Current time: %s",__TIME__); } O/P: Current time: 19:54:39
  124. Enumeration • User-defined data type that consists of integral constants. • To define - keyword enum is used enum flag { const1, const2, ..., constN }; • Default values of enum elements is 0,1 so on enum suit { club = 0, diamonds = 10, hearts = 20, spades = 3, };
  125. Enumerated Type Declaration • When declaration of an enumerated type, only blueprint for the variable is created. enum boolean { F, T}; enum boolean check; enum boolean { F, T} check; • Enum variable takes only one value out of many possible values. • Good choice to work with flags enum suit card ; card = club; printf("Size of enum variable = %d bytes", sizeof(card));