most important topics in C programming
most important topics in C programming
Instructions:
1. Explain the difference between int, float, char, and void data types in C. Provide
examples of when you would use each. (3 Marks)
2. What are operators in C? Briefly describe the different categories of operators
with examples for each category. (3 Marks)
3. Explain the purpose of printf() and scanf() functions in C. How are they used for
input and output operations? (3 Marks)
4. What is a variable in C? Explain the rules for naming variables and the concept of
variable declaration and initialization. (3 Marks)
5. Describe the difference between while and do-while loops in C. Give a scenario
where you would prefer to use do-while over while. (3 Marks)
6. Explain the if-else if-else ladder in C. Provide a simple example to demonstrate its
usage. (3 Marks)
7. What is a function in C? Explain the advantages of using functions in
programming. Describe the concept of function prototype. (3 Marks)
8. What are arrays in C? How are they declared and initialized? Explain the concept
of accessing array elements. (3 Marks)
9. Explain the difference between call by value and call by reference in functions,
illustrating with simple code examples. (3 Marks)
10.What are pointers in C? Explain how pointers are declared, initialized, and
dereferenced. What is the significance of the & and * operators in pointer
operations? (3 Marks)
Analyze the following C code snippet and predict its output. Explain the logic behind the
output.
#include <stdio.h>
int main() {
int x = 10;
int y = 5;
if (x > 5 && y < 10) {
printf("Condition 1 is true\n");
}
if (x < 8 || y > 7) {
printf("Condition 2 is true\n");
}
if (!(x == 10)) {
printf("Condition 3 is true\n");
} else {
printf("Condition 3 is false\n");
}
return 0;
}
What will be the output of the following C program? Explain the flow of execution.
#include <stdio.h>
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int size = sizeof(numbers) / sizeof(numbers[0]);
modify(numbers, size);
for (int i = 0; i < size; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
return 0;
}
Trace the execution of the following code and determine the output.
#include <stdio.h>
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int num = 4;
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
}
Predict the output of the following code snippet and explain the concept being
demonstrated.
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
char str3[20];
strcpy(str3, str1);
strcat(str3, " ");
strcat(str3, str2);
printf("Concatenated string: %s\n", str3);
printf("Length of string: %lu\n", strlen(str3));
return 0;
}
(Answer ANY THREE questions from this section. Each question carries 16.67 marks)
● For Students: Use this as a practice test to assess your preparation for a C
programming exam. Focus on understanding the concepts behind each question and
practice writing C code.
● For Educators: You can use this as a template for creating your own C programming
question paper. Adjust the difficulty level and specific topics as needed for your
curriculum and students.
This question paper aims to be comprehensive and cover the most important aspects of
introductory C programming. Good luck!
Okay, I will solve the question paper by providing detailed answers and code solutions where
required. Let's go section by section.
1. Explain the difference between int, float, char, and void data types in C. Provide
examples of when you would use each.
● int (Integer):
○ Difference: Used to store whole numbers (integers) without fractional parts. The
size of int can vary depending on the system architecture (typically 2 or 4 bytes),
but it always represents a whole number.
○ Example Use Cases:
■ Counting (e.g., number of students, loop counters).
■ Representing indices of arrays.
■ Storing quantities that are naturally whole numbers (e.g., age, number of
items).
● float (Floating-point):
○ Difference: Used to store numbers with fractional parts (decimal numbers).
Typically uses 4 bytes and provides single-precision floating-point representation
according to IEEE 754 standard.
○ Example Use Cases:
■ Representing measurements (e.g., height, weight, temperature).
■ Calculations involving decimals (e.g., prices, percentages).
■ Scientific and engineering applications.
● char (Character):
○ Difference: Used to store single characters (letters, digits, symbols). Internally,
char stores the ASCII value (or other encoding like UTF-8 in some systems) of
the character as a small integer (typically 1 byte).
○ Example Use Cases:
■ Storing letters of the alphabet.
■ Representing punctuation marks and special symbols.
■ Working with strings (which are arrays of char).
● void (Void):
○ Difference: Represents the absence of a data type. It has several uses:
■ Function return type: Indicates that a function does not return any value.
■ Function parameters: In older C or in specific contexts, void as a
parameter list means the function takes no arguments (more common
now to leave parameter list empty ()).
■ Pointers: void * is a generic pointer that can point to data of any type. It
needs to be type-casted before dereferencing.
○ Example Use Cases:
■ Functions that perform actions but don't return a result.
■ Generic pointers in advanced programming.
void *ptr; // Generic pointer (can point to int, float, char, etc.)
int x = 10;
ptr = &x;
// Cannot directly dereference ptr without casting:
// int value = *ptr; // Error!
int value = *(int *)ptr; // Correct: cast to int pointer first
2. What are operators in C? Briefly describe the different categories of operators with
examples for each category.
Operators in C are special symbols that perform specific operations on operands (variables or
values). Here are the main categories:
● Sizeof Operator: Returns the size (in bytes) of a variable or data type.
○ sizeof(int)
○ sizeof(variable_name)
● Comma Operator: Evaluates expressions from left to right and returns the value of the
rightmost expression. Often used in for loops.
○ for (i = 0, j = 10; i < 5; i++, j--) ...
● Pointer Operators (covered later in question 10): & (address-of), * (dereference).
3. Explain the purpose of printf() and scanf() functions in C. How are they used for input
and output operations?
● Direction: printf() is for output (program to console), scanf() is for input (console to
program).
● Address-of Operator (&) with scanf(): Essential for most data types (except arrays
used as strings) to provide scanf with the memory location to store the input. Forgetting
& is a common error and can lead to crashes or unexpected behavior.
● Format Specifiers: Both functions rely heavily on format specifiers to interpret and
format data correctly. Mismatched format specifiers can lead to incorrect input/output.
● Error Handling (for scanf()): scanf() returns the number of input items successfully
read. It's good practice in more robust programs to check the return value of scanf() to
handle cases where the user might enter input that doesn't match the expected format.
4. What is a variable in C? Explain the rules for naming variables and the concept of
variable declaration and initialization.
Examples:
int age; // Declares an integer variable named 'age'
float salary; // Declares a floating-point variable 'salary'
char initial; // Declares a character variable 'initial'
int count, total; // Declares multiple integer variables
● Variable Initialization:
○ Purpose: Initialization is assigning an initial value to a variable at the time of
declaration or later in the program.
○ Initialization at Declaration:
■ Syntax: data_type variable_name = initial_value;
Examples:
int age = 25; // Declares and initializes 'age' to 25
float pi = 3.14f; // Declares and initializes 'pi' to 3.14
char grade = 'A'; // Declares and initializes 'grade' to 'A'
5. Describe the difference between while and do-while loops in C. Give a scenario where
you would prefer to use do-while over while.
● while loop:
○ Entry-controlled loop: The condition is checked before the loop body is
executed.
Syntax:
while (condition) {
// Loop body (statements to be executed)
}
○ Behavior:
1. The condition is evaluated.
2. If the condition is true (non-zero), the loop body is executed.
3. After executing the loop body, the process repeats from step 1 (condition
is checked again).
4. If the condition is false (zero), the loop terminates, and execution
continues after the loop.
○ Key Feature: The loop body might not execute even once if the condition is
initially false.
● do-while loop:
○ Exit-controlled loop: The condition is checked after the loop body is executed.
Syntax:
do {
// Loop body (statements to be executed)
} while (condition); // Note the semicolon at the end
○ Behavior:
1. The loop body is executed at least once.
2. Then, the condition is evaluated.
3. If the condition is true (non-zero), the loop repeats from step 1 (loop body
is executed again).
4. If the condition is false (zero), the loop terminates, and execution
continues after the loop.
○ Key Feature: The loop body is guaranteed to execute at least once, regardless
of the initial condition.
● Difference Summary:
Feature while loop do-while loop
int main() {
int choice;
do {
printf("\nMenu:\n");
printf("1. Option 1\n");
printf("2. Option 2\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("You selected Option 1\n");
break;
case 2:
printf("You selected Option 2\n");
break;
case 3:
printf("Exiting...\n");
break;
default:
printf("Invalid choice!\n");
}
} while (choice != 3); // Continue looping as long as choice is NOT 3 (Exit)
return 0;
}
In this example, we want to display the menu to the user initially. Using a do-while loop
ensures that the menu is shown at least once. If we used a while loop, we'd have to
duplicate the menu printing code before the loop to display it the first time, which is less
elegant.
6. Explain the if-else if-else ladder in C. Provide a simple example to demonstrate its
usage.
● if-else if-else Ladder Definition: It's a control flow structure in C (and many other
languages) that allows you to test a sequence of conditions in order. It's used when you
have multiple mutually exclusive conditions to check, and you want to execute different
blocks of code based on which condition is true.
Syntax:
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition1 is false AND condition2 is true
} else if (condition3) {
// Code to execute if condition1 and condition2 are false AND condition3 is true
}
// ... more 'else if' blocks can be added ...
else {
// Code to execute if ALL preceding conditions (condition1, condition2, condition3, ...) are
false
// (Optional 'else' block - acts as a default case)
}
● How it Works:
○ The condition1 in the first if statement is evaluated.
○ If condition1 is true, the code block associated with the if is executed, and the
rest of the if-else if-else ladder is skipped.
○ If condition1 is false, the program moves to the first else if block and evaluates
condition2.
○ If condition2 is true, the code block for that else if is executed, and the rest of the
ladder is skipped.
○ This process continues for each else if condition in order.
○ If none of the if or else if conditions are true, and there is an else block at the
end, the code block associated with the else is executed.
○ If no condition is true and there is no else block, nothing within the ladder is
executed.
int main() {
int marks;
return 0;
}
Explanation of Example:
Syntax:
return_type function_name(parameter_type1 parameter_name1, parameter_type2
parameter_name2, ...);
// or, parameter names can be omitted in the prototype:
return_type function_name(parameter_type1, parameter_type2, ...);
Note the semicolon at the end of the prototype.
Example:
// Function prototype for a function that adds two integers and returns the sum
int add(int a, int b); // Prototype declared before main
int main() {
int result = add(5, 3); // Calling the 'add' function
printf("Sum: %d\n", result);
return 0;
}
8. What are arrays in C? How are they declared and initialized? Explain the concept of
accessing array elements.
● Array Definition: An array in C is a collection of elements of the same data type stored
in contiguous (adjacent) memory locations. Arrays provide a way to store and access
multiple values of the same kind using a single variable name.
● Declaration:
○ Syntax: data_type array_name[array_size];
○ data_type: The data type of the elements the array will hold (e.g., int, float, char).
○ array_name: The name you choose for the array (following variable naming
rules).
○ array_size: A positive integer constant or constant expression that specifies the
number of elements the array can store. The size must be known at compile
time for statically allocated arrays (the most common type in introductory
C).
Examples:
int numbers[5]; // Declares an integer array named 'numbers' of size 5
float temperatures[10]; // Declares a float array 'temperatures' of size 10
char name[20]; // Declares a character array 'name' of size 20 (can store a string of up to
19 characters + null terminator)
● Initialization:
○ Initialization at Declaration:
■ Syntax: data_type array_name[array_size] = {value1, value2, value3, ...};
Examples:
int numbers[5] = {10, 20, 30, 40, 50}; // Initialize all 5 elements
int scores[3] = {85, 92, 78}; // Initialize 3 elements
char vowels[5] = {'a', 'e', 'i', 'o', 'u'}; // Initialize character array
int zeros[5] = {0}; // Initializes only the first element to 0, rest are implicitly initialized
to 0
int partial[5] = {1, 2}; // Initializes first two elements, rest (index 2, 3, 4) are implicitly
initialized to 0
int empty_array[5] = {}; // All elements are implicitly initialized to 0
Examples:
int numbers[5] = {10, 20, 30, 40, 50};
printf("First element: %d\n", numbers[0]); // Accesses the element at index 0 (value 10)
printf("Third element: %d\n", numbers[2]); // Accesses the element at index 2 (value 30)
numbers[1] = 25; // Modifies the element at index 1 (changes value from 20 to 25)
printf("Second element after modification: %d\n", numbers[1]); // Output: 25
● Important Note: Array Bounds Checking: C does not perform automatic bounds
checking on arrays. If you try to access an element outside the valid index range (e.g.,
numbers[5] for an array of size 5), it's an error called array out-of-bounds access. This
can lead to unpredictable program behavior, crashes, or security vulnerabilities. It's the
programmer's responsibility to ensure that array indices are always within the valid range
(0 to size - 1).
9. Explain the difference between call by value and call by reference in functions,
illustrating with simple code examples.
● Call by Value:
○ Mechanism: When you use call by value, a copy of the actual argument's value
is passed to the function's parameter.
○ Effect: Any changes made to the parameter inside the function do not affect the
original argument in the calling function. The function works with a copy, and the
original variable remains unchanged.
○ Default in C for primitive data types: For int, float, char, etc., call by value is
the default way arguments are passed to functions in C (unless you explicitly use
pointers for call by reference).
int main() {
int x = 10;
printf("Before function call, x = %d\n", x);
increment(x); // Call by value: a copy of 'x' (which is 10) is passed to 'increment'
printf("After function call, x = %d\n", x);
return 0;
}
Output:
Before function call, x = 10
Inside increment function, num = 11
After function call, x = 10
Explanation:
int main() {
int y = 20;
printf("Before function call, y = %d\n", y);
increment_by_reference(&y); // Call by reference: pass the address of 'y' using &
printf("After function call, y = %d\n", y);
return 0;
}
Output:
Before function call, y = 20
Inside increment_by_reference function, *ptr = 21
After function call, y = 21
Explanation:
10. What are pointers in C? Explain how pointers are declared, initialized, and
dereferenced. What is the significance of the & and * operators in pointer operations?
● Pointer Definition: A pointer in C is a special type of variable that stores the memory
address of another variable. Instead of holding a direct value (like an int or float), a
pointer holds the location in memory where another variable of a specific data type is
stored.
● Declaration:
○ Syntax: data_type *pointer_name;
○ data_type: The data type of the variable that the pointer will point to. This is
crucial because pointers are type-specific in C (e.g., an int * pointer should point
to an integer variable).
○ *: The asterisk (*) indicates that pointer_name is a pointer variable.
○ pointer_name: The name you choose for the pointer variable (following variable
naming rules).
Examples:
int *ptr_int; // Declares a pointer named 'ptr_int' that can point to an integer variable
float *ptr_float; // Declares a pointer 'ptr_float' to point to a float
char *ptr_char; // Declares a pointer 'ptr_char' to point to a character
● Initialization:
○ Purpose: Before using a pointer, you should initialize it to point to a valid
memory location. Common ways to initialize pointers:
■ Address of an existing variable: Use the & (address-of) operator to get
the memory address of a variable and assign it to the pointer.
■ Dynamic memory allocation: Using functions like malloc() (covered in
more advanced topics) to allocate memory dynamically and get the
address of the allocated memory.
■ Initialize to NULL: If a pointer is not immediately pointing to a valid
memory location, it's good practice to initialize it to NULL (a special
constant that represents "nowhere" or "no address"). This helps in error
checking.
Examples of Initialization:
int num = 100;
int *ptr_num;
float *ptr_value = NULL; // Initialize 'ptr_value' to NULL (not pointing anywhere initially)
● Dereferencing:
○ Purpose: Dereferencing a pointer means accessing the value stored at the
memory location that the pointer is pointing to.
○ Operator: The dereference operator is the asterisk * (same symbol used in
pointer declaration, but context is different).
○ Syntax: *pointer_name
Example:
int number = 50;
int *ptr = &number;
printf("Address of number: %p\n", ptr); // Print the address stored in ptr (using %p format
specifier for pointers)
printf("Value at address pointed to by ptr: %d\n", *ptr); // Dereference ptr to get the value (50)
*ptr = 75; // Dereferencing and assigning a new value through the pointer. This modifies
'number' itself.
printf("Value of number after modification through pointer: %d\n", number); // Output: 75
1. Analyze the following C code snippet and predict its output. Explain the logic behind
the output.
#include <stdio.h>
int main() {
int x = 10;
int y = 5;
if (x > 5 && y < 10) {
printf("Condition 1 is true\n");
}
if (x < 8 || y > 7) {
printf("Condition 2 is true\n");
}
if (!(x == 10)) {
printf("Condition 3 is true\n");
} else {
printf("Condition 3 is false\n");
}
return 0;
}
Predicted Output:
Condition 1 is true
Condition 3 is false
Explanation:
2. What will be the output of the following C program? Explain the flow of execution.
#include <stdio.h>
void modify(int arr[], int size) {
for (int i = 0; i < size; i++) {
arr[i] = arr[i] * 2;
}
}
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int size = sizeof(numbers) / sizeof(numbers[0]);
modify(numbers, size);
for (int i = 0; i < size; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
return 0;
}
Predicted Output:
2 4 6 8 10
Explanation:
3. Trace the execution of the following code and determine the output.
#include <stdio.h>
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int num = 4;
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
}
Predicted Output:
Factorial of 4 is 24
The factorial function is a recursive function. Let's trace the calls for factorial(4):
● factorial(0) returns 1.
● factorial(1) returns 1 * factorial(0) = 1 * 1 = 1.
● factorial(2) returns 2 * factorial(1) = 2 * 1 = 2.
● factorial(3) returns 3 * factorial(2) = 3 * 2 = 6.
● factorial(4) returns 4 * factorial(3) = 4 * 6 = 24.
4. Predict the output of the following code snippet and explain the concept being
demonstrated.
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
char str3[20];
strcpy(str3, str1);
strcat(str3, " ");
strcat(str3, str2);
printf("Concatenated string: %s\n", str3);
printf("Length of string: %lu\n", strlen(str3));
return 0;
}
Predicted Output:
Explanation:
● #include <string.h>: Includes the string.h header file, which is necessary for using
string manipulation functions like strcpy, strcat, and strlen.
● char str1[] = "Hello"; char str2[] = "World"; char str3[20];:
○ str1 and str2 are character arrays initialized with string literals "Hello" and "World"
respectively.
○ str3 is a character array of size 20, which will be used to store the concatenated
string.
● strcpy(str3, str1);: strcpy (string copy) function copies the string from str1 to str3. Now
str3 contains "Hello".
● strcat(str3, " ");: strcat (string concatenation) appends the string " " (a space) to the end
of str3. Now str3 becomes "Hello ".
● strcat(str3, str2);: strcat appends the string from str2 ("World") to the end of str3. Now
str3 becomes "Hello World".
● printf("Concatenated string: %s\n", str3);: Prints the string stored in str3 using the %s
format specifier. Output: "Concatenated string: Hello World".
● printf("Length of string: %lu\n", strlen(str3));: strlen(str3) calculates the length of the
string in str3 (excluding the null terminator character \0). The length of "Hello World" is
11 characters. %lu is the format specifier for unsigned long (the return type of strlen).
Output: "Length of string: 11".
Concept Demonstrated: String manipulation using standard C library functions from string.h:
#include <stdio.h>
#include <limits.h> // For INT_MIN and INT_MAX
int main() {
int n, i;
if (n <= 0) {
printf("Invalid array size. Please enter a positive integer.\n");
return 1; // Indicate an error
}
#include <stdio.h>
int main() {
float num1, num2, result;
char operator;
#include <stdio.h>
#include <string.h>
#include <ctype.h> // For tolower()
int main() {
char str[100]; // Assuming maximum string length of 100
int vowels = 0, consonants = 0;
int i;
● Define a structure named Student with the following members: roll_no (integer), name
(string), marks (float).
● Read the details of n students (roll number, name, and marks) and store them in an
array of structures.
● Write a function to display the details of all students who have scored marks above a
given threshold (e.g., 75).
● Call this function from your main function.
#include <stdio.h>
#include <string.h>
int main() {
int n, i;
float threshold = 75.0; // Example threshold
if (n <= 0) {
printf("Invalid number of students.\n");
return 1; // Indicate error
}
● Read data from a file named "input.txt". The file contains a list of integers, each on a new
line.
● Calculate the sum of all integers in the file.
● Write the sum to a new file named "output.txt".
● Include error handling for file operations (e.g., file not found).
First, create a file named "input.txt" in the same directory as your C program and put
some integers in it, each on a new line, like this:
10
25
5
30
15
#include <stdio.h>
#include <stdlib.h> // For exit()
int main() {
FILE *inputFile, *outputFile;
int number, sum = 0;
// Check for file read errors AFTER the loop (e.g., if file ended prematurely)
if (ferror(inputFile)) {
perror("Error reading input.txt");
fclose(inputFile); // Close input file before exiting
return 1; // Indicate error
}
// 3. Close input.txt
fclose(inputFile);
// 6. Close output.txt
fclose(outputFile);
1. FILE *inputFile, *outputFile;: Declares file pointer variables. FILE is a structure defined
in stdio.h used to represent file streams.
2. inputFile = fopen("input.txt", "r");: Opens the file "input.txt" in "read" mode ("r").
fopen() returns a file pointer if successful, or NULL if there's an error (like file not found).
3. Error Handling (Input File): if (inputFile == NULL) { ... } checks if fopen() returned
NULL. If so, it means the file couldn't be opened. perror("Error opening input.txt"); prints
an error message to the standard error stream, and return 1; exits the program indicating
an error.
4. while (fscanf(inputFile, "%d", &number) == 1) { ... }: Reads integers from input.txt
using fscanf().
○ fscanf(inputFile, "%d", &number) attempts to read an integer from the file pointed
to by inputFile and store it in the number variable.
○ fscanf() returns the number of input items successfully read. If it reads an integer
successfully, it returns 1. When it reaches the end of the file or encounters
non-integer input, it will return a value other than 1 (often EOF - End Of File,
which is typically -1).
○ The while loop continues as long as fscanf() successfully reads an integer
(returns 1).
○ sum += number; adds each read integer to the sum.
5.
6. if (ferror(inputFile)) { ... }: After the loop, ferror(inputFile) checks if any error occurred
during file reading (e.g., if the file ended unexpectedly or had invalid data). If ferror()
returns a non-zero value (true), it means an error occurred. Error handling is done after
the loop to catch read errors that might not be immediately apparent during fscanf.
7. fclose(inputFile);: Closes the input file. It's essential to close files when you are done
with them to release system resources and ensure data is properly written to disk (for
output files).
8. outputFile = fopen("output.txt", "w");: Opens "output.txt" in "write" mode ("w"). If the
file already exists, it will be overwritten. If it doesn't exist, it will be created.
9. Error Handling (Output File): Similar error check for opening the output file.
10.fprintf(outputFile, "Sum of integers from input.txt: %d\n", sum);: Writes the
calculated sum to "output.txt" using fprintf(), which works like printf() but writes to a file
stream instead of the console.
11.fclose(outputFile);: Closes the output file.
12.printf("Sum calculated and written to output.txt successfully.\n");: Prints a success
message to the console.
13.return 0;: Indicates successful program execution.
This completes the solution to the question paper. Remember to compile and run these
programs to test them thoroughly! Let me know if you have any specific questions about any
part of these solutions.