C PROGRAMMING
FUNDAMENTALS
STUDY GUIDE
■■ Exam Prep Edition ■■
Data Types | Operators | Control Flow
Functions | Arrays | Algorithms
Common Mistakes | Exam Questions | Decision Trees
For students in introductory university C programming courses
Covers all topics from basic syntax through 1D arrays
TABLE OF CONTENTS
1. C Language Fundamentals
1.1 Program Structure & Compilation
1.2 Data Types
1.3 Variables & Constants
1.4 Operators
1.5 Type Casting
2. Input / Output
2.1 printf() — Formatted Output
2.2 scanf() — Formatted Input
2.3 Format Specifiers
3. Control Structures
3.1 if / else if / else
3.2 Nested if Statements
3.3 switch / case
3.4 Ternary Operator
4. Loops
4.1 for Loop
4.2 while Loop
4.3 do-while Loop
4.4 break & continue
4.5 Nested Loops
5. Functions
5.1 Defining & Calling Functions
5.2 Return Types & Parameters
5.3 Scope & Local Variables
5.4 Function Prototypes
6. 1D Arrays
6.1 Declaration & Initialization
6.2 Accessing & Modifying Elements
6.3 Arrays in Loops
6.4 Arrays as Function Parameters
6.5 Common Array Algorithms
7. Problem-Solving Strategy
7.1 Reading Scenario Questions
7.2 Decision Tree: Syntax Selector
7.3 Worked Examples (5 Problems)
8. Common Student Mistakes
8.1 Off-by-one Errors
8.2 Assignment vs Equality
8.3 Array Index Confusion
8.4 Type Mismatches
8.5 Semicolons & Braces
8.6 scanf & printf Errors
8.7 Uninitialized Variables
9. Exam Question Bank
9.1 Trace the Output Questions
9.2 Write the Code Questions
9.3 Find the Bug Questions
9.4 Array Algorithm Questions
9.5 Function Questions
C Programming Fundamentals Study Guide • Page 3 of 31
CORE CONCEPTS
SECTION 1: C LANGUAGE FUNDAMENTALS
1.1 Program Structure & Compilation
Every C program follows a fixed skeleton. Understanding this structure is the first step to writing
correct code.
Minimal C Program
#include <stdio.h> // Include the standard I/O library
int main() {
// Your code goes here
printf("Hello, World!\n");
return 0; // Signal successful program exit
}
#include <stdio.h> — This line tells the compiler to load the Standard Input/Output library. You need
it whenever you use printf or scanf. Think of it as importing a toolbox.
• int main() — The entry point. Every C program starts executing from main().
• return 0; — Tells the operating system the program finished without errors.
• { } — Curly braces define a block of code. Every opening brace must have a matching closing
brace.
■ TIP Every statement in C ends with a semicolon ; — forgetting it is the most common compiler error
for beginners.
1.2 Data Types
C is a statically typed language — you must declare the type of every variable before using it. The
type tells the compiler how much memory to allocate and how to interpret the stored bits.
Format
Type Size (typical) Range / Values Use When...
Specifier
-2,147,483,648 to Counting, indexing, whole
int 4 bytes %d or %i
2,147,483,647 numbers
Decimal numbers (less
float 4 bytes ~6–7 decimal digits precision %f
precision)
C Programming Fundamentals Study Guide • Page 4 of 31
~15–16 decimal digits Decimal numbers (more
double 8 bytes %lf
precision precision)
char 1 byte Single character: 'A', 'z', '5', '@' %c Single letters, symbols
long 8 bytes Very large whole numbers %ld Large integers
1.3 Variables & Constants
A variable is a named memory location whose value can change. A constant is a value that never
changes during execution.
Variables & Constants
// Variable declaration
int age; // Declared but uninitialized (dangerous!)
int score = 100; // Declared AND initialized — always do this
float temperature = 36.5;
char grade = 'A';
// Constants — value cannot be changed after definition
#define PI 3.14159 // Preprocessor constant (no type, no semicolon after
value)
const int MAX = 100; // const keyword constant
// Multiple variables of the same type
int x = 5, y = 10, z = 0;
■ TIP Variable naming rules: start with a letter or underscore, no spaces, no special characters
(except _), case-sensitive (age ≠ Age ≠ AGE).
1.4 Operators
Operators are symbols that perform operations on values. Knowing operator precedence (which runs
first) prevents logic errors.
Category Operators Example Result
Arithmetic + - * / % 10 % 3 1 (remainder)
Comparison == != < > <= >= 5 != 3 1 (true)
Logical && || ! (x>0) && (x<10) 1 if x is between 0 and 10
Assignment = += -= *= /= %= x += 5 Same as x = x + 5
Increment/Decrem
++ -- i++ or ++i Adds 1 to i
ent
C Programming Fundamentals Study Guide • Page 5 of 31
Arithmetic Operators Demo
int a = 10, b = 3;
int sum = a + b; // 13
int diff = a - b; // 7
int product = a * b; // 30
int quotient= a / b; // 3 (integer division — decimal truncated!)
int remainder = a % b; // 1 (modulo — very useful!)
// WARNING: 10 / 3 = 3 (not 3.333) when both are integers
// To get 3.333, use: (float)a / b
■ TIP The % (modulo) operator gives the remainder after division. Use it to: check even/odd
(n%2==0), wrap around arrays, extract digits.
1.5 Type Casting
Type casting forces a value to be treated as a different type. This is essential when dividing integers
but wanting a decimal result.
Type Casting — Integer Division Trap
int a = 7, b = 2;
float result;
result = a / b; // result = 3.0 (wrong! integer division first)
result = (float)a / b; // result = 3.5 (correct! cast a to float first)
result = (float)(a / b); // result = 3.0 (wrong! division happens first)
C Programming Fundamentals Study Guide • Page 6 of 31
printf & scanf
SECTION 2: INPUT / OUTPUT
2.1 printf() — Formatted Output
printf() prints text and values to the screen. It uses format specifiers (starting with %) as
placeholders for variable values.
printf Examples
int age = 20;
float gpa = 3.75;
char initial = 'A';
printf("Hello!\n");
printf("Age: %d\n", age);
printf("GPA: %.2f\n", gpa); // .2 = 2 decimal places
printf("Initial: %c\n", initial);
printf("Age=%d, GPA=%.1f\n", age, gpa); // Multiple values
Escape sequences are special characters inside strings:
Sequence Meaning Example Output
\n Newline (go to next line) Line break
\t Tab (indent) (4-8 spaces)
\\ Print a literal backslash \
\" Print a literal quote "
2.2 scanf() — Formatted Input
scanf() reads input from the keyboard and stores it in variables. Always use the & (address-of)
operator before variable names — except for arrays.
C Programming Fundamentals Study Guide • Page 7 of 31
scanf Examples
int age;
float salary;
char letter;
printf("Enter your age: ");
scanf("%d", &age); // & is REQUIRED for int, float, char
printf("Enter salary: ");
scanf("%f", &salary);
printf("Enter a letter: ");
scanf(" %c", &letter); // Note the space before %c — skips whitespace
■ TIP The & before variable names in scanf is mandatory. It gives scanf the memory address where it
should store the value. Forgetting it causes undefined behavior (crashes or garbage values).
2.3 Format Specifiers Summary
Specifier Type scanf printf Notes
%d int ✓ ✓ Decimal integer
%f float ✓ ✓ Floating point
%lf double ✓ (required) same as %f Use %lf in scanf for double
%c char ✓ ✓ Single character
%s string (char[]) ✓ ✓ No & needed in scanf
%.2f float/double — ✓ 2 decimal places
C Programming Fundamentals Study Guide • Page 8 of 31
DECISIONS & BRANCHING
SECTION 3: CONTROL STRUCTURES
3.1 if / else if / else
The if statement evaluates a condition. If it is true (non-zero), the associated block runs. Use else if to
check more conditions, and else as a final fallback.
if / else if / else
// Syntax Template
if (condition1) {
// runs if condition1 is true
} else if (condition2) {
// runs if condition1 false AND condition2 true
} else {
// runs if ALL conditions above are false
}
// Real Example: Grade Classifier
int marks = 75;
if (marks >= 90) {
printf("Grade: A\n");
} else if (marks >= 80) {
printf("Grade: B\n");
} else if (marks >= 70) {
printf("Grade: C\n");
} else {
printf("Grade: F\n");
}
■ TIP Conditions use == (comparison), NOT = (assignment). Writing if (x = 5) is a bug — it assigns 5
to x and is always true!
3.2 switch / case
Use switch when you are comparing one variable against multiple exact values. It is cleaner than a
long chain of else-if for this purpose.
C Programming Fundamentals Study Guide • Page 9 of 31
switch / case — Day of Week
int day = 3;
switch (day) {
case 1: printf("Monday\n"); break;
case 2: printf("Tuesday\n"); break;
case 3: printf("Wednesday\n"); break;
case 4: printf("Thursday\n"); break;
case 5: printf("Friday\n"); break;
default: printf("Weekend\n");
}
// Output: Wednesday
■ TIP break is required at the end of each case. Without it, execution 'falls through' to the next case
automatically — a common source of bugs.
3.3 Ternary Operator
The ternary operator is a compact one-line if-else. Use it for simple assignments based on a
condition.
Ternary Operator
// Syntax: variable = (condition) ? value_if_true : value_if_false;
int x = 10;
int abs_val = (x >= 0) ? x : -x; // abs_val = 10
int a = 5, b = 8;
char *bigger = (a > b) ? "a" : "b"; // bigger = "b"
C Programming Fundamentals Study Guide • Page 10 of 31
REPETITION & ITERATION
SECTION 4: LOOPS
4.1 for Loop
The for loop is best when you know exactly how many times to repeat. It packs initialization,
condition, and update into one line.
for Loop Variations
// init condition update
for ( int i=0; i < 5; i++ ) {
printf("%d ", i);
}
// Output: 0 1 2 3 4
// Counting DOWN
for ( int i=10; i > 0; i--) {
printf("%d ", i);
}
// Output: 10 9 8 7 6 5 4 3 2 1
// Step by 2
for ( int i=0; i <= 10; i+=2) {
printf("%d ", i);
}
// Output: 0 2 4 6 8 10
4.2 while Loop
Use while when you do not know in advance how many iterations are needed. The condition is
checked before each iteration.
C Programming Fundamentals Study Guide • Page 11 of 31
while Loop
// Keep asking until valid input
int num = -1;
while (num < 0) {
printf("Enter a positive number: ");
scanf("%d", &num);
}
// printf("You entered: %d\n", num);
// Count digits of a number
int n = 12345, count = 0;
while (n > 0) {
count++;
n /= 10; // Remove last digit
}
// printf("Digits: %d\n", count); // Output: 5
4.3 do-while Loop
The do-while loop executes the body at least once, then checks the condition. Use it for menu-driven
programs.
do-while — Menu Loop
int choice;
do {
printf("\n1. Add\n2. Subtract\n3. Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);
} while (choice != 3); // Keep looping until user picks Exit
4.4 break & continue
C Programming Fundamentals Study Guide • Page 12 of 31
break & continue
// break: exit the loop immediately
for ( int i=0; i<10; i++) {
if (i == 5) break; // Stop when i reaches 5
printf("%d ", i);
}
// Output: 0 1 2 3 4
// continue: skip this iteration, go to next
for ( int i=0; i<10; i++) {
if (i % 2 == 0) continue; // Skip even numbers
printf("%d ", i);
}
// Output: 1 3 5 7 9
4.5 Nested Loops
A nested loop is a loop inside another loop. The inner loop completes ALL its iterations for EACH
iteration of the outer loop.
Nested Loop — Multiplication Table
// Print a multiplication table (3x3)
for ( int i=1; i<=3; i++) { // Outer: rows
for ( int j=1; j<=3; j++) { // Inner: columns
printf("%d\t", i*j);
}
printf("\n");
}
// Output:
// 1 2 3
// 2 4 6
// 3 6 9
// Total iterations = outer_count × inner_count = 3 × 3 = 9
C Programming Fundamentals Study Guide • Page 13 of 31
MODULAR PROGRAMMING
SECTION 5: FUNCTIONS
5.1 Anatomy of a Function
A function is a reusable named block of code. It takes inputs (parameters), does work, and optionally
returns a result. Functions prevent code repetition and make programs easier to understand.
Function Structure
// return_type name (parameters)
int add (int a, int b)
{
int result = a + b;
return result; // Must return same type as return_type
}
int main() {
int sum = add(3, 7); // CALLING the function
printf("Sum = %d\n", sum); // Output: Sum = 10
return 0;
}
5.2 Return Types & void Functions
C Programming Fundamentals Study Guide • Page 14 of 31
Function Return Types
// void: function returns nothing
void printStars(int n) {
for ( int i=0; i<n; i++)
printf("*");
printf("\n");
}
// int: function returns an integer
int square(int x) {
return x * x;
}
// float: function returns a float
float average(float a, float b) {
return (a + b) / 2.0;
}
int main() {
printStars(5); // Output: *****
printf("%d\n", square(4)); // Output: 16
printf("%.2f\n", average(8.0, 5.0)); // Output: 6.50
return 0;
}
5.3 Function Prototypes
If you define a function after main(), you must declare its prototype above main(). A prototype is just
the function signature followed by a semicolon.
Function Prototype
#include <stdio.h>
int multiply(int a, int b); // PROTOTYPE — semicolon at end!
int main() {
printf("%d\n", multiply(4, 5)); // Works even though body is below
return 0;
}
int multiply(int a, int b) { // DEFINITION — full function body
return a * b;
}
C Programming Fundamentals Study Guide • Page 15 of 31
COLLECTIONS OF DATA
SECTION 6: 1D ARRAYS
6.1 Declaration & Initialization
An array stores multiple values of the same type under one name. Elements are accessed by their
index, which always starts at 0.
Array Declaration & Initialization
// Declaration: type name [size]
int scores[5]; // 5 integers, uninitialized
int marks[5] = {90, 85, 78, 92, 88}; // Initialized at declaration
float temps[3] = {36.5, 37.0, 36.8};
// Partial initialization — rest filled with 0
int arr[5] = {1, 2}; // arr = {1, 2, 0, 0, 0}
// Initialize ALL elements to 0
int zeros[10] = {0};
// Size determined automatically
int nums[] = {10, 20, 30, 40}; // Size = 4
6.2 Indexing — The Golden Rule
For an array of size N: valid indices are 0 to N-1. Index N does NOT exist — accessing it is an error
called a buffer overflow.
Array Indexing
int arr[5] = {10, 20, 30, 40, 50};
// Index: [0] [1] [2] [3] [4]
// Reading elements
// printf("%d\n", arr[0]); // 10
// printf("%d\n", arr[4]); // 50
// Modifying elements
arr[2] = 99; // arr = {10, 20, 99, 40, 50}
// DANGER: arr[5] is OUT OF BOUNDS — undefined behavior!
// arr[-1] is also invalid.
6.3 Arrays with Loops
C Programming Fundamentals Study Guide • Page 16 of 31
Arrays and loops are natural partners. The loop variable serves as the array index, automatically
cycling through all elements.
Array Traversal Algorithms
#define SIZE 5
int arr[SIZE] = {3, 7, 1, 9, 4};
// Print all elements
for ( int i = 0; i < SIZE; i++) {
printf("arr[%d] = %d\n", i, arr[i]);
}
// Sum all elements
int sum = 0;
for ( int i = 0; i < SIZE; i++) {
sum += arr[i];
}
// printf("Sum = %d\n", sum); // Output: 24
// Find the maximum
int max = arr[0]; // Start by assuming first is max
for ( int i = 1; i < SIZE; i++) { // Start from index 1
if (arr[i] > max)
max = arr[i];
}
// printf("Max = %d\n", max); // Output: 9
6.4 Arrays as Function Parameters
When you pass an array to a function, you also pass its size. Arrays are passed by reference —
changes inside the function affect the original array.
C Programming Fundamentals Study Guide • Page 17 of 31
Arrays as Function Parameters
// Function that calculates sum of an array
int arraySum(int arr[], int size) {
int total = 0;
for ( int i = 0; i < size; i++)
total += arr[i];
return total;
}
// Function that fills array with user input
void fillArray(int arr[], int size) {
for ( int i = 0; i < size; i++) {
printf("Enter element %d: ", i);
scanf("%d", &arr[i]);
}
}
int main() {
int scores[4];
fillArray(scores, 4);
printf("Sum = %d\n", arraySum(scores, 4));
return 0;
}
C Programming Fundamentals Study Guide • Page 18 of 31
HOW TO DECODE EXAM QUESTIONS
SECTION 7: PROBLEM-SOLVING STRATEGY
7.1 Reading Scenario Questions
Exam questions describe a problem in English. Your job is to translate the English into C syntax. Use
these steps:
• Step 1 — Identify the DATA: What values are involved? → Choose data types
• Step 2 — Identify the QUANTITY: Single value or multiple? → Use variable vs array
• Step 3 — Identify the REPETITION: Does something repeat? → Loop needed
• Step 4 — Identify the DECISION: Is there a condition ('if', 'only when', 'unless')? → if/switch
• Step 5 — Identify the REUSE: Is the same process done multiple times? → Function
7.2 Decision Tree: Syntax Selector
Use this table whenever you read a question and are unsure which C concept to use:
If the question says... → Use this C concept Key Syntax
'store a number / name / value' Variable int x; float y; char c;
'store multiple / a list of / N values' Array int arr[N];
'repeat N times / for each / loop' for loop for(i=0; i<N; i++)
'keep going until / while condition' while loop while(condition){...}
'at least once / menu / retry' do-while loop do{...}while(cond);
'if / only when / otherwise / check' if / else if(cond){...}else{...}
'depending on choice / case 1/2/3' switch / case switch(x){case 1:...}
'write a function / reusable block' Function int funcName(params){...}
'sum / total / count / average' Accumulator + loop sum+=arr[i]; avg=sum/n;
'find max / min / largest / smallest' Comparison in loop if(arr[i]>max) max=arr[i];
'read from user / take input' scanf() scanf("%d",&x;);
'display / print / output / show' printf() printf("%d\n",x);
C Programming Fundamentals Study Guide • Page 19 of 31
7.3 Worked Examples
EXAMPLE 1: Sum of N Numbers
■ PROBLEM Question: Write a program that asks the user how many numbers they want to enter,
reads those numbers, and displays their sum.
Thinking Process:
• 'how many numbers' → need an int variable for count (n)
• 'reads those numbers' → need to repeat → loop (for loop because we know count)
• 'displays their sum' → need an accumulator variable (sum)
Solution — Sum of N Numbers
#include <stdio.h>
int main() {
int n, num, sum = 0; // sum starts at 0
printf("How many numbers? ");
scanf("%d", &n);
for ( int i = 1; i <= n; i++) { // Repeat n times
printf("Enter number %d: ", i);
scanf("%d", &num);
sum += num; // Add each number to sum
}
printf("Sum = %d\n", sum);
return 0;
}
EXAMPLE 2: Even or Odd Checker
■ PROBLEM Question: Write a function that receives an integer and prints whether it is even or odd.
Thinking Process:
• 'write a function' → define a function
• 'receives an integer' → parameter of type int
• 'even or odd' → condition → if/else. Use modulo: n%2==0 means even
C Programming Fundamentals Study Guide • Page 20 of 31
Solution — Even/Odd Checker
#include <stdio.h>
void checkEvenOdd(int n) {
if (n % 2 == 0)
printf("%d is Even\n", n);
else
printf("%d is Odd\n", n);
}
int main() {
checkEvenOdd(4); // Output: 4 is Even
checkEvenOdd(7); // Output: 7 is Odd
return 0;
}
EXAMPLE 3: Find Minimum in Array
■ PROBLEM Question: Write a program that reads 5 integers into an array and finds the smallest
value.
Thinking Process:
• '5 integers into an array' → int arr[5]
• 'reads' → scanf in a loop
• 'smallest value' → start with arr[0] as min, loop and compare
C Programming Fundamentals Study Guide • Page 21 of 31
Solution — Find Minimum
#include <stdio.h>
int main() {
int arr[5];
for ( int i = 0; i < 5; i++) {
printf("Enter element %d: ", i+1);
scanf("%d", &arr[i]);
}
int min = arr[0]; // Assume first element is minimum
for ( int i = 1; i < 5; i++) { // Compare from index 1 onward
if (arr[i] < min)
min = arr[i];
}
printf("Minimum = %d\n", min);
return 0;
}
EXAMPLE 4: Count Positive Numbers in Array
■ PROBLEM Question: Write a function that takes an integer array and its size, and returns the count
of positive numbers (> 0).
Solution — Count Positives
#include <stdio.h>
int countPositive(int arr[], int size) {
int count = 0;
for ( int i = 0; i < size; i++) {
if (arr[i] > 0)
count++;
}
return count;
}
int main() {
int nums[] = {-3, 5, 0, 8, -1, 4};
int result = countPositive(nums, 6);
printf("Positive count: %d\n", result); // Output: 3
return 0;
}
C Programming Fundamentals Study Guide • Page 22 of 31
EXAMPLE 5: Factorial with Function
■ PROBLEM Question: Write a function that calculates the factorial of a non-negative integer n. (n! =
1 × 2 × 3 × ... × n)
Thinking Process:
• 'multiply 1 through n' → loop from 1 to n, multiply into accumulator
• Factorial of 0 = 1 (special case, handle with if)
Solution — Factorial
#include <stdio.h>
int factorial(int n) {
if (n == 0) return 1; // Base case: 0! = 1
int result = 1;
for ( int i = 1; i <= n; i++) {
result *= i; // result = result * i
}
return result;
}
int main() {
printf("5! = %d\n", factorial(5)); // Output: 120
printf("0! = %d\n", factorial(0)); // Output: 1
return 0;
}
C Programming Fundamentals Study Guide • Page 23 of 31
LEARN FROM ERRORS
SECTION 8: COMMON STUDENT MISTAKES
8.1 Off-by-one Error in Loops
This is the most common loop mistake. It happens when loop boundaries are one step too many or
too few — causing one extra or one missing iteration.
✗ WRONG: Using <= instead of < when iterating over array of size N
// WRONG — accesses arr[5] which doesn't exist (size is 5, last index is 4)
int arr[5] = {1,2,3,4,5};
for ( int i=0; i<=5; i++) { // BUG: i goes 0,1,2,3,4,5
printf("%d ", arr[i]); // arr[5] is OUT OF BOUNDS
}
✓ CORRECT: Use i < size (strict less than)
// CORRECT
for ( int i=0; i<5; i++) { // i goes 0,1,2,3,4 — exactly 5 elements
printf("%d ", arr[i]);
}
8.2 Using = Instead of == in Conditions
The single equal sign (=) is ASSIGNMENT. The double equal sign (==) is COMPARISON. Confusing
them creates logic bugs that are hard to spot because the code compiles without error.
✗ WRONG: if (x = 5) — this ASSIGNS 5 to x, then checks if x is non-zero (always true!)
// WRONG
int x = 3;
if (x = 5) { // BUG: x becomes 5, condition is always true
printf("This always prints\n");
}
✓ CORRECT: if (x == 5) — this COMPARES x to 5
C Programming Fundamentals Study Guide • Page 24 of 31
// CORRECT
if (x == 5) {
printf("x is 5\n");
}
8.3 Forgetting & in scanf
scanf needs the memory address of the variable, provided by the & (address-of) operator. Without it,
scanf receives a garbage value and attempts to write to an invalid memory location.
✗ WRONG: scanf("%d", age); — missing & causes undefined behavior / crash
// WRONG
int age;
scanf("%d", age); // BUG: passing value of age (garbage) not its address
// CORRECT
scanf("%d", &age); // & gives the memory address — required!
■ TIP Exception: char arrays (strings) do NOT use & because the array name itself is already an
address. Example: scanf("%s", name); not scanf("%s", &name;);
8.4 Integer Division Truncation
When both operands are integers, C performs integer division — any decimal part is discarded, not
rounded.
✗ WRONG: int avg = sum / 3; when sum is 10 gives 3, not 3.33
// WRONG — if sum = 10
int sum = 10;
float avg = sum / 3; // 10/3 = 3 (integer), then stored as 3.0
// CORRECT — cast at least one operand to float
float avg = (float)sum / 3; // 10.0/3 = 3.333...
8.5 Array Index Out of Bounds
Accessing arr[N] when the array has N elements is out of bounds. Valid indices are 0 to N-1. C does
not check array bounds — you get silent corruption.
C Programming Fundamentals Study Guide • Page 25 of 31
int arr[5] = {10, 20, 30, 40, 50};
// Valid: arr[0] through arr[4]
// WRONG: arr[5], arr[-1], arr[100] — undefined behavior
// Common mistake in user input:
int n = 5;
int arr[5];
for ( int i = 1; i <= n; i++) { // BUG: i starts at 1, last i=n=5
scanf("%d", &arr[i]); // arr[5] is accessed — OUT OF BOUNDS
}
// Fix: for (int i=0; i<n; i++)
8.6 Uninitialized Variables
Local variables in C have garbage values until explicitly assigned. Using them produces
unpredictable results.
// WRONG — sum has garbage value
int sum;
for ( int i=0; i<5; i++)
sum += i; // Adding to garbage!
// CORRECT — initialize sum to 0 before using as accumulator
int sum = 0;
for ( int i=0; i<5; i++)
sum += i; // sum = 0+1+2+3+4 = 10
8.7 Missing Semicolons & Mismatched Braces
// Missing semicolon — compiler error
int x = 5 // ERROR: expected ';'
int y = 10;
// for loop with semicolon — creates infinite or null loop
for (int i=0; i<5; i++); // WARNING: the ; ends the loop immediately!
{ // This block runs only ONCE, not 5 times
printf("%d\n", i);
}
C Programming Fundamentals Study Guide • Page 26 of 31
PRACTICE & PATTERNS
SECTION 9: EXAM QUESTION BANK
9.1 Trace the Output Questions
These questions give you code and ask what it prints. Technique: trace variable values step by step,
iteration by iteration.
Q1. What is the output of this code?
int x = 1;
while (x <= 5) {
if (x % 2 != 0)
printf("%d ", x);
x++;
}
✓ CORRECT: Output: 1 3 5 (prints x when x is odd: 1%2=1, 3%2=1, 5%2=1)
Q2. What does this nested loop print?
for ( int i=1; i<=3; i++) {
for ( int j=1; j<=i; j++) {
printf("* ");
}
printf("\n");
}
✓ CORRECT: Output: * * * * * * (inner loop runs i times — triangle pattern)
Q3. Trace this array loop:
C Programming Fundamentals Study Guide • Page 27 of 31
int a[] = {5, 3, 8, 1, 6};
int result = 0;
for ( int i=0; i<5; i++) {
if (a[i] > result)
result = a[i];
}
// printf("%d", result);
✓ CORRECT: Output: 8 (This finds the maximum value in the array)
9.2 Write the Code Questions
Q4. Write a program to compute the average of N numbers entered by the user.
Solution — Average of N Numbers
#include <stdio.h>
int main() {
int n;
float sum = 0, num;
printf("Enter count: ");
scanf("%d", &n);
for ( int i=0; i<n; i++) {
scanf("%f", &num);
sum += num;
}
printf("Average = %.2f\n", sum / n);
return 0;
}
Q5. Write a function that reverses the elements of an integer array.
C Programming Fundamentals Study Guide • Page 28 of 31
Solution — Reverse Array
void reverseArray(int arr[], int size) {
int left = 0, right = size - 1;
while (left < right) {
int temp = arr[left]; // Swap
arr[left] = arr[right];
arr[right]= temp;
left++;
right--;
}
}
9.3 Find the Bug Questions
Q6. Find and fix the bug:
int factorial(int n) {
int result; // BUG 1: uninitialized
for ( int i=1; i<=n; i++)
result *= i;
return result;
}
✓ CORRECT: Fix: Change 'int result;' to 'int result = 1;' (factorial starts at 1, not garbage)
Q7. Find the bug in this search:
int arr[5] = {2, 4, 6, 8, 10};
int target = 6;
for ( int i=1; i<=5; i++) { // BUG: starts at 1, ends at 5
if (arr[i] == target)
printf("Found!\n");
}
✓ CORRECT: Fix: for(int i=0; i<5; i++) — must start at 0, use < not <=
9.4 Array Algorithm Questions
Q8. Write code to count how many elements in an array are greater than the average.
C Programming Fundamentals Study Guide • Page 29 of 31
Two-Pass Array Algorithm
#include <stdio.h>
#define N 6
int main() {
int arr[N] = {4, 7, 2, 9, 5, 8};
float sum = 0;
// First pass: calculate average
for ( int i=0; i<N; i++) sum += arr[i];
float avg = sum / N;
// Second pass: count elements > average
int count = 0;
for ( int i=0; i<N; i++)
if (arr[i] > avg) count++;
printf("Average: %.2f\n", avg);
printf("Above average: %d\n", count);
return 0;
}
Q9. Write a function that checks if an array is sorted in ascending order.
Check if Array is Sorted
// Returns 1 (true) if sorted ascending, 0 (false) otherwise
int isSorted(int arr[], int size) {
for ( int i=0; i<size-1; i++) {
if (arr[i] > arr[i+1])
return 0; // Found an out-of-order pair
}
return 1; // No violations found
}
9.5 Typical Exam Patterns — Quick Reference
These patterns appear repeatedly on exams. Memorizing them gives you a structural head start.
Pattern Key Variables Needed Loop Structure
Sum / Total sum=0 sum += arr[i];
Average sum=0, then avg=sum/n sum+=arr[i]; avg=sum/n after loop
Count (with condition) count=0 if(condition) count++;
C Programming Fundamentals Study Guide • Page 30 of 31
Maximum max=arr[0] i starts at 1; if(arr[i]>max) max=arr[i];
Minimum min=arr[0] i starts at 1; if(arr[i]<min) min=arr[i];
Linear Search found=0 if(arr[i]==target){found=1; break;}
left=0, right=size-1,
Reverse Array while(left<right) swap and move inward
temp
Print Pyramid outer i, inner j for(j=1;j<=i;j++) nested in outer
Good luck on your exams. The key is consistent practice — read the question carefully, identify the
pattern, then write the code.
C Programming Fundamentals Study Guide • Page 31 of 31