C Programming Study Notes — Unit II & III Reema Thareja Reference
C PROGRAMMING
EXAM STUDY NOTES
Unit II · Unit III
Based on: Programming in C — Reema Thareja
PART I — THEORY Concepts, Definitions, Syntax, Examples
PART II — PROGRAMS Complete Programs with Output
PART III — Q&A; 1-2 Mark Questions, MCQ, Output-based
UNIT II 2D Arrays: Declaration, Initialization, Access, Transpose, Sum, Difference, Product
UNIT III Introduction, Length, Upper/Lower Case, Concat, Append, Compare, Reverse, Built-in Functions
(Strings)
UNIT III Introduction, Declaration, Definition, Call, Return, Parameters (Call by Value/Reference), Passing Arrays,
(Functions) Built-in Functions, Recursion (GCD, Fibonacci)
Page 1 | 2D Arrays · Strings · Functions · Recursion
C Programming Study Notes — Unit II & III Reema Thareja Reference
PART I — THEORY
Concepts · Definitions · Syntax · Simple Examples
UNIT II: TWO-DIMENSIONAL ARRAYS
Introduction
Two-Dimensional Array (2D Array): An array that stores data in the form of a matrix (rows and columns). It is an array
of 1D arrays. Each element is identified by two subscripts: row index and column index.
Key Points:
• A 2D array is declared as: data_type array_name[row_size][column_size];
• Example: int marks[3][5]; — creates a matrix of 3 rows and 5 columns (15 elements total)
• First index selects the row; second selects the column
• Indexing starts from 0 — so marks[0][0] is the first element
• Elements are stored in Row Major Order (row by row) in memory
• Total elements = rows × columns
• Size of array in bytes = rows × cols × sizeof(data_type)
★ EXAM TIP: Declaration syntax and how many elements are stored are very common exam questions.
Declaration Syntax:
data_type array_name[row_size][column_size];
// Examples:
int marks[3][5]; // 3 rows, 5 cols = 15 integers
float salary[10][12]; // 10 rows, 12 cols = 120 floats
Initialization:
int marks[2][3] = {90, 87, 78, 68, 62, 71}; // row-by-row
int marks[2][3] = {{90,87,78}, {68,62,71}}; // nested braces (clearer)
int marks[2][3] = {0}; // initialize all to 0
★ If fewer values are provided, remaining elements are auto-initialized to 0. In 2D arrays, only the first (row) dimension size can be
omitted if fully initialized.
Accessing Elements (Input/Output):
// Reading elements using nested loops
for(i=0; i<rows; i++)
for(j=0; j<cols; j++)
scanf("%d", &arr[i][j]);
// Printing elements
for(i=0; i<rows; i++) {
printf("\n");
for(j=0; j<cols; j++)
printf("%d\t", arr[i][j]);
Memory Representation (Row Major Order):
Address of element A[I][J] = Base_Address + w × (N×(I−1) + (J−1))
where w = bytes per element, N = number of columns.
Page 2 | 2D Arrays · Strings · Functions · Recursion
C Programming Study Notes — Unit II & III Reema Thareja Reference
■ Important: C stores 2D arrays in Row Major Order — all elements of row 0 first, then row 1, etc.
OPERATIONS ON 2D ARRAYS
Transpose
Swapping rows with columns of a matrix A (m×n) gives matrix B (n×m).
B[j][i] = A[i][j]
Sum (Addition)
Two matrices must have the same dimensions. Add corresponding elements.
C[i][j] = A[i][j] + B[i][j]
Difference (Subtraction)
Subtract corresponding elements (same dimensions required).
C[i][j] = A[i][j] − B[i][j]
Product (Multiplication)
Columns of A must equal Rows of B. C[i][j] = Σ A[i][k]×B[k][j]
Result: if A is m×n and B is n×q, result C is m×q
★ EXAM TIP: Matrix Multiplication: cols of A must equal rows of B. This condition check is very frequently asked!
UNIT III: STRINGS — INTRODUCTION
String: A null-terminated character array. The last character is always '\0' (null character, ASCII 0). A string of n
characters requires n+1 memory locations.
• Strings are enclosed in double quotes (" "); characters in single quotes ('')
• Declared as: char str[size]; — can store size−1 usable characters
• When compiler assigns a string to array, it automatically appends \0
• The name of the string (array) acts as a pointer to the first character
• Header required for string built-in functions: #include <string.h>
• Reading: scanf("%s", str) stops at whitespace; gets(str) reads the full line including spaces
Declaration and Initialization Syntax:
char str[10]; // declaration (uninitialized)
char str[] = "HELLO"; // auto-size: 6 bytes (5 chars + \0)
char str[10] = "HELLO"; // size 10; remaining filled with \0
char str[] = {'H','E','L','L','O','\0'}; // character array form
STRING OPERATIONS
Finding Length of a String
Count characters until \0 is encountered. Manual method uses a loop. Built-in: strlen(str) returns length excluding the null
character.
char str[100]; int len=0;
gets(str);
while(str[len] != '\0') len++;
printf("Length = %d", len); // Manual
Page 3 | 2D Arrays · Strings · Functions · Recursion
C Programming Study Notes — Unit II & III Reema Thareja Reference
Converting to UPPERCASE
Subtract 32 from ASCII value of lowercase letters (a−z). Built-in: toupper(ch) from ctype.h.
while(str[i] != '\0') {
if(str[i] >= 'a' && str[i] <= 'z')
upper[j] = str[i] - 32;
else upper[j] = str[i];
i++; j++;
} upper[j] = '\0';
Converting to LOWERCASE
Add 32 to ASCII value of uppercase letters (A−Z). Built-in: tolower(ch) from ctype.h.
while(str[i] != '\0') {
if(str[i] >= 'A' && str[i] <= 'Z')
lower[j] = str[i] + 32;
else lower[j] = str[i];
i++; j++;
} lower[j] = '\0';
Concatenating Two Strings
Append characters of str2 to the end of str1. Built-in: strcat(str1, str2).
// Manual: move to end of str1, then copy str2
while(str1[i] != '\0') i++;
while(str2[j] != '\0') { str1[i] = str2[j]; i++; j++; }
str1[i] = '\0';
Appending a String (strncat)
Append first n characters of str2 to str1. Built-in: strncat(str1, str2, n).
// Appends only n characters of str2
strncat(str1, str2, 5); // appends first 5 chars of str2
Comparing Two Strings
Compare character by character using ASCII values. Returns 0 if equal, positive if str1 > str2, negative if str1 < str2. Built-in:
strcmp(str1, str2).
i = 0;
while(str1[i] == str2[i] && str1[i] != '\0') i++;
if(str1[i] == str2[i]) printf("Equal");
else if(str1[i] > str2[i]) printf("str1 > str2");
else printf("str1 < str2");
Reversing a String
Swap characters from both ends moving towards center. Built-in: strrev(str) (available in many compilers).
// Manual reversal
len = strlen(str);
for(i=0, j=len-1; i<j; i++, j--) {
temp=str[i]; str[i]=str[j]; str[j]=temp;
STRING BUILT-IN FUNCTIONS (string.h)
Page 4 | 2D Arrays · Strings · Functions · Recursion
C Programming Study Notes — Unit II & III Reema Thareja Reference
Function Syntax Description
strlen() strlen(str) Returns length of string (excludes \0)
strcpy() strcpy(dest, src) Copies src into dest
strncpy() strncpy(dest, src, n) Copies first n chars of src into dest
strcat() strcat(str1, str2) Appends str2 to end of str1
strncat() strncat(str1, str2, n) Appends first n chars of str2 to str1
strcmp() strcmp(str1, str2) Compares; returns 0 if equal
strncmp() strncmp(str1, str2, n) Compares first n characters
strchr() strchr(str, ch) Finds first occurrence of ch; returns pointer
strrchr() strrchr(str, ch) Finds last occurrence of ch
strstr() strstr(str1, str2) Finds first occurrence of str2 in str1
strrev() strrev(str) Reverses a string (non-standard)
strupr() strupr(str) Converts to uppercase (non-standard)
strlwr() strlwr(str) Converts to lowercase (non-standard)
★ EXAM TIP: strlen() does NOT count \0. strcpy() is destination first, source second. strcmp() returns 0 for equal
strings — very frequently asked!
Character Built-in Functions (ctype.h):
Function Description
toupper(c) Converts char to uppercase
tolower(c) Converts char to lowercase
isalpha(c) Returns non-zero if c is a letter
isdigit(c) Returns non-zero if c is a digit (0-9)
isalnum(c) Returns non-zero if c is alphanumeric
isspace(c) Returns non-zero if c is whitespace
isupper(c) Returns non-zero if c is uppercase
islower(c) Returns non-zero if c is lowercase
UNIT III: FUNCTIONS — INTRODUCTION
Function: A self-contained block of statements that performs a specific, well-defined task. A C program is made up of
one or more functions. Every C program must have a main() function.
Why Use Functions?
• Modularity: Break large programs into manageable, smaller parts
• Reusability: Write once, call multiple times from anywhere in the program
• Avoid repetition: Same code need not be written repeatedly
• Easy debugging: Each function can be tested independently
• Divide workload: Different programmers can write different functions
Function Declaration / Prototype
A function declaration (prototype) tells the compiler about the function's name, return type, and parameter types before it is
defined. It ends with a semicolon.
// Syntax:
Page 5 | 2D Arrays · Strings · Functions · Recursion
C Programming Study Notes — Unit II & III Reema Thareja Reference
return_type function_name(data_type param1, data_type param2, ...);
// Examples:
int sum(int a, int b); // accepts 2 ints, returns int
float avg(int a, int b); // returns float
void print(void); // no parameters, no return value
int find_largest(int a, int b, int c);
■ Important: Function declaration must end with a semicolon. If the function is defined before main(), declaration can be
skipped.
Function Definition
The actual body of the function — contains the code that runs when the function is called. Consists of a function header +
function body.
// Syntax:
return_type function_name(data_type param1, data_type param2) {
// function body
statements;
return value; // omit for void functions
// Example:
int sum(int a, int b) { // function header
int result; // function body
result = a + b;
return result;
Function Call
Invokes (executes) the function. Control jumps to the function, executes it, then returns to the calling function.
// Syntax:
function_name(argument1, argument2, ...);
// Or to store return value:
variable = function_name(arg1, arg2);
// Example:
total = sum(num1, num2); // FUNCTION CALL
★ EXAM TIP: Know the difference: Declaration = prototype with semicolon. Definition = actual code body. Call =
using the function.
Return Statement
Terminates execution of the current function and returns control (and optionally a value) to the calling function.
// Syntax:
return; // for void functions
return expression; // returns value to caller
// A function may have multiple return statements
int max(int a, int b) {
if(a > b) return a;
else return b;
Page 6 | 2D Arrays · Strings · Functions · Recursion
C Programming Study Notes — Unit II & III Reema Thareja Reference
• A void function cannot return a value.
• If no return type is specified, it defaults to int.
• Only one value can be returned by a function.
PASSING PARAMETERS TO A FUNCTION
Call by Value
Call by Value: A copy of the argument's value is passed to the function. Changes made inside the function do NOT affect
the original variable.
void add(int n) { // n is a COPY
n = n + 10; // changes local copy only
int main() {
int num = 2;
add(num);
printf("%d", num); // still prints 2
Call by Reference
Call by Reference: The address (reference) of the argument is passed using &. Changes made inside the function DO
affect the original variable. An ampersand (&) is placed after the type in the parameter list.
void add(int *n) { // pointer receives address
*n = *n + 10; // changes original via pointer
int main() {
int num = 2;
add(&num); // pass address
printf("%d", num); // prints 12
Call by Value Call by Reference
Copy of data passed Address of data passed
Original unchanged Original can be changed
Safe — no accidental modification Faster for large data
Cannot return multiple values Can modify multiple variables
Passing Arrays to Functions
Arrays are always passed to functions by reference (the base address is passed). This means the function can modify the
original array. The size of the array must be passed separately.
// Function prototype (array parameter):
void display(int arr[], int n); // or int *arr
// Function definition:
void display(int arr[], int n) {
for(int i=0; i<n; i++)
printf("%d ", arr[i]);
Page 7 | 2D Arrays · Strings · Functions · Recursion
C Programming Study Notes — Unit II & III Reema Thareja Reference
// Calling:
int main() {
int a[] = {1,2,3,4,5};
display(a, 5); // pass array name (base address)
★ EXAM TIP: Arrays are ALWAYS passed by reference. The array name = base address (pointer). This is a very
frequently tested concept.
BUILT-IN FUNCTIONS (Standard Library)
Header Functions Purpose
stdio.h printf(), scanf(), gets(), puts(), getchar(), putchar() Input/Output
math.h sqrt(), pow(), abs(), ceil(), floor(), log(), sin(), cos() Mathematics
string.h strlen(), strcpy(), strcat(), strcmp(), strrev() Strings
ctype.h toupper(), tolower(), isalpha(), isdigit(), isspace() Characters
stdlib.h malloc(), calloc(), free(), rand(), srand(), exit() Memory/Utility
RECURSIVE FUNCTIONS
Recursion: A technique where a function calls itself to solve a problem. Every recursive function must have a base case
(termination condition) to stop the infinite recursion.
• Base case: The condition that stops the recursion (e.g., n==0 or n==1)
• Recursive case: The function calls itself with a smaller/simpler input
• Recursion uses the system stack to store function calls
• Disadvantage: Uses more memory (stack overhead) and can be slower than iteration
• Advantage: Code is simpler and more readable for problems like GCD, Fibonacci, Factorial
GCD (Greatest Common Divisor) — Euclid's Algorithm
The GCD of two numbers is the largest integer that divides both. Using Euclid's algorithm: GCD(a,b) = GCD(b, a mod b) if b≠0;
GCD(a,0) = a (base case).
GCD(a, b) = { b, if b divides a (rem == 0)
{ GCD(b, a mod b), otherwise
Fibonacci Series
Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 ...
Each term is the sum of the two preceding terms.
FIB(n) = 1 if n <= 2; FIB(n) = FIB(n−1) + FIB(n−2) otherwise.
★ EXAM TIP: Write the base case correctly for both GCD (rem==0) and Fibonacci (n<=2). These programs appear in
every exam!
Recursion vs Iteration:
Recursion Iteration
Function calls itself Uses loops (for/while)
Uses system stack No extra stack overhead
Slower, more memory Faster, less memory
Shorter, elegant code Longer but straightforward
Top-down approach Bottom-up approach
Page 8 | 2D Arrays · Strings · Functions · Recursion
C Programming Study Notes — Unit II & III Reema Thareja Reference
PART II — IMPORTANT PROGRAMS
Complete Programs with Output
2D ARRAY PROGRAMS
■ P1: Read and Display a 2D Array (Matrix)
#include <stdio.h>
int main() {
int arr[2][2] = {12, 34, 56, 32};
int i, j;
for(i=0; i<2; i++) {
printf("\n");
for(j=0; j<2; j++)
printf("%d\t", arr[i][j]);
return 0;
}
Output:
12 34
56 32
Page 9 | 2D Arrays · Strings · Functions · Recursion
C Programming Study Notes — Unit II & III Reema Thareja Reference
■ P2: Matrix Addition (Sum of two m×n matrices)
#include <stdio.h>
int main() {
int i, j, rows, cols;
int mat1[5][5], mat2[5][5], sum[5][5];
printf("\nEnter rows and cols: "); scanf("%d%d",&rows,&cols);
printf("\nEnter matrix 1:\n");
for(i=0;i<rows;i++) for(j=0;j<cols;j++) scanf("%d",&mat1[i][j]);
printf("\nEnter matrix 2:\n");
for(i=0;i<rows;i++) for(j=0;j<cols;j++) scanf("%d",&mat2[i][j]);
// Compute sum
for(i=0;i<rows;i++)
for(j=0;j<cols;j++)
sum[i][j] = mat1[i][j] + mat2[i][j];
printf("\nResultant Matrix:\n");
for(i=0;i<rows;i++) {
printf("\n");
for(j=0;j<cols;j++) printf("%d\t", sum[i][j]);
return 0;
}
Output:
Enter rows and cols: 2 2
Resultant Matrix:
6 8
10 12
Page 10 | 2D Arrays · Strings · Functions · Recursion
C Programming Study Notes — Unit II & III Reema Thareja Reference
■ P3: Transpose of a 3×3 Matrix
#include <stdio.h>
int main() {
int i, j, mat[3][3], transposed[3][3];
printf("Enter 9 elements: ");
for(i=0;i<3;i++) for(j=0;j<3;j++) scanf("%d",&mat[i][j]);
// Transpose: swap row and column index
for(i=0;i<3;i++)
for(j=0;j<3;j++)
transposed[j][i] = mat[i][j];
printf("\nTransposed Matrix:\n");
for(i=0;i<3;i++) {
printf("\n");
for(j=0;j<3;j++) printf("%d\t", transposed[i][j]);
return 0;
}
Output:
Input: 1 2 3 / 4 5 6 / 7 8 9
Output: 1 4 7 / 2 5 8 / 3 6 9
Page 11 | 2D Arrays · Strings · Functions · Recursion
C Programming Study Notes — Unit II & III Reema Thareja Reference
■ P4: Matrix Multiplication (m×n × n×q)
#include <stdio.h>
int main() {
int i,j,k, rows1,cols1,rows2,cols2;
int mat1[5][5], mat2[5][5], res[5][5];
printf("\nRows and Cols of mat1: "); scanf("%d%d",&rows1,&cols1);
printf("\nRows and Cols of mat2: "); scanf("%d%d",&rows2,&cols2);
if(cols1 != rows2) { printf("Multiplication not possible!"); return 0; }
printf("\nEnter mat1: ");
for(i=0;i<rows1;i++) for(j=0;j<cols1;j++) scanf("%d",&mat1[i][j]);
printf("\nEnter mat2: ");
for(i=0;i<rows2;i++) for(j=0;j<cols2;j++) scanf("%d",&mat2[i][j]);
// Multiply
for(i=0;i<rows1;i++)
for(j=0;j<cols2;j++) {
res[i][j] = 0;
for(k=0;k<cols1;k++)
res[i][j] += mat1[i][k] * mat2[k][j];
printf("\nResult:\n");
for(i=0;i<rows1;i++) { printf("\n"); for(j=0;j<cols2;j++) printf("%d\t",res[i][j]); }
return 0;
}
Output:
Condition: cols of mat1 == rows of mat2
Key check: if(cols1 != rows2) → multiplication not possible!
Page 12 | 2D Arrays · Strings · Functions · Recursion
C Programming Study Notes — Unit II & III Reema Thareja Reference
■ P5: Find Max Marks Per Subject using 2D Array (Application)
#include <stdio.h>
int main() {
int marks[5][3], i, j, max_marks;
for(i=0;i<5;i++) {
printf("\nMarks of student %d in 3 subjects: ",i);
for(j=0;j<3;j++) scanf("%d",&marks[i][j]);
for(j=0;j<3;j++) {
max_marks = -999;
for(i=0;i<5;i++)
if(marks[i][j] > max_marks) max_marks = marks[i][j];
printf("\nHighest marks in subject %d = %d", j, max_marks);
return 0;
}
Output:
Highest marks in subject 0 = 99
Highest marks in subject 1 = 90
Highest marks in subject 2 = 100
■ P6: Pascal's Triangle using 2D Array
#include <stdio.h>
int main() {
int arr[7][7]={0}, row=2, col, i, j;
arr[0][0]=arr[1][0]=arr[1][1]=1;
while(row<=6) {
arr[row][0]=1;
for(col=1;col<=row;col++)
arr[row][col]=arr[row-1][col-1]+arr[row-1][col];
row++;
for(i=0;i<7;i++) {
printf("\n");
for(j=0;j<=i;j++) printf("%d\t",arr[i][j]);
return 0;
}
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Page 13 | 2D Arrays · Strings · Functions · Recursion
C Programming Study Notes — Unit II & III Reema Thareja Reference
STRING PROGRAMS
■ P7: Find Length of String (Manual + strlen)
#include <stdio.h>
#include <string.h>
int main() {
char str[100]; int i=0;
printf("\nEnter string: "); gets(str);
while(str[i] != '\0') i++; // manual count
printf("\nManual Length = %d", i);
printf("\nstrlen Length = %d", (int)strlen(str));
return 0;
}
Output:
Enter string: hello
Manual Length = 5
strlen Length = 5
■ P8: Convert String to Uppercase (Manual)
#include <stdio.h>
int main() {
char str[100], upper_str[100];
int i=0, j=0;
printf("\nEnter string: "); gets(str);
while(str[i] != '\0') {
if(str[i] >= 'a' && str[i] <= 'z')
upper_str[j] = str[i] - 32; // subtract 32 for uppercase
else
upper_str[j] = str[i];
i++; j++;
upper_str[j] = '\0';
printf("\nUppercase: %s", upper_str);
return 0;
}
Output:
Enter string: hello
Uppercase: HELLO
Page 14 | 2D Arrays · Strings · Functions · Recursion
C Programming Study Notes — Unit II & III Reema Thareja Reference
■ P9: Concatenate Two Strings (Manual)
#include <stdio.h>
int main() {
char str1[100], str2[50];
int i=0, j=0;
printf("\nEnter str1: "); gets(str1);
printf("\nEnter str2: "); gets(str2);
while(str1[i] != '\0') i++; // move to end of str1
while(str2[j] != '\0') {
str1[i] = str2[j];
i++; j++;
str1[i] = '\0';
printf("\nConcatenated: %s", str1);
return 0;
}
Output:
Enter str1: Hello
Enter str2: World
Concatenated: HelloWorld
■ P10: Compare Two Strings (Manual)
#include <stdio.h>
int main() {
char str1[50], str2[50];
int i=0;
printf("\nEnter str1: "); gets(str1);
printf("\nEnter str2: "); gets(str2);
while(str1[i]==str2[i] && str1[i]!='\0') i++;
if(str1[i]==str2[i]) printf("\nStrings are EQUAL");
else if(str1[i]>str2[i]) printf("\nstr1 > str2");
else printf("\nstr1 < str2");
return 0;
}
Output:
Enter str1: hello Enter str2: hello
Strings are EQUAL
Page 15 | 2D Arrays · Strings · Functions · Recursion
C Programming Study Notes — Unit II & III Reema Thareja Reference
■ P11: Reverse a String (Manual)
#include <stdio.h>
#include <string.h>
int main() {
char str[100], rev[100];
int i, len;
printf("\nEnter string: "); gets(str);
len = strlen(str);
for(i=0; i<len; i++)
rev[i] = str[len-1-i];
rev[len] = '\0';
printf("\nReversed: %s", rev);
return 0;
}
Output:
Enter string: hello
Reversed: olleh
Alternative: use strrev(str) directly (non-standard but common)
■ P12: Using String Built-in Functions (strcpy, strcmp, strcat)
#include <stdio.h>
#include <string.h>
int main() {
char s1[50]="Programming", s2[]="In C";
printf("\nstrlen(s1) = %d", (int)strlen(s1));
strcat(s1, s2);
printf("\nAfter strcat: %s", s1);
printf("\nstrcmp: %d", strcmp("abc","abc")); // 0 = equal
char s3[50];
strcpy(s3, "Hello");
printf("\nstrcpy s3: %s", s3);
return 0;
}
Output:
strlen(s1) = 11
After strcat: ProgrammingIn C
strcmp: 0
strcpy s3: Hello
FUNCTION PROGRAMS
Page 16 | 2D Arrays · Strings · Functions · Recursion
C Programming Study Notes — Unit II & III Reema Thareja Reference
■ P13: Add Two Numbers Using Functions
#include <stdio.h>
int sum(int a, int b); // FUNCTION DECLARATION
int main() {
int num1, num2, total;
printf("\nEnter two numbers: "); scanf("%d%d",&num1,&num2);
total = sum(num1, num2); // FUNCTION CALL
printf("\nTotal = %d", total);
return 0;
int sum(int a, int b) { // FUNCTION DEFINITION
int result;
result = a + b;
return result;
}
Output:
Enter two numbers: 20 30
Total = 50
■ P14: Find Largest of Three Numbers Using Functions
#include <stdio.h>
int find_largest(int a, int b, int c);
int main() {
int a, b, c;
printf("\nEnter 3 numbers: "); scanf("%d%d%d",&a,&b,&c);
printf("\nLargest = %d", find_largest(a,b,c));
return 0;
int find_largest(int a, int b, int c) {
if(a>=b && a>=c) return a;
else if(b>=a && b>=c) return b;
else return c;
}
Output:
Enter 3 numbers: 45 12 78
Largest = 78
Page 17 | 2D Arrays · Strings · Functions · Recursion
C Programming Study Notes — Unit II & III Reema Thareja Reference
■ P15: Factorial Using Functions (Iterative)
#include <stdio.h>
int Fact(int num);
int main() {
int n;
printf("\nEnter number: "); scanf("%d",&n);
printf("\nFactorial of %d = %d", n, Fact(n));
return 0;
int Fact(int num) {
int f=1, i;
for(i=num; i>=1; i--) f = f*i;
return f;
}
Output:
Enter number: 5
Factorial of 5 = 120
■ P16: Swap Using Call by Reference
#include <stdio.h>
void swap(int *a, int *b);
int main() {
int x=10, y=20;
printf("\nBefore: x=%d, y=%d", x, y);
swap(&x, &y);
printf("\nAfter: x=%d, y=%d", x, y);
return 0;
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
Output:
Before: x=10, y=20
After: x=20, y=10
Page 18 | 2D Arrays · Strings · Functions · Recursion
C Programming Study Notes — Unit II & III Reema Thareja Reference
■ P17: Passing Array to Function (Find Sum)
#include <stdio.h>
int array_sum(int arr[], int n);
int main() {
int a[] = {10, 20, 30, 40, 50};
printf("\nSum = %d", array_sum(a, 5));
return 0;
int array_sum(int arr[], int n) {
int sum=0, i;
for(i=0; i<n; i++) sum += arr[i];
return sum;
}
Output:
Sum = 150
RECURSIVE FUNCTION PROGRAMS
■ P18: Factorial Using Recursion
#include <stdio.h>
int Fact(int n);
int main() {
int num;
printf("\nEnter number: "); scanf("%d",&num);
printf("\nFactorial = %d", Fact(num));
return 0;
int Fact(int n) {
if(n==1) // BASE CASE
return 1;
return (n * Fact(n-1)); // RECURSIVE CALL
}
Output:
Enter number: 5
Factorial = 120
Working: Fact(5)=5×Fact(4)=5×4×Fact(3)=...=120
Page 19 | 2D Arrays · Strings · Functions · Recursion
C Programming Study Notes — Unit II & III Reema Thareja Reference
■ P19: GCD (Greatest Common Divisor) Using Recursion
#include <stdio.h>
int GCD(int x, int y); // FUNCTION DECLARATION
int main() {
int num1, num2, res;
printf("\nEnter two numbers: "); scanf("%d%d",&num1,&num2);
res = GCD(num1, num2); // FUNCTION CALL
printf("\nGCD of %d and %d = %d", num1, num2, res);
return 0;
int GCD(int x, int y) { // FUNCTION DEFINITION
int rem;
rem = x % y;
if(rem == 0) // BASE CASE: y divides x
return y;
else
return (GCD(y, rem)); // RECURSIVE CALL
}
Output:
Enter two numbers: 62 8
GCD of 62 and 8 = 2
Working: GCD(62,8)→GCD(8,6)→GCD(6,2)→GCD(2,0) rem=0 → return 2
■ P20: Fibonacci Series Using Recursion
#include <stdio.h>
int Fibonacci(int num);
int main() {
int n, i;
printf("\nEnter number of terms: "); scanf("%d",&n);
printf("\nFibonacci Series: ");
for(i=0; i<n; i++)
printf("\nFibonacci(%d) = %d", i, Fibonacci(i));
return 0;
int Fibonacci(int num) {
if(num <= 2) // BASE CASE
return 1;
return (Fibonacci(num-1) + Fibonacci(num-2)); // RECURSIVE
}
Output:
Fibonacci(0)=1 Fibonacci(1)=1 Fibonacci(2)=1
Fibonacci(3)=2 Fibonacci(4)=3 Fibonacci(5)=5
Series: 1 1 2 3 5 8 13 21 34 55...
Page 20 | 2D Arrays · Strings · Functions · Recursion
C Programming Study Notes — Unit II & III Reema Thareja Reference
■ P21: Fibonacci Iterative (Non-Recursive) — Application
#include <stdio.h>
int main() {
int n, i, a=0, b=1, next;
printf("\nEnter terms: "); scanf("%d",&n);
printf("\nFibonacci: %d %d", a, b);
for(i=2; i<n; i++) {
next = a + b;
printf(" %d", next);
a = b;
b = next;
return 0;
}
Output:
Enter terms: 7
Fibonacci: 0 1 1 2 3 5 8
■ P22: Check Prime Using Function (Application)
#include <stdio.h>
int is_prime(int n);
int main() {
int n;
printf("\nEnter number: "); scanf("%d",&n);
if(is_prime(n)) printf("\n%d is PRIME", n);
else printf("\n%d is NOT PRIME", n);
return 0;
int is_prime(int n) {
int i;
if(n<2) return 0;
for(i=2; i<=n/2; i++)
if(n%i==0) return 0;
return 1;
}
Output:
Enter number: 7
7 is PRIME
Page 21 | 2D Arrays · Strings · Functions · Recursion
C Programming Study Notes — Unit II & III Reema Thareja Reference
PART III — 1-2 MARK QUESTIONS
Objective · Fill in the Blank · Output-based · Short Answer
A. 2D ARRAYS — Short Answer Questions
Q1. What is a two-dimensional array?
Ans: A 2D array stores data in row-column (matrix) form using two subscripts. It is an array of 1D arrays.
Q2. Write the syntax to declare a 2D array.
Ans: data_type array_name[row_size][column_size]; e.g., int marks[3][5];
Q3. How many elements can int arr[5][5] store?
Ans: 25 elements (5×5).
Q4. What is row major order?
Ans: Elements of a 2D array stored row by row in memory. All elements of row 0 first, then row 1, etc.
Q5. What condition must hold for matrix multiplication to be possible?
Ans: The number of columns in matrix A must equal the number of rows in matrix B.
Q6. What is the formula to find transpose of a matrix?
Ans: B[j][i] = A[i][j] — rows and columns are swapped.
Q7. If array is declared as int a[3][4], what is size in bytes?
Ans: 3 × 4 × 2 = 24 bytes (assuming int = 2 bytes) or 48 bytes (int = 4 bytes).
Q8. How do you initialize all elements of a 2D array to zero?
Ans: int arr[3][3] = {0}; — first element 0, rest auto-initialized to 0.
B. 2D ARRAYS — Multiple Choice Questions
1. If array declared as int arr[5][5], how many elements can it store?
(a) 5
(b) 10
(c) 25
(d) 0
Answer: (c) 25
2. Which index selects the row in a 2D array?
(a) Second index
(b) First index
(c) Both
(d) None
Answer: (b) First index
3. How are elements of a 2D array stored in C memory?
(a) Column major order
(b) Row major order
(c) Random
(d) Diagonal
Answer: (b) Row major order
4. For matrix multiplication A×B, which must be true?
(a) A and B have same rows
(b) Cols of A = Rows of B
(c) Rows of A = Cols of B
(d) A and B must be square
Answer: (b) Cols of A = Rows of B
Page 22 | 2D Arrays · Strings · Functions · Recursion
C Programming Study Notes — Unit II & III Reema Thareja Reference
5. For transpose of matrix A[m][n], result size is:
(a) m×n
(b) n×m
(c) m×m
(d) n×n
Answer: (b) n×m
C. STRINGS — Short Answer Questions
Q1. What is a string in C?
Ans: A string is a null-terminated character array. The last character is always '\0'.
Q2. How much memory does char str[10]="HELLO" use?
Ans: 10 bytes. "HELLO" takes 5 chars + 1 null = 6 bytes, rest are \0.
Q3. What does strlen("HELLO") return?
Ans: 5 — strlen counts characters excluding the null character.
Q4. What is the difference between gets() and scanf() for strings?
Ans: gets() reads the entire line including spaces; scanf("%s") stops at the first whitespace.
Q5. What does strcmp("abc","abc") return?
Ans: 0 — returns 0 if strings are equal, positive if str1 > str2, negative if str1 < str2.
Q6. Which header file is needed for string functions?
Ans: #include <string.h>
Q7. How do you convert lowercase to uppercase manually?
Ans: Subtract 32 from the ASCII value: upper = lower - 32.
Q8. How do you convert uppercase to lowercase manually?
Ans: Add 32 to the ASCII value: lower = upper + 32.
Q9. What does strcat(str1, str2) do?
Ans: Appends str2 to the end of str1. Returns str1.
Q10. What is the function to copy a string?
Ans: strcpy(destination, source) — copies source into destination.
D. STRINGS — Multiple Choice Questions
1. What character terminates every string in C?
(a) '$'
(b) '\n'
(c) '\0'
(d) '#'
Answer: (c) '\0'
2. strlen("HELLO") returns:
(a) 6
(b) 4
(c) 5
(d) 0
Answer: (c) 5
3. To store string "HELLO", minimum array size needed:
(a) 4
(b) 5
(c) 6
(d) 7
Answer: (c) 6 (5 chars + \0)
Page 23 | 2D Arrays · Strings · Functions · Recursion
C Programming Study Notes — Unit II & III Reema Thareja Reference
4. Which function compares two strings?
(a) strcat()
(b) strcpy()
(c) strcmp()
(d) strlen()
Answer: (c) strcmp()
5. ASCII of 'A' is 65, ASCII of 'a' is 97. Difference is:
(a) 31
(b) 32
(c) 33
(d) 30
Answer: (b) 32
6. Which function appends one string to another?
(a) strcmp()
(b) strcpy()
(c) strlen()
(d) strcat()
Answer: (d) strcat()
E. FUNCTIONS — Short Answer Questions
Q1. What is a function in C?
Ans: A self-contained block of statements that performs a specific, well-defined task. Functions provide modularity and code
reusability.
Q2. What are the four elements of a function?
Ans: Function Declaration (prototype), Function Definition, Function Call, Return statement.
Q3. What is a function prototype?
Ans: A declaration that tells the compiler the function's name, return type, and parameter types before it is used. Ends with a
semicolon.
Q4. What is the difference between formal and actual parameters?
Ans: Formal parameters: in function definition header. Actual parameters: values passed in function call.
Q5. What is call by value?
Ans: A copy of the argument is passed. Changes inside function do NOT affect original variables.
Q6. What is call by reference?
Ans: The address of the argument is passed using &. Changes inside function DO affect original variables.
Q7. How are arrays passed to functions?
Ans: Arrays are always passed by reference (base address is passed). Changes affect the original array.
Q8. What is a recursive function?
Ans: A function that calls itself. Must have a base case (termination condition) to avoid infinite recursion.
Q9. What is the base case in GCD recursion?
Ans: When rem (x % y) == 0, return y. This stops the recursion.
Q10. What is the base case in Fibonacci recursion?
Ans: When num <= 2, return 1. (Fib(1)=1, Fib(2)=1)
Q11. What does a void function return?
Ans: Nothing — void functions do not return any value to the caller.
Q12. What is the default return type of a function in C?
Ans: int — if no return type is specified, the function returns an integer by default.
F. FUNCTIONS — Multiple Choice Questions
Page 24 | 2D Arrays · Strings · Functions · Recursion
C Programming Study Notes — Unit II & III Reema Thareja Reference
1. Which of the following is NOT a benefit of using functions?
(a) Code reusability
(b) Modularity
(c) Increased memory usage
(d) Easy debugging
Answer: (c) Increased memory usage
2. In call by value, changes made to the parameter inside the function:
(a) Affect original
(b) Do not affect original
(c) Depends on compiler
(d) Cause error
Answer: (b) Do not affect original
3. Arrays in C are passed to functions:
(a) By value
(b) By reference
(c) By copy
(d) By constant
Answer: (b) By reference
4. A recursive function must have:
(a) Multiple return statements
(b) A base case
(c) Global variables
(d) Void return type
Answer: (b) A base case
5. What is GCD(8, 6)?
(a) 4
(b) 2
(c) 6
(d) 8
Answer: (b) 2
6. Fibonacci(5) = Fibonacci(4) + Fibonacci(3). Fibonacci(3) = ?
(a) 1
(b) 2
(c) 3
(d) 5
Answer: (b) 2 (since Fib(2)+Fib(1)=1+1=2)
7. Which symbol is used to pass address in call by reference?
(a) *
(b) &
(c) #
(d) @
Answer: (b) &
8. The function declaration int sum(int a, int b); — what is missing if removed?
(a) Compiler cannot check argument types
(b) Function will not execute
(c) Linker error
(d) No effect
Answer: (a) Compiler cannot check argument types
G. OUTPUT-FINDING QUESTIONS
Page 25 | 2D Arrays · Strings · Functions · Recursion
C Programming Study Notes — Unit II & III Reema Thareja Reference
Find the Output of the following programs:
OQ1:
int arr[2][3] = {{1,2,3},{4,5,6}};
printf("%d %d", arr[0][1], arr[1][2]);
Output: 2 6
OQ2:
char str[] = "Hello";
printf("%d", strlen(str));
Output: 5
OQ3:
char s1[20]="Good", s2[]="Morning";
strcat(s1,s2);
printf("%s", s1);
Output: GoodMorning
OQ4:
int GCD(int x, int y) {
int rem = x%y;
if(rem==0) return y;
else return GCD(y,rem);
printf("%d", GCD(12,8));
Output: 4
OQ5:
int Fib(int n) {
if(n<=2) return 1;
return Fib(n-1)+Fib(n-2);
printf("%d", Fib(6));
Output: 8
OQ6:
char s1[]="abc", s2[]="abc";
printf("%d", strcmp(s1,s2));
Output: 0 (strings are equal)
OQ7:
int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};
int i,j; int tr[3][3];
for(i=0;i<3;i++) for(j=0;j<3;j++) tr[j][i]=a[i][j];
printf("%d %d", tr[0][2], tr[2][0]);
Output: 7 3
OQ8:
void add(int n) { n = n+10; printf("%d ", n); }
int main() { int x=5; add(x); printf("%d", x); }
Output: 15 5 (original unchanged — call by value)
H. FILL IN THE BLANKS
1. A 2D array is declared as int a[3][4]. Total number of elements = ___
Answer: 12
Page 26 | 2D Arrays · Strings · Functions · Recursion
C Programming Study Notes — Unit II & III Reema Thareja Reference
2. In C, 2D arrays are stored in ___ major order.
Answer: Row
3. The null character '\0' has ASCII value ___.
Answer: 0
4. ___ function returns the length of a string excluding null character.
Answer: strlen()
5. To convert 'a' to 'A', subtract ___ from its ASCII value.
Answer: 32
6. In call by ___, the address of the variable is passed to the function.
Answer: reference
7. Arrays are always passed to functions by ___.
Answer: reference
8. Every recursive function must have a ___ condition to terminate.
Answer: base case / termination
9. GCD of 0 and b = ___.
Answer: b
10. The ___ statement returns control from a function to the calling function.
Answer: return
11. strcmp() returns ___ when both strings are equal.
Answer: 0
12. Fibonacci series: 0, 1, 1, 2, 3, 5, ___, 13
Answer: 8
I. TRUE / FALSE
1. An array can store elements of different data types.
Answer: False — all elements must be same data type.
2. strlen() counts the null character \0.
Answer: False — it excludes the null character.
3. In call by value, the original variable is not modified.
Answer: True
4. Arrays in C are passed by value to functions.
Answer: False — arrays are always passed by reference.
5. A recursive function can work without a base case.
Answer: False — without base case, it causes infinite recursion and stack overflow.
6. strcmp() returns 0 if strings are equal.
Answer: True
7. A void function can use the return statement.
Answer: True — but it cannot return a value: just "return;"
8. The first index in a 2D array selects the column.
Answer: False — it selects the row.
9. Fibonacci(3) = Fibonacci(1) + Fibonacci(2) = 1 + 1 = 2.
Answer: True (using recursive definition where Fib(1)=Fib(2)=1)
10. strcat() modifies the destination string.
Answer: True — str2 is appended to str1.
Page 27 | 2D Arrays · Strings · Functions · Recursion