UNIT-II Introduction to C Programming Detailed Explanation with Examples
Introduction • C is a general-purpose, procedural programming language. • Developed by Dennis Ritchie in 1972 at Bell Labs. • Provides low-level access, efficient performance. • Used in system programming, operating systems, embedded systems.
Structure of a C Program #include <stdio.h> int main() { // variable declaration printf("Hello World"); return 0; } Sections: • Preprocessor directives • main() function • Variable declarations • Statements
Comments, Keywords, Identifiers • Comments: // single-line, /* multi-line */ • Keywords: int, float, return, if, else, for, while, etc. • Identifiers: Names given to variables/functions. Example: int age; // 'age' is an identifier
Data Types, Variables, Constants • Primary: int, char, float, double • Derived: arrays, structures, pointers • Variables: Storage for data • Constants: Fixed values (e.g., #define PI 3.14) Example: int num = 10; const float pi = 3.14;
Type Conversion • Implicit (Type promotion): int → float automatically • Explicit (Type casting): (float) a/b Example: int a=5, b=2; float res = (float)a/b;
Control Flow & Relational Expressions • Control flow changes execution order • Relational operators: <, >, <=, >=, ==, != Example: if (a > b) { printf("a is greater"); } else { printf("b is greater"); }
Conditional Branching • if, if-else, if-else if • switch-case Example: switch(choice) { case 1: printf("One"); break; case 2: printf("Two"); break; default: printf("Invalid"); }
Loops • while: checks condition before execution • do-while: executes at least once • for: compact loop • Nested loops: loop inside another loop Example: for(int i=0;i<5;i++){ printf("%d", i); }
Jump Statements • break: exit loop/switch • continue: skip current iteration • goto: jump to a label Example: for(int i=0;i<5;i++){ if(i==3) continue; printf("%d", i); }