0% found this document useful (0 votes)
42 views27 pages

most important topics in C programming

This document is a C programming question paper designed to assess students' understanding of fundamental concepts, problem-solving skills, and practical application of C. It includes sections on fundamentals and concepts, code analysis, output prediction, and programming problems, covering key topics such as data types, operators, control flow, functions, arrays, strings, pointers, structures, and file handling. The paper aims to be comprehensive and serves as a practice test for students and a template for educators.

Uploaded by

anipak.1234
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views27 pages

most important topics in C programming

This document is a C programming question paper designed to assess students' understanding of fundamental concepts, problem-solving skills, and practical application of C. It includes sections on fundamentals and concepts, code analysis, output prediction, and programming problems, covering key topics such as data types, operators, control flow, functions, arrays, strings, pointers, structures, and file handling. The paper aims to be comprehensive and serves as a practice test for students and a template for educators.

Uploaded by

anipak.1234
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Okay, here's a question paper designed to cover the most important topics in C programming.

This paper is structured to assess a student's understanding of fundamental concepts,


problem-solving skills, and practical application of C.

C Programming - Question Paper

Instructions:

●​ Time Allowed: 3 Hours


●​ Maximum Marks: 100
●​ Answer all questions.
●​ Assume suitable data if necessary and clearly state your assumptions.
●​ Write clean, well-commented C code where applicable.

Section A: Fundamentals and Concepts (30 Marks)

(Answer ALL questions in this section. Each question carries 3 marks)

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)

Section B: Code Analysis and Output Prediction (20 Marks)

(Answer ALL questions in this section. Each question carries 5 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>

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;
}​

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;
} ​

Section C: Programming Problems (50 Marks)

(Answer ANY THREE questions from this section. Each question carries 16.67 marks)

1.​ Write a C program to:


○​ Read an array of n integers from the user.
○​ Find the largest and smallest element in the array.
○​ Calculate the average of all elements in the array.
○​ Print the largest, smallest, and average values.
○​ Include comments to explain each step of your code.
2.​ Develop a C program to:
○​ Implement a simple calculator that performs addition, subtraction,
multiplication, and division.
○​ *The program should take two numbers and an operator (+, -, , /) as input from
the user.
○​ Use a switch statement to perform the selected operation.
○​ Handle the case of division by zero and display an appropriate error
message.
○​ Display the result of the operation.
3.​ Create a C program to:
○​ Read a string from the user.
○​ Count the number of vowels (a, e, i, o, u) and consonants in the string.
○​ Display the counts of vowels and consonants.
○​ Consider both uppercase and lowercase vowels.
4.​ Write a C program to:
○​ 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.
5.​ Implement a C program to:
○​ 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).

--- END OF QUESTION PAPER ---

Important Topics Covered:

This question paper focuses on these key C programming topics:

●​ Data Types and Operators: Fundamental building blocks of C.


●​ Input/Output: Using printf() and scanf() for interaction.
●​ Control Flow: if-else, switch, while, do-while, for loops.
●​ Functions: Modular programming, call by value/reference, recursion.
●​ Arrays: Data structures for storing collections of elements.
●​ Strings: Character arrays and string manipulation.
●​ Pointers: Memory addresses, pointer arithmetic, dynamic memory allocation (implicitly
tested through arrays/strings).
●​ Structures: Creating custom data types.
●​ File Handling: Basic file input and output operations.
●​ Logical Reasoning and Code Analysis: Understanding code snippets and predicting
output.
●​ Problem Solving: Applying C programming to solve practical problems.

How to Use this Question Paper:

●​ 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.

Section A: Fundamentals and Concepts (30 Marks)

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).

int age = 30;


int count = 0;
for (int i = 0; i < 10; i++) { // 'i' is an int
count++;
}​

●​ 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.

float price = 99.99;


float temperature = 25.5;
float pi = 3.14159f; // 'f' suffix to indicate float literal​

●​ 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).

char initial = 'J';


char symbol = '$';
char newline = '\n'; // Escape sequence for newline​

●​ 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 print_message() { // Function that returns nothing


printf("Hello!\n");
}

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:

●​ Arithmetic Operators: Perform mathematical calculations.


○​ + (Addition): int sum = 5 + 3;
○​ - (Subtraction): int diff = 10 - 4;
○​ * (Multiplication): int product = 6 * 7;
○​ / (Division): float quotient = 15.0 / 2.0; (Note: Integer division truncates, e.g., 15 /
2 is 7)
○​ % (Modulo - Remainder): int remainder = 16 % 5; (remainder is 1)
○​ ++ (Increment): int x = 5; x++; (x becomes 6)
○​ -- (Decrement): int y = 8; y--; (y becomes 7)
●​ Relational Operators: Compare values and return a boolean result (true or false,
represented as 1 or 0 in C).
○​ == (Equal to): if (a == b) ...
○​ != (Not equal to): if (a != b) ...
○​ > (Greater than): if (a > b) ...
○​ < (Less than): if (a < b) ...
○​ >= (Greater than or equal to): if (a >= b) ...
○​ <= (Less than or equal to): if (a <= b) ...
●​ Logical Operators: Combine or modify boolean expressions.
○​ && (Logical AND): if (condition1 && condition2) ... (true if both are true)
○​ || (Logical OR): if (condition1 || condition2) ... (true if at least one is true)
○​ ! (Logical NOT): if (!condition) ... (true if condition is false, and vice versa)
●​ Assignment Operators: Assign values to variables.
○​ = (Simple assignment): int x = 10;
○​ += (Add and assign): x += 5; (equivalent to x = x + 5;)
○​ -= (Subtract and assign): x -= 2; (equivalent to x = x - 2;)
○​ *= (Multiply and assign): x *= 3; (equivalent to x = x * 3;)
○​ /= (Divide and assign): x /= 2; (equivalent to x = x / 2;)
○​ %= (Modulo and assign): x %= 4; (equivalent to x = x % 4;)
●​ Bitwise Operators: Operate on individual bits of integers.
○​ & (Bitwise AND): int result = a & b;
○​ | (Bitwise OR): int result = a | b;
○​ ^ (Bitwise XOR): int result = a ^ b;
○​ ~ (Bitwise NOT - One's complement): int result = ~a;
○​ << (Left shift): int result = a << 2; (shift bits left by 2 positions)
○​ >> (Right shift): int result = a >> 1; (shift bits right by 1 position)
●​ Conditional Operator (Ternary Operator): A shorthand for if-else in some cases.

condition ? value_if_true : value_if_false​


int age = 20;
char *message = (age >= 18) ? "Adult" : "Minor";
printf("%s\n", message); // Output: Adult ​

●​ 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?

●​ printf() (Formatted Output):


○​ Purpose: Used to display output to the standard output stream (usually the
console). It allows formatted output, meaning you can control how data is
presented (e.g., specify number of decimal places, alignment, etc.).
○​ Usage:
■​ printf("Hello, World!\n"); (Prints a string literal)
■​ int age = 25; printf("My age is %d\n", age); (Prints a string with a variable
value. %d is a format specifier for integers).
■​ Format Specifiers: %d (int), %f (float), %c (char), %s (string), %p
(pointer address), etc. You can also use flags and modifiers to control
formatting (e.g., %.2f for two decimal places in a float).
●​ scanf() (Formatted Input):
○​ Purpose: Used to read input from the standard input stream (usually the
keyboard). It also allows formatted input, meaning you can specify the expected
data type of the input.
○​ Usage:
■​ int number; scanf("%d", &number); (Reads an integer from the input and
stores it in the number variable. %d is the format specifier for integer
input. Crucially, you need to use the & (address-of) operator before
the variable name to provide the memory address where scanf
should store the input value.)
■​ char name[50]; scanf("%s", name); (Reads a string (up to the next
whitespace) into the name character array. For strings, & is generally not
needed because the array name itself decays to a pointer to the first
element.)
■​ Format Specifiers: Similar to printf, scanf uses format specifiers like %d,
%f, %c, %s to indicate the expected input data type.

Key Differences and Important Points:

●​ 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.

●​ Variable Definition: A variable in C is a named storage location in the computer's


memory that can hold a value of a specific data type. Think of it as a container with a
label (the variable name) that can store data.
●​ Rules for Naming Variables (Identifiers):
○​ Valid Characters: Variables names can contain:
■​ Uppercase letters (A-Z)
■​ Lowercase letters (a-z)
■​ Digits (0-9)
■​ Underscore _
○​ First Character: The first character must be a letter (uppercase or lowercase) or
an underscore. It cannot be a digit.
○​ Case-Sensitive: C is case-sensitive. variableName, VariableName, and
variablename are treated as three different variables.
○​ Reserved Words (Keywords): You cannot use reserved keywords of C (like int,
float, if, else, for, while, etc.) as variable names.
○​ No Spaces: Variable names cannot contain spaces. Use underscores to
separate words in a multi-word name (e.g., student_name).
○​ Length: While technically there might be limits in very old compilers, modern C
compilers generally allow reasonably long variable names. However, it's good
practice to keep names descriptive but not excessively long for readability.
●​ Variable Declaration:
○​ Purpose: Declaration tells the compiler about the variable's name and its data
type. It allocates memory for the variable but doesn't necessarily assign an initial
value.
○​ Syntax: data_type variable_name;

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' ​

Initialization after Declaration (Assignment):​


int number; // Declaration
number = 100; // Initialization (assignment) later​

●​ Importance of Initialization: It's generally good practice to initialize variables when you
declare them. If you don't initialize a variable, it will contain a garbage value (whatever
was previously in that memory location). Using uninitialized variables can lead to
unpredictable program behavior and bugs.

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

Condition Check Before loop body After loop body

Loop Body May not execute at all Executes at least once

Control Entry-controlled Exit-controlled

Scenario for Preferring do-while:​


A common scenario is when you need to present a menu to the user and get their choice, and
you want to display the menu at least once before checking if they want to continue. Consider a
simple menu-driven program:​
#include <stdio.h>

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.

Example: Grading System based on Marks:​


#include <stdio.h>

int main() {
int marks;

printf("Enter your marks (0-100): ");


scanf("%d", &marks);

if (marks >= 90) {


printf("Grade: A+\n");
} else if (marks >= 80) {
printf("Grade: A\n");
} else if (marks >= 70) {
printf("Grade: B\n");
} else if (marks >= 60) {
printf("Grade: C\n");
} else if (marks >= 50) {
printf("Grade: D\n");
} else { // marks < 50
printf("Grade: Fail\n");
}

return 0;
}




Explanation of Example:

○​ The program takes marks as input.


○​ It uses an if-else if-else ladder to determine the grade based on the marks range.
○​ The conditions are checked in order:
■​ Is marks >= 90? If yes, grade is "A+", and the rest is skipped.
■​ If not, is marks >= 80? If yes, grade is "A", and the rest is skipped.
■​ ... and so on.
○​ If none of the if or else if conditions are met (meaning marks are less than 50),
the else block is executed, and the grade is "Fail".

7. What is a function in C? Explain the advantages of using functions in programming.


Describe the concept of function prototype.
●​ Function Definition: A function in C is a self-contained block of code that performs a
specific task. It's a fundamental building block for structuring programs and promoting
code reusability. Functions can take input values (arguments or parameters), perform
operations, and optionally return a result.
●​ Advantages of Using Functions:
○​ Modularity: Functions break down a large, complex program into smaller,
manageable, and logical units. This makes the code easier to understand, write,
debug, and maintain. Each function has a specific, well-defined purpose.
○​ Reusability: Once a function is written, it can be called (used) from multiple parts
of the program or even in different programs. This avoids code duplication and
saves development time. For example, a function to calculate the factorial of a
number can be reused whenever you need to calculate factorials.
○​ Readability and Organization: Functions improve code readability by
separating different functionalities into distinct blocks. This makes the overall
program structure clearer and easier to follow. It's like organizing a book into
chapters and sections.
○​ Abstraction (Hiding Complexity): Functions allow you to hide the
implementation details of a task. When you use a function, you only need to
know what it does (its purpose) and how to call it (its interface - input and output).
You don't need to know the internal workings unless you are modifying or
debugging the function itself.
○​ Easier Debugging: When a program is divided into functions, debugging
becomes easier. You can test and debug each function independently. If an error
occurs, it's easier to isolate the problem to a specific function.
○​ Teamwork and Collaboration: In larger projects, functions facilitate teamwork.
Different programmers can work on different functions concurrently, knowing the
interfaces (function prototypes) for interaction.
●​ Function Prototype (Declaration):
○​ Purpose: A function prototype is a declaration of a function that informs the
compiler about the function's:
■​ Return type: The data type of the value the function will return (e.g., int,
float, void).
■​ Function name: The name used to call the function.
■​ Parameter list: The number, data types, and order of arguments the
function expects to receive when called.

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.

○​ Where to Place Prototypes: Function prototypes are typically placed at the


beginning of your C file, usually before the main() function or in header files (.h
files) if you are creating reusable libraries.
○​ Why Prototypes are Important:
■​ Compiler Information: Prototypes let the compiler know about the
function before it's actually used (called) in main() or other functions. This
is essential for type checking. The compiler can verify if you are calling
the function correctly with the right number and types of arguments and if
you are using the return value correctly.
■​ Early Error Detection: If there is a mismatch between how you call a
function and its prototype, the compiler will catch it as an error at compile
time, preventing runtime errors.
■​ Separate Compilation: Prototypes are crucial for separate compilation
(compiling different parts of a large program independently). If you have
functions defined in one file and called in another, the prototypes in
header files allow the compiler to ensure correct function calls across
files.

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;
}

// Function definition (actual code of the function)


int add(int a, int b) {
return a + b;
}

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 ​

■​ If you don't initialize explicitly, arrays of numeric types (int, float,


etc.) will contain garbage values. Character arrays, if not initialized, will
also have garbage values.

Initialization using a Loop:​


int squares[5];
for (int i = 0; i < 5; i++) {
squares[i] = (i + 1) * (i + 1); // Calculate squares and store
} ​

●​ Accessing Array Elements:


○​ Array elements are accessed using their index (also called subscript). Array
indexing in C is zero-based, meaning the first element is at index 0, the second
at index 1, and so on. For an array of size n, the valid indices range from 0 to n-1.
○​ Syntax: array_name[index]

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

for (int i = 0; i < 5; i++) {


printf("Element at index %d: %d\n", i, numbers[i]); // Loop to access all elements
}​

●​ 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).

Example (Call by Value):​


#include <stdio.h>
void increment(int num) { // 'num' is a parameter (local variable)
num = num + 1;
printf("Inside increment function, num = %d\n", num);
}

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:

■​ increment(x) is called. The value of x (which is 10) is copied to the


parameter num in the increment function.
■​ Inside increment, num is incremented to 11. This change is local to the
increment function and affects only the copy num.
■​ Back in main, the original variable x remains unchanged at 10.
●​ Call by Reference:
○​ Mechanism: When you use call by reference (in C, typically achieved using
pointers), you pass the memory address of the actual argument to the function's
parameter.
○​ Effect: The function parameter becomes an alias (another name) for the original
argument. Any changes made to the parameter inside the function directly affect
the original argument in the calling function because you are working with the
original memory location.
○​ Achieved using pointers in C: To implement call by reference in C, you use
pointers as parameters in the function and pass the address of the variable when
calling the function.

Example (Call by Reference using Pointers):​


#include <stdio.h>

void increment_by_reference(int *ptr) { // 'ptr' is a pointer parameter (holds an address)


*ptr = *ptr + 1; // Dereference 'ptr' to access the value at that address, then increment it
printf("Inside increment_by_reference function, *ptr = %d\n", *ptr);
}

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:

■​ increment_by_reference(&y) is called. The address of y is passed to the


pointer parameter ptr. Now, ptr points to the memory location of y.
■​ Inside increment_by_reference, *ptr dereferences the pointer ptr, which
means it accesses the value stored at the memory location pointed to by
ptr (which is the location of y).
■​ *ptr = *ptr + 1; increments the value at the memory location of y.
■​ Back in main, the original variable y is now changed to 21 because the
function directly modified the value at its memory address.
●​ Summary Table:
Feature Call by Value Call by Reference (using
pointers in C)

Argument Passed Copy of value Memory address of value

Parameter Effect Changes local to function Changes affect original


variable

Original Variable Unchanged after function call Can be changed by function


call

Default for Primitives in C Yes No (need to use pointers


explicitly)

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;

ptr_num = # // Initialize 'ptr_num' to point to the address of '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​

●​ Significance of & (Address-of) and * (Dereference) Operators:


○​ & (Address-of Operator):
■​ Purpose: Used to get the memory address of a variable.
■​ Usage: &variable_name gives you the memory address where
variable_name is stored.
■​ Key Role: Essential for initializing pointers to point to existing variables.
Used in scanf() to provide the memory address for input to be stored.
○​ * (Dereference Operator):
■​ Purpose: Used to access the value stored at the memory location
pointed to by a pointer.
■​ Usage: *pointer_name gives you the value stored at the address held by
pointer_name.
■​ Key Role: Allows you to work with the value indirectly through the pointer.
Used to modify the value of the variable that the pointer points to.
●​ Pointer Arithmetic (Brief Mention, more advanced): C allows certain arithmetic
operations on pointers (addition, subtraction, increment, decrement). When you perform
arithmetic on a pointer, the pointer is moved by a number of bytes equal to the size of
the data type it points to. This is particularly useful when working with arrays. For
example, if ptr points to the first element of an integer array, ptr + 1 will point to the next
integer element in the array.

Section B: Code Analysis and Output Prediction (20 Marks)

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:

●​ int x = 10; int y = 5;: Variables x and y are initialized.


●​ if (x > 5 && y < 10):
○​ x > 5 (10 > 5) is true.
○​ y < 10 (5 < 10) is true.
○​ true && true is true.
○​ Therefore, "Condition 1 is true" is printed.
●​ if (x < 8 || y > 7):
○​ x < 8 (10 < 8) is false.
○​ y > 7 (5 > 7) is false.
○​ false || false is false.
○​ Therefore, nothing is printed for this if condition.
●​ if (!(x == 10)):
○​ x == 10 (10 == 10) is true.
○​ !(true) is false (logical NOT negates true to false).
○​ Since the if condition is false, the else block is executed.
○​ Therefore, "Condition 3 is false" is printed.

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:

●​ int numbers[] = {1, 2, 3, 4, 5};: An integer array numbers is initialized.


●​ int size = sizeof(numbers) / sizeof(numbers[0]);: Calculates the size of the array
(number of elements). sizeof(numbers) gives the total size of the array in bytes, and
sizeof(numbers[0]) gives the size of one integer element in bytes. Dividing them gives
the number of elements.
●​ modify(numbers, size);: Calls the modify function, passing the numbers array and its
size. Arrays in C are passed by reference. This means that the modify function
receives the memory address of the first element of the numbers array.
●​ void modify(int arr[], int size) { ... }:
○​ The modify function iterates through the array arr (which is actually the numbers
array from main because of call by reference).
○​ Inside the loop, arr[i] = arr[i] * 2; multiplies each element of the array by 2. So, the
original numbers array in main is modified.
●​ for (int i = 0; i < size; i++) { printf("%d ", numbers[i]); }: This loop in main iterates
through the modified numbers array and prints each element, separated by a space.
●​ printf("\n");: Prints a newline character to move the cursor to the next line after printing
the array elements.

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

Explanation (Recursion Trace):

The factorial function is a recursive function. Let's trace the calls for factorial(4):

1.​ factorial(4) is called:


○​ n is 4. n == 0 is false. else block is executed.
○​ Returns 4 * factorial(3) (Needs to calculate factorial(3))
2.​ factorial(3) is called:
○​ n is 3. n == 0 is false. else block is executed.
○​ Returns 3 * factorial(2) (Needs to calculate factorial(2))
3.​ factorial(2) is called:
○​ n is 2. n == 0 is false. else block is executed.
○​ Returns 2 * factorial(1) (Needs to calculate factorial(1))
4.​ factorial(1) is called:
○​ n is 1. n == 0 is false. else block is executed.
○​ Returns 1 * factorial(0) (Needs to calculate factorial(0))
5.​ factorial(0) is called:
○​ n is 0. n == 0 is true. if block is executed.
○​ Returns 1 (Base case of recursion)

Now, the results are returned back up the call stack:

●​ 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.

Finally, in main(), printf("Factorial of %d is %d\n", num, factorial(num)); prints "Factorial of 4 is


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:

Concatenated string: Hello World


Length of string: 11

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:

●​ strcpy(): Copying strings.


●​ strcat(): Concatenating (appending) strings.
●​ strlen(): Calculating the length of a string.

Section C: Programming Problems (50 Marks)

1. Write a C program to:

●​ Read an array of n integers from the user.


●​ Find the largest and smallest element in the array.
●​ Calculate the average of all elements in the array.
●​ Print the largest, smallest, and average values.
●​ Include comments to explain each step of your code.

#include <stdio.h>
#include <limits.h> // For INT_MIN and INT_MAX

int main() {
int n, i;

// 1. Get the size of the array from the user


printf("Enter the number of elements in the array: ");
scanf("%d", &n);

if (n <= 0) {
printf("Invalid array size. Please enter a positive integer.\n");
return 1; // Indicate an error
}

int arr[n]; // Declare an array of size 'n'

// 2. Read array elements from the user


printf("Enter %d integer elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// 3. Find the largest and smallest elements


int largest = INT_MIN; // Initialize largest to the smallest possible integer
int smallest = INT_MAX; // Initialize smallest to the largest possible integer

for (i = 0; i < n; i++) {


if (arr[i] > largest) {
largest = arr[i]; // Update largest if current element is greater
}
if (arr[i] < smallest) {
smallest = arr[i]; // Update smallest if current element is smaller
}
}

// 4. Calculate the sum of elements to find the average


double sum = 0; // Use double for sum and average to avoid potential integer division issues
for (i = 0; i < n; i++) {
sum += arr[i]; // Add each element to the sum
}
double average = sum / n; // Calculate average

// 5. Print the results


printf("Largest element: %d\n", largest);
printf("Smallest element: %d\n", smallest);
printf("Average of elements: %.2lf\n", average); // %.2lf to print average with 2 decimal places

return 0; // Indicate successful execution


}

2. Develop a C program to:

●​ Implement a simple calculator that performs addition, subtraction, multiplication, and


division.
●​ The program should take two numbers and an operator (+, -, *, /) as input from the user.
●​ Use a switch statement to perform the selected operation.
●​ Handle the case of division by zero and display an appropriate error message.
●​ Display the result of the operation.

#include <stdio.h>

int main() {
float num1, num2, result;
char operator;

// 1. Get input from the user: two numbers and an operator


printf("Enter first number: ");
scanf("%f", &num1);
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &operator); // Note the space before %c to consume any leftover whitespace
from previous scanf
printf("Enter second number: ");
scanf("%f", &num2);

// 2. Use switch statement to perform operation based on operator


switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
// 3. Handle division by zero
if (num2 == 0) {
printf("Error: Division by zero is not allowed.\n");
return 1; // Indicate an error
} else {
result = num1 / num2;
}
break;
default:
printf("Error: Invalid operator.\n");
return 1; // Indicate an error
}

// 4. Display the result (if no error occurred)


if (operator == '+' || operator == '-' || operator == '*' || operator == '/') {
printf("Result: %.2f %c %.2f = %.2f\n", num1, operator, num2, result); // %.2f for 2 decimal
places
}

return 0; // Indicate successful execution


}

3. Create a C program to:

●​ Read a string from the user.


●​ Count the number of vowels (a, e, i, o, u) and consonants in the string.
●​ Display the counts of vowels and consonants.
●​ Consider both uppercase and lowercase vowels.

#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;

// 1. Read a string from the user


printf("Enter a string: ");
fgets(str, sizeof(str), stdin); // Use fgets to read entire line, including spaces

// 2. Iterate through the string and count vowels and consonants


for (i = 0; str[i] != '\0'; i++) {
char ch = tolower(str[i]); // Convert to lowercase for easier vowel checking

if (isalpha(str[i])) { // Check if it's an alphabet character


if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++; // Increment vowel count
} else {
consonants++; // Increment consonant count
}
}
// Ignore non-alphabetic characters (spaces, punctuation, digits, etc.)
}

// Remove newline character from fgets if present


if (str[strlen(str) - 1] == '\n') {
str[strlen(str) - 1] = '\0';
}

// 3. Display the counts


printf("String: %s\n", str);
printf("Number of vowels: %d\n", vowels);
printf("Number of consonants: %d\n", consonants);

return 0; // Indicate successful execution


}

4. Write a C program to:

●​ 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>

// 1. Define the Student structure


struct Student {
int roll_no;
char name[50]; // String for student name (max 49 characters + null terminator)
float marks;
};

// 3. Function to display students above a threshold


void displayAboveThreshold(struct Student students[], int n, float threshold) {
printf("\nStudents scoring above %.2f marks:\n", threshold);
printf("-----------------------------------\n");
printf("Roll No\tName\t\tMarks\n");
printf("-----------------------------------\n");
for (int i = 0; i < n; i++) {
if (students[i].marks > threshold) {
printf("%d\t\t%s\t\t%.2f\n", students[i].roll_no, students[i].name, students[i].marks);
}
}
}

int main() {
int n, i;
float threshold = 75.0; // Example threshold

// 2. Get the number of students


printf("Enter the number of students: ");
scanf("%d", &n);

if (n <= 0) {
printf("Invalid number of students.\n");
return 1; // Indicate error
}

struct Student student_list[n]; // Array of Student structures

// Read student details


printf("Enter details for %d students:\n", n);
for (i = 0; i < n; i++) {
printf("\nEnter details for student %d:\n", i + 1);
printf("Roll No: ");
scanf("%d", &student_list[i].roll_no);
printf("Name: ");
scanf(" %[^\n]s", student_list[i].name); // Read name with spaces using %[^\n]s
printf("Marks: ");
scanf("%f", &student_list[i].marks);
}

// 4. Call the displayAboveThreshold function


displayAboveThreshold(student_list, n, threshold);

return 0; // Indicate successful execution


}

5. Implement a C program to:

●​ 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

Now, the C program:

#include <stdio.h>
#include <stdlib.h> // For exit()

int main() {
FILE *inputFile, *outputFile;
int number, sum = 0;

// 1. Open "input.txt" for reading


inputFile = fopen("input.txt", "r");
if (inputFile == NULL) {
perror("Error opening input.txt"); // perror provides more descriptive error message
return 1; // Indicate error
}

// 2. Read integers from input.txt and calculate sum


while (fscanf(inputFile, "%d", &number) == 1) { // Read integer, check if read successfully
(returns 1 if successful)
sum += number;
}

// 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);

// 4. Open "output.txt" for writing


outputFile = fopen("output.txt", "w");
if (outputFile == NULL) {
perror("Error opening output.txt");
return 1; // Indicate error
}

// 5. Write the sum to output.txt


fprintf(outputFile, "Sum of integers from input.txt: %d\n", sum);

// 6. Close output.txt
fclose(outputFile);

printf("Sum calculated and written to output.txt successfully.\n");

return 0; // Indicate successful execution


}
Explanation of File Handling Program:

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.

You might also like