C Language Notes
Unit 2: Control Structures and Functions
1. Control Structures:
A. Conditional Statements:
- if: Executes a block of code if a condition is true.
Example:
if (a > b) {
printf("a is greater than b");
- if-else: Executes one block of code if a condition is true, otherwise another block.
- switch: Tests a variable for equality against a list of values.
Example:
switch (choice) {
case 1: printf("Option 1"); break;
case 2: printf("Option 2"); break;
default: printf("Invalid Option");
B. Looping Statements:
- for: Repeats a block of code for a specific number of times.
Example:
for (int i = 0; i < 5; i++) {
printf("%d", i);
Page 1
C Language Notes
- while: Repeats as long as a condition is true.
- do-while: Executes at least once before checking the condition.
2. Functions in C:
- Functions break a program into smaller, reusable blocks.
- Syntax:
return_type function_name(parameters) {
// function body
Example:
int add(int a, int b) {
return a + b;
3. Predefined Functions:
- printf(): Prints data to the screen.
- scanf(): Reads input from the user.
- pow(), sqrt(): Math functions from <math.h> library.
Mastering control structures and functions is key to writing efficient programs in C.
Page 2