Data types define the type and size of data a variable can store.
| Type | Description | Example |
|---|---|---|
int | Integer (whole number) | int age = 21; |
float | Single-precision floating point (decimal number) | float price = 19.99; |
double | Double-precision floating point (more precise) | double pi = 3.14159265; |
char | Single character | char grade = 'A'; |
An expression is a combination of variables, constants, and operators that evaluates to a single value. Example: (a + b) / 2.
+, -, *, /, % (modulus/remainder)== (equal to), != (not equal to), <, >, <=, >=&& (AND), || (OR), ! (NOT)=, +=, -=, *=, /=Handled using standard library functions from <stdio.h>.
printf()Used to print formatted output to the console.
printf("Hello, %s! You are %d years old.\n", "Alex", 25);
Output: Hello, Alex! You are 25 years old.
%d for integers%f for floats/doubles%c for characters%s for strings\n for a new linescanf()Used to read formatted input from the console.
scanf() requires the address of the variable, using the & (address-of) operator.
int age;
printf("Enter your age: ");
scanf("%d", &age);A basic C program structure:
// 1. Preprocessor Directive
#include <stdio.h>
// 2. Main function (entry point of the program)
int main() {
// 3. Variable declaration
int num1 = 10;
int num2 = 20;
int sum;
// 4. Logic
sum = num1 + num2;
// 5. Output
printf("The sum of %d and %d is %d\n", num1, num2, sum);
// 6. Return statement
return 0;
}These control the flow of program execution.
if-else: Used for conditional branching.
if (score >= 50) {
printf("Pass\n");
} else {
printf("Fail\n");
}switch: Used to select one of many code blocks to be executed.
break; statement in a switch case, which causes "fall-through."switch (grade) {
case 'A':
printf("Excellent\n");
break;
case 'B':
printf("Good\n");
break;
default:
printf("Try harder\n");
}while loop (Entry-controlled): Executes as long as the condition is true.
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}do-while loop (Exit-controlled): Always executes at least once.
int i = 1;
do {
printf("%d ", i);
i++;
} while (i <= 5);for loop: The most common loop for a known number of iterations.
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}break: Immediately exits the innermost loop or switch statement.continue: Skips the rest of the current iteration and moves to the next iteration of the loop.goto: Jumps to a labeled statement.
goto is highly discouraged as it makes code unreadable and hard to debug (spaghetti code).Using the above structures to solve problems from mathematics and statistics.
int n = 5;
long factorial = 1;
for (int i = 1; i <= n; i++) {
factorial = factorial * i;
}
printf("Factorial of %d = %ld\n", n, factorial);int count = 5;
float sum = 0;
float num;
printf("Enter %d numbers:\n", count);
for (int i = 0; i < count; i++) {
scanf("%f", &num);
sum += num;
}
printf("Average = %.2f\n", sum / count);