CSC115 · Exam intelligence
C Programming important questions
From 7 past TU papers: which questions keep coming back, how much they carry, and what is most likely to show up next. Every question links to a model answer.
Most likely in the next examStatistical
Ranked by how often a topic is asked, its marks weight, and whether it is due after skipping the 2081 paper. No guarantees; study the whole syllabus.
1asked 9xavg 7 marks · Decision Making and LoopingAnswerHideWrite a program to display first 50 prime numbers. [5]
Write a program to display first 50 prime numbers. [5]
Program to Display First 50 Prime Numbers
Given Data
- Required output: first 50 prime numbers
- Marks: 5
Concept
A prime number is an integer greater than 1 whose only positive divisors are 1 and itself. To generate the first 50 primes, we test successive integers starting from 2, counting each prime until 50 are found.
Program (C)
#include<stdio.h>
#include<conio.h>
void main()
{
int num, i, count, primeCount;
clrscr();
primeCount = 0; /* number of primes found so far */
num = 2; /* start from smallest prime */
printf("First 50 Prime Numbers are:\n");
while(primeCount < 50)
{
count = 0; /* 0 = prime, 1 = not prime */
for(i = 2; i <= num/2; i++) /* check divisors up to num/2 */
{
if(num % i == 0)
{
count = 1;
break;
}
}
if(count == 0) /* num is prime */
{
printf("%d\t", num);
primeCount++;
}
num++;
}
getch();
}
Note: an inner loop written as
i < numis logically correct, it simply checks more divisors than necessary. Usingi <= num/2(ori*i <= num) is more efficient, and both give the same correct output.
Sample Output
First 50 Prime Numbers are:
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
Verification of Output
Counting the listed primes: 5 rows of 10 = 50 primes. The 50th prime is $229$, which is correct.
Explanation
| Part | Purpose |
|---|---|
primeCount < 50 | Loop continues until exactly 50 primes are found |
Inner for loop | Tests whether num has any divisor |
num % i == 0 | Marks num as composite |
count == 0 | Indicates num is prime |
primeCount++ | Records each prime found |
2asked 5xavg 6 marks · due (skipped 2081) · User defined functionsAnswerHideDefine structure and nested structure. Write a program to find out whether the $n^{th}$ term of the Fibonacci series is a prime number or not. Read the value of $n$ from the user and display the result in the main function. Use separate user-defined function to
(i) generate $n^{th}$ term and
(ii) to check whether that number is prime or not.[3+7]
Define structure and nested structure. Write a program to find out whether the $n^{th}$ term of the Fibonacci series is a prime number or not. Read the value of $n$ from the user and display the result in the main function. Use separate user-defined function to
(i) generate $n^{th}$ term and
(ii) to check whether that number is prime or not.[3+7]
Structure, Nested Structure, and Fibonacci Prime Program
(a) Definitions
Structure
A structure is a user-defined data type in C that allows grouping of variables of different data types under a single name. Each variable inside a structure is called a member or field.
Syntax:
struct structure_name {
data_type member1;
data_type member2;
...
};
Example:
struct Student {
int roll;
char name[20];
float marks;
};
Nested Structure
A nested structure is a structure that contains another structure as its member. That is, one structure is defined or declared inside another structure.
Syntax:
struct Inner {
data_type member1;
};
struct Outer {
data_type member;
struct Inner obj; /* nested structure member */
};
Example:
struct Date {
int day;
int month;
int year;
};
struct Student {
int roll;
char name[20];
struct Date dob; /* nested structure */
};
Here, struct Date is nested inside struct Student. The member dob is accessed as s.dob.day, s.dob.month, etc.
(b) Program
Problem Analysis
- Read
nfrom the user inmain(). - Call function
fibonacci(n)to find the nth term of the Fibonacci series. - Call function
isPrime(num)to check whether that term is prime or not. - Display the result in
main().
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, ... The 1st term = 0, 2nd term = 1, 3rd term = 1, and so on.
Complete Program
#include <stdio.h>
#include <conio.h>
/* Function to generate the nth term of Fibonacci series */
int fibonacci(int n)
{
int first = 0, second = 1, next, i;
if (n == 1)
return 0;
if (n == 2)
return 1;
for (i = 3; i <= n; i++)
{
next = first + second;
first = second;
second = next;
}
return next;
}
/* Function to check whether a number is prime or not */
/* Returns 1 if prime, 0 if not prime */
int isPrime(int num)
{
int i;
if (num <= 1)
return 0; /* 0 and 1 are not prime */
for (i = 2; i <= num / 2; i++)
{
if (num % i == 0)
return 0; /* divisible, so not prime */
}
return 1; /* prime */
}
/* Main function */
void main()
{
int n, term, result;
clrscr();
printf("Enter the value of n: ");
scanf("%d", &n);
/* Generate nth Fibonacci term */
term = fibonacci(n);
printf("\nThe %dth term of Fibonacci series is: %d\n", n, term);
/* Check if the term is prime */
result = isPrime(term);
if (result == 1)
printf("%d is a PRIME number.\n", term);
else
printf("%d is NOT a prime number.\n", term);
getch();
}
Sample Output
Enter the value of n: 7
The 7th term of Fibonacci series is: 8
8 is NOT a prime number.
Enter the value of n: 5
The 5th term of Fibonacci series is: 3
3 is a PRIME number.
Fibonacci Series Reference Table
| n | Fibonacci Term |
|---|---|
| 1 | 0 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 3 |
| 6 | 5 |
| 7 | 8 |
| 8 | 13 |
Key Points
| Function | Purpose | Return Type |
|---|---|---|
fibonacci(n) | Returns the nth Fibonacci term | int |
isPrime(num) | Returns 1 if prime, 0 if not | int |
main() | Reads input, calls both functions, displays result | void |
3asked 5xavg 5 marks · due (skipped 2081) · Input Output Operations in FileAnswerHideDescribe the different types of I/O functions used in file handling with syntax. [5]
Describe the different types of I/O functions used in file handling with syntax. [5]
File handling in C provides several categories of I/O functions to read from and write to files. These are defined in <stdio.h. --- Used to read/write a single character at a time. Writes a single character to a specified file and increm...
4asked 3xavg 5 marks · due (skipped 2081) · Dynamic Memory AllocationAnswerHideWhat is dynamic memory allocation? Explain with a suitable program. [5]
What is dynamic memory allocation? Explain with a suitable program. [5]
Dynamic Memory Allocation
Definition
The process of allocating memory at the time of execution (runtime) is called dynamic memory allocation. Unlike static memory allocation where the size is fixed at compile time, dynamic memory allocation allows a program to request and release memory as needed during execution.
Problems with static allocation (e.g., int emp[100];):
- If fewer values are stored, memory is wasted
- If more values are needed, we cannot store them
Dynamic memory allocation solves both problems. Memory is accessed through pointers, and the functions are available in stdlib.h / alloc.h.
Key Functions
| Function | Purpose |
|---|---|
malloc() | Allocates a block of memory of specified size |
calloc() | Allocates memory and initializes to zero |
realloc() | Resizes previously allocated memory |
free() | Releases dynamically allocated memory |
Syntax of malloc():
pointer_variable = (datatype *) malloc(specified_size);
Example Program
The following program dynamically allocates memory for n integers entered by the user, stores them, and displays them.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
int n, i;
printf("Enter number of elements: ");
scanf("%d", &n);
/* Dynamically allocate memory for n integers */
ptr = (int *) malloc(n * sizeof(int));
/* Check if memory was allocated successfully */
if (ptr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
/* Input values */
printf("Enter %d integers:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &ptr[i]);
}
/* Display values */
printf("You entered:\n");
for (i = 0; i < n; i++) {
printf("%d ", ptr[i]);
}
printf("\n");
/* Release the allocated memory */
free(ptr);
return 0;
}
Sample Output
Enter number of elements: 4
Enter 4 integers:
10 20 30 40
You entered:
10 20 30 40
Key Points
malloc(n * sizeof(int))allocates exactly the memory needed at runtime- The pointer
ptris used to access the dynamically allocated memory block free(ptr)releases the memory back to the system after use- If allocation fails,
malloc()returnsNULL, which should always be checked
5asked 4xavg 8 marks · Introduction to ArrayAnswerHideWhat are the characteristics of array?Write a program to input age of 500 persons and display the following:
a) Average age
b) Age between 25 to 30_[2+8]_
What are the characteristics of array?Write a program to input age of 500 persons and display the following:
a) Average age
b) Age between 25 to 30_[2+8]_
Characteristics of Array and Program for Age Analysis
Characteristics of Array [2 marks]
An array is a collection of similar data type elements stored in contiguous memory locations. Its main characteristics are:
- Homogeneous Elements: All elements in an array must be of the same data type (e.g., all int, all float).
- Contiguous Memory Allocation: Array elements are stored in consecutive memory locations.
- Index/Subscript Based Access: Each element is accessed using an index starting from 0 (lower bound = 0, upper bound = size - 1).
- Fixed Size: The size of an array is fixed at the time of declaration and cannot be changed during execution.
- Random Access: Any element can be directly accessed using its index in constant time.
- Single Variable Name: Multiple values are stored under one variable name with different indices.
Program to Input Age of 500 Persons [8 marks]
#include<stdio.h>
#include<conio.h>
void main()
{
int age[500], i;
int count = 0; /* count of persons with age between 25 to 30 */
float sum = 0, average;
clrscr();
/* Input age of 500 persons */
for(i = 0; i < 500; i++)
{
printf("Enter age of person %d: ", i + 1);
scanf("%d", &age[i]);
}
/* Calculate sum and count persons with age between 25 to 30 */
for(i = 0; i < 500; i++)
{
sum = sum + age[i];
if(age[i] >= 25 && age[i] <= 30)
{
count++;
}
}
/* a) Calculate average age */
average = sum / 500;
printf("\n--- Results ---\n");
/* Display average age */
printf("\na) Average Age = %.2f", average);
/* b) Display ages between 25 to 30 */
printf("\n\nb) Ages between 25 to 30:\n");
for(i = 0; i < 500; i++)
{
if(age[i] >= 25 && age[i] <= 30)
{
printf("Person %d : %d years\n", i + 1, age[i]);
}
}
printf("\nTotal persons with age between 25 to 30: %d", count);
getch();
}
Explanation of the Program
| Step | Description |
|---|---|
| Declaration | int age[500] declares an integer array of size 500 to store ages |
| Input Loop | A for loop runs from i=0 to i<500 to input all 500 ages |
| Sum Calculation | Each age is added to sum to find total |
| Condition Check | age[i] >= 25 && age[i] <= 30 checks if age falls in the range |
| Average | average = sum / 500 gives the average age |
| Output | Average is displayed and ages in range 25-30 are printed with person number |
Sample Output
--- Results ---
a) Average Age = 35.46
b) Ages between 25 to 30:
Person 3 : 27 years
Person 7 : 25 years
Person 12 : 30 years
...
Total persons with age between 25 to 30: 85
Most repeated questions
Topics asked at least twice, most-asked first.
asked 9xavg 7 marks · 2081, 2080, 2079, 2077, 2075...AnswerHideWrite a program to display first 50 prime numbers. [5]
Write a program to display first 50 prime numbers. [5]
Program to Display First 50 Prime Numbers
Given Data
- Required output: first 50 prime numbers
- Marks: 5
Concept
A prime number is an integer greater than 1 whose only positive divisors are 1 and itself. To generate the first 50 primes, we test successive integers starting from 2, counting each prime until 50 are found.
Program (C)
#include<stdio.h>
#include<conio.h>
void main()
{
int num, i, count, primeCount;
clrscr();
primeCount = 0; /* number of primes found so far */
num = 2; /* start from smallest prime */
printf("First 50 Prime Numbers are:\n");
while(primeCount < 50)
{
count = 0; /* 0 = prime, 1 = not prime */
for(i = 2; i <= num/2; i++) /* check divisors up to num/2 */
{
if(num % i == 0)
{
count = 1;
break;
}
}
if(count == 0) /* num is prime */
{
printf("%d\t", num);
primeCount++;
}
num++;
}
getch();
}
Note: an inner loop written as
i < numis logically correct, it simply checks more divisors than necessary. Usingi <= num/2(ori*i <= num) is more efficient, and both give the same correct output.
Sample Output
First 50 Prime Numbers are:
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
Verification of Output
Counting the listed primes: 5 rows of 10 = 50 primes. The 50th prime is $229$, which is correct.
Explanation
| Part | Purpose |
|---|---|
primeCount < 50 | Loop continues until exactly 50 primes are found |
Inner for loop | Tests whether num has any divisor |
num % i == 0 | Marks num as composite |
count == 0 | Indicates num is prime |
primeCount++ | Records each prime found |
asked 5xavg 6 marks · 2080, 2078, 2077, 2074AnswerHideDefine structure and nested structure. Write a program to find out whether the $n^{th}$ term of the Fibonacci series is a prime number or not. Read the value of $n$ from the user and display the result in the main function. Use separate user-defined function to
(i) generate $n^{th}$ term and
(ii) to check whether that number is prime or not.[3+7]
Define structure and nested structure. Write a program to find out whether the $n^{th}$ term of the Fibonacci series is a prime number or not. Read the value of $n$ from the user and display the result in the main function. Use separate user-defined function to
(i) generate $n^{th}$ term and
(ii) to check whether that number is prime or not.[3+7]
Structure, Nested Structure, and Fibonacci Prime Program
(a) Definitions
Structure
A structure is a user-defined data type in C that allows grouping of variables of different data types under a single name. Each variable inside a structure is called a member or field.
Syntax:
struct structure_name {
data_type member1;
data_type member2;
...
};
Example:
struct Student {
int roll;
char name[20];
float marks;
};
Nested Structure
A nested structure is a structure that contains another structure as its member. That is, one structure is defined or declared inside another structure.
Syntax:
struct Inner {
data_type member1;
};
struct Outer {
data_type member;
struct Inner obj; /* nested structure member */
};
Example:
struct Date {
int day;
int month;
int year;
};
struct Student {
int roll;
char name[20];
struct Date dob; /* nested structure */
};
Here, struct Date is nested inside struct Student. The member dob is accessed as s.dob.day, s.dob.month, etc.
(b) Program
Problem Analysis
- Read
nfrom the user inmain(). - Call function
fibonacci(n)to find the nth term of the Fibonacci series. - Call function
isPrime(num)to check whether that term is prime or not. - Display the result in
main().
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, ... The 1st term = 0, 2nd term = 1, 3rd term = 1, and so on.
Complete Program
#include <stdio.h>
#include <conio.h>
/* Function to generate the nth term of Fibonacci series */
int fibonacci(int n)
{
int first = 0, second = 1, next, i;
if (n == 1)
return 0;
if (n == 2)
return 1;
for (i = 3; i <= n; i++)
{
next = first + second;
first = second;
second = next;
}
return next;
}
/* Function to check whether a number is prime or not */
/* Returns 1 if prime, 0 if not prime */
int isPrime(int num)
{
int i;
if (num <= 1)
return 0; /* 0 and 1 are not prime */
for (i = 2; i <= num / 2; i++)
{
if (num % i == 0)
return 0; /* divisible, so not prime */
}
return 1; /* prime */
}
/* Main function */
void main()
{
int n, term, result;
clrscr();
printf("Enter the value of n: ");
scanf("%d", &n);
/* Generate nth Fibonacci term */
term = fibonacci(n);
printf("\nThe %dth term of Fibonacci series is: %d\n", n, term);
/* Check if the term is prime */
result = isPrime(term);
if (result == 1)
printf("%d is a PRIME number.\n", term);
else
printf("%d is NOT a prime number.\n", term);
getch();
}
Sample Output
Enter the value of n: 7
The 7th term of Fibonacci series is: 8
8 is NOT a prime number.
Enter the value of n: 5
The 5th term of Fibonacci series is: 3
3 is a PRIME number.
Fibonacci Series Reference Table
| n | Fibonacci Term |
|---|---|
| 1 | 0 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 3 |
| 6 | 5 |
| 7 | 8 |
| 8 | 13 |
Key Points
| Function | Purpose | Return Type |
|---|---|---|
fibonacci(n) | Returns the nth Fibonacci term | int |
isPrime(num) | Returns 1 if prime, 0 if not | int |
main() | Reads input, calls both functions, displays result | void |
asked 5xavg 5 marks · 2080, 2079, 2078, 2077, 2074AnswerHideDescribe the different types of I/O functions used in file handling with syntax. [5]
Describe the different types of I/O functions used in file handling with syntax. [5]
File handling in C provides several categories of I/O functions to read from and write to files. These are defined in <stdio.h. --- Used to read/write a single character at a time. Writes a single character to a specified file and increm...
asked 4xavg 8 marks · 2081, 2079, 2075, 2074AnswerHideWhat are the characteristics of array?Write a program to input age of 500 persons and display the following:
a) Average age
b) Age between 25 to 30_[2+8]_
What are the characteristics of array?Write a program to input age of 500 persons and display the following:
a) Average age
b) Age between 25 to 30_[2+8]_
Characteristics of Array and Program for Age Analysis
Characteristics of Array [2 marks]
An array is a collection of similar data type elements stored in contiguous memory locations. Its main characteristics are:
- Homogeneous Elements: All elements in an array must be of the same data type (e.g., all int, all float).
- Contiguous Memory Allocation: Array elements are stored in consecutive memory locations.
- Index/Subscript Based Access: Each element is accessed using an index starting from 0 (lower bound = 0, upper bound = size - 1).
- Fixed Size: The size of an array is fixed at the time of declaration and cannot be changed during execution.
- Random Access: Any element can be directly accessed using its index in constant time.
- Single Variable Name: Multiple values are stored under one variable name with different indices.
Program to Input Age of 500 Persons [8 marks]
#include<stdio.h>
#include<conio.h>
void main()
{
int age[500], i;
int count = 0; /* count of persons with age between 25 to 30 */
float sum = 0, average;
clrscr();
/* Input age of 500 persons */
for(i = 0; i < 500; i++)
{
printf("Enter age of person %d: ", i + 1);
scanf("%d", &age[i]);
}
/* Calculate sum and count persons with age between 25 to 30 */
for(i = 0; i < 500; i++)
{
sum = sum + age[i];
if(age[i] >= 25 && age[i] <= 30)
{
count++;
}
}
/* a) Calculate average age */
average = sum / 500;
printf("\n--- Results ---\n");
/* Display average age */
printf("\na) Average Age = %.2f", average);
/* b) Display ages between 25 to 30 */
printf("\n\nb) Ages between 25 to 30:\n");
for(i = 0; i < 500; i++)
{
if(age[i] >= 25 && age[i] <= 30)
{
printf("Person %d : %d years\n", i + 1, age[i]);
}
}
printf("\nTotal persons with age between 25 to 30: %d", count);
getch();
}
Explanation of the Program
| Step | Description |
|---|---|
| Declaration | int age[500] declares an integer array of size 500 to store ages |
| Input Loop | A for loop runs from i=0 to i<500 to input all 500 ages |
| Sum Calculation | Each age is added to sum to find total |
| Condition Check | age[i] >= 25 && age[i] <= 30 checks if age falls in the range |
| Average | average = sum / 500 gives the average age |
| Output | Average is displayed and ages in range 25-30 are printed with person number |
Sample Output
--- Results ---
a) Average Age = 35.46
b) Ages between 25 to 30:
Person 3 : 27 years
Person 7 : 25 years
Person 12 : 30 years
...
Total persons with age between 25 to 30: 85
asked 4xavg 8 marks · 2081, 2080, 2079, 2077AnswerHideCreate a structure called STUDENT with data members SID, name, address, CGPA. Write a program to initialize the value of 100 students and display the information of those students whose address is "KTM" and CGPA is between 3.5 to 4. [5]
Create a structure called STUDENT with data members SID, name, address, CGPA. Write a program to initialize the value of 100 students and display the information of those students whose address is "KTM" and CGPA is between 3.5 to 4. [5]
--- Part Description ------------------- struct STUDENT Defines the structure with members SID, name, address, CGPA struct STUDENT st[100] Declares an array of structures to hold 100 student records First for loop Reads and initializes d...
asked 4xavg 5 marks · 2081, 2078, 2077, 2074AnswerHideWrite a program to draw two shapes of your choice using graphics function. [5]
Write a program to draw two shapes of your choice using graphics function. [5]
Program to Draw Two Shapes Using Graphics Functions
Answer
The two shapes chosen are a Circle and a Rectangle, both drawn using standard graphics functions from graphics.h.
Program
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void main()
{
int gd = DETECT, gm;
/* Initialize the graphics mode */
initgraph(&gd, &gm, "c:\\tc\\bgi");
/* Shape 1: Draw a Circle
center at (200, 150) with radius 80 */
setcolor(WHITE);
circle(200, 150, 80);
/* Shape 2: Draw a Rectangle
top-left corner at (350, 100)
bottom-right corner at (550, 250) */
setcolor(WHITE);
rectangle(350, 100, 550, 250);
getch();
/* Close the graphics mode */
closegraph();
}
Explanation of Each Step
| Step | Description |
|---|---|
int gd = DETECT, gm; | Declares graphics driver and mode variables. DETECT auto-detects the driver. |
initgraph(&gd, &gm, "c:\\tc\\bgi") | Initializes the graphics system and opens a graphics window. The path points to the BGI driver files. |
setcolor(WHITE) | Sets the current drawing color to white. |
circle(200, 150, 80) | Draws a circle with center at pixel (200, 150) and radius 80 pixels. |
rectangle(350, 100, 550, 250) | Draws a rectangle with top-left corner at (350, 100) and bottom-right corner at (550, 250). |
getch() | Waits for a key press so the output window stays visible. |
closegraph() | Closes the graphics mode and returns to text mode. |
Output
+------------------------------------------+
| |
| ( Circle ) [ Rectangle ] |
| drawn at drawn at |
| (200,150) (350,100) to |
| r = 80 (550,250) |
| |
+------------------------------------------+
Note: The pixel origin (0, 0) is at the top-left corner of the screen. All coordinates are measured in pixels from this origin.
asked 3xavg 5 marks · 2080, 2078, 2075AnswerHideWhat is dynamic memory allocation? Explain with a suitable program. [5]
What is dynamic memory allocation? Explain with a suitable program. [5]
Dynamic Memory Allocation
Definition
The process of allocating memory at the time of execution (runtime) is called dynamic memory allocation. Unlike static memory allocation where the size is fixed at compile time, dynamic memory allocation allows a program to request and release memory as needed during execution.
Problems with static allocation (e.g., int emp[100];):
- If fewer values are stored, memory is wasted
- If more values are needed, we cannot store them
Dynamic memory allocation solves both problems. Memory is accessed through pointers, and the functions are available in stdlib.h / alloc.h.
Key Functions
| Function | Purpose |
|---|---|
malloc() | Allocates a block of memory of specified size |
calloc() | Allocates memory and initializes to zero |
realloc() | Resizes previously allocated memory |
free() | Releases dynamically allocated memory |
Syntax of malloc():
pointer_variable = (datatype *) malloc(specified_size);
Example Program
The following program dynamically allocates memory for n integers entered by the user, stores them, and displays them.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
int n, i;
printf("Enter number of elements: ");
scanf("%d", &n);
/* Dynamically allocate memory for n integers */
ptr = (int *) malloc(n * sizeof(int));
/* Check if memory was allocated successfully */
if (ptr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
/* Input values */
printf("Enter %d integers:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &ptr[i]);
}
/* Display values */
printf("You entered:\n");
for (i = 0; i < n; i++) {
printf("%d ", ptr[i]);
}
printf("\n");
/* Release the allocated memory */
free(ptr);
return 0;
}
Sample Output
Enter number of elements: 4
Enter 4 integers:
10 20 30 40
You entered:
10 20 30 40
Key Points
malloc(n * sizeof(int))allocates exactly the memory needed at runtime- The pointer
ptris used to access the dynamically allocated memory block free(ptr)releases the memory back to the system after use- If allocation fails,
malloc()returnsNULL, which should always be checked
asked 3xavg 7 marks · 2081, 2080, 2079AnswerHideList different types of operators.Explain any four of them_[2+8]_
List different types of operators.Explain any four of them_[2+8]_
Types of Operators in C
List of Operators [2 marks]
An operator is a symbol that specifies an operation to be performed on operands. C includes the following types of operators:
- Arithmetic Operator
- Assignment Operator
- Increment and Decrement Operator
- Relational Operator
- Logical Operator
- Conditional Operator
- Comma Operator
- Sizeof Operator
- Bitwise Operator
Explanation of Any Four Operators [8 marks]
1. Arithmetic Operators
Arithmetic operators are used for numeric calculations. They are of two types:
i. Unary Arithmetic Operators - operate on a single operand.
| Operator | Meaning | Example |
|---|---|---|
| + | Unary plus | +a |
| - | Unary minus (negation) | -a |
ii. Binary Arithmetic Operators - operate on two operands.
| Operator | Meaning | Example | Result (a=10, b=3) |
|---|---|---|---|
| + | Addition | a + b | 13 |
| - | Subtraction | a - b | 7 |
| * | Multiplication | a * b | 30 |
| / | Division | a / b | 3 |
| % | Modulus (remainder) | a % b | 1 |
Example:
int a = 10, b = 3;
printf("%d", a % b); // Output: 1
printf("%d", a / b); // Output: 3
2. Relational Operators
Relational operators are used to compare two values or expressions. The result of a relational operation is either true (1) or false (0).
| Operator | Meaning | Example (a=5, b=3) | Result |
|---|---|---|---|
| > | Greater than | a > b | 1 (true) |
| < | Less than | a < b | 0 (false) |
| >= | Greater than or equal to | a >= 5 | 1 (true) |
| <= | Less than or equal to | a <= b | 0 (false) |
| == | Equal to | a == b | 0 (false) |
| != | Not equal to | a != b | 1 (true) |
Example:
int a = 5, b = 3;
if (a > b)
printf("a is greater"); // Output: a is greater
3. Increment and Decrement Operators
These operators are used to increase or decrease the value of a variable by 1. They are of two types:
i. Prefix (operator written before operand)
++x: value is incremented first, then used in expression.--x: value is decremented first, then used in expression.
ii. Postfix (operator written after operand)
x++: value is used in expression first, then incremented.x--: value is used in expression first, then decremented.
Example:
int x = 5, y;
y = ++x; // x becomes 6 first, then y = 6
printf("%d %d", x, y); // Output: 6 6
x = 5;
y = x++; // y = 5 first, then x becomes 6
printf("%d %d", x, y); // Output: 6 5
4. Logical Operators
Logical operators are used to combine two or more relational expressions and return a true (1) or false (0) result. They are commonly used in decision-making.
| Operator | Meaning | Example | Result (a=5, b=3, c=0) |
|---|---|---|---|
| && | Logical AND | a>b && b>c | 1 (both true) |
| || | Logical OR | a>b || b<c | 1 (at least one true) |
| ! | Logical NOT | !c | 1 (negation of 0) |
Truth Table for AND (&&):
| Condition 1 | Condition 2 | Result |
|---|---|---|
| True (1) | True (1) | True (1) |
| True (1) | False (0) | False (0) |
| False (0) | True (1) | False (0) |
| False (0) | False (0) | False (0) |
Example:
int a = 5, b = 3, c = 0;
if (a > b && b > c)
printf("Both conditions true"); // Output: Both conditions true
if (!c)
printf("c is zero"); // Output: c is zero
Summary: Operators are fundamental building blocks in C programming. Arithmetic operators perform calculations, relational operators compare values, increment/decrement operators modify values by 1, and logical operators combine conditions for decision-making.
asked 3xavg 5 marks · 2081, 2080, 2079AnswerHideDemonstrate the use of recursive function with a suitable example. [5]
Demonstrate the use of recursive function with a suitable example. [5]
A recursive function is a function that calls itself during its own execution. Each recursive call works on a smaller version of the problem until a base condition (terminating condition) is reached, which stops further recursion. --- Co...
asked 2xavg 8 marks · 2080, 2074AnswerHideExplain the relation to array and pointer.Differentiate between call by value and call by reference with a suitable program.[2+8]
Explain the relation to array and pointer.Differentiate between call by value and call by reference with a suitable program.[2+8]
Relation Between Array and Pointer, and Call by Value vs Call by Reference
(a) Relation Between Array and Pointer
In C, there is a strong relationship between arrays and pointers. Any operation that can be achieved by array subscripting can also be done with pointers.
Key Points:
- An array name is itself an address (a constant pointer to the first element of the array).
- Pointers and arrays are almost synonymous in terms of how they are used to access memory.
- The pointer version of array operations is generally faster but harder to understand for beginners.
Illustration:
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr; // ptr points to the first element of arr
| Array Notation | Pointer Notation | Meaning |
|---|---|---|
arr[0] | *ptr | First element |
arr[1] | *(ptr + 1) | Second element |
arr[i] | *(ptr + i) | i-th element |
&arr[i] | ptr + i | Address of i-th element |
Important Difference:
- A pointer is a variable (its value can be changed).
- An array name is a constant pointer (it always points to the first element and cannot be reassigned).
(b) Difference Between Call by Value and Call by Reference
Definition:
Call by Value: In call by value, a copy of the actual argument is passed to the formal parameter. The called function works on this copy, so any changes made inside the function do not affect the original variable.
Call by Reference: In call by reference, the address (reference) of the actual argument is passed to the function. The called function works directly on the original data using pointers, so changes made inside the function do affect the original variable.
Comparison Table:
| Feature | Call by Value | Call by Reference |
|---|---|---|
| What is passed | Copy of the value | Address of the variable |
| Effect on original data | No change in original variable | Original variable gets modified |
| Memory | Separate memory for formal parameter | Formal parameter refers to same memory |
| Return values | Can return only one value | Can effectively return multiple values |
| Safety | Safer (original data protected) | Less safe (original data can be changed) |
| Speed | Slightly slower (copy is made) | Slightly faster (no copy made) |
| Mechanism used | Normal variables | Pointers |
Program Demonstrating Both:
#include<stdio.h>
#include<conio.h>
/* Function prototypes */
void callByValue(int x);
void callByReference(int *x);
void main()
{
int a = 15;
int b = 15;
clrscr();
/* Demonstrating Call by Value */
printf("--- Call by Value ---\n");
printf("Before calling function, a = %d\n", a);
callByValue(a);
printf("After calling function, a = %d\n\n", a);
/* Demonstrating Call by Reference */
printf("--- Call by Reference ---\n");
printf("Before calling function, b = %d\n", b);
callByReference(&b);
printf("After calling function, b = %d\n", b);
getch();
}
/* Call by Value: works on a copy */
void callByValue(int x)
{
x = x + 5;
printf("Inside callByValue function, x = %d\n", x);
}
/* Call by Reference: works on original via pointer */
void callByReference(int *x)
{
*x = *x + 5;
printf("Inside callByReference function, *x = %d\n", *x);
}
Output:
--- Call by Value ---
Before calling function, a = 15
Inside callByValue function, x = 20
After calling function, a = 15
--- Call by Reference ---
Before calling function, b = 15
Inside callByReference function, *x = 20
After calling function, b = 20
Explanation of Output:
-
In Call by Value:
aremains15after the function call because only a copy (x) was modified inside the function. The original variableais not affected. -
In Call by Reference:
bbecomes20after the function call because the address ofbwas passed (&b). Inside the function,*xdirectly modifies the original variableb. The original variablebis affected.
Summary: Use call by value when you want to protect the original data. Use call by reference when you want the function to modify the original variable or when you need to return multiple values from a function.
asked 2xavg 8 marks · 2080, 2077AnswerHideWrite a program to read P*Q matrix of integers and find the largest integer of each row and display it. [5]
Write a program to read P*Q matrix of integers and find the largest integer of each row and display it. [5]
A two-dimensional array is declared as datatype arrayname[row][col]. Processing requires a nested loop where the outer loop corresponds to rows and the inner loop corresponds to columns. Each element can be accessed as a[i][j]. --- 1. St...
asked 2xavg 8 marks · 2078, 2075AnswerHideWhat do you mean by jump statement?Explain each jump statement with example.Write a program to check whether a number entered is prime or not.[1+5+4]
What do you mean by jump statement?Explain each jump statement with example.Write a program to check whether a number entered is prime or not.[1+5+4]
A jump statement is a control statement that transfers the flow of program execution unconditionally from one part of the program to another. Jump statements interrupt the normal sequential or loop-based execution and cause the program t...
asked 2xavg 8 marks · 2078, 2075AnswerHideExplain any three string functions.Write a program to check if two matrices are identical or not.[3+7]
Explain any three string functions.Write a program to check if two matrices are identical or not.[3+7]
(a) Three String Functions String functions are built-in functions available in the <string.h header file used to manipulate strings in C. --- Returns the number of characters in a string, excluding the null character \0. Syntax: int str...
asked 2xavg 8 marks · 2075AnswerHideWhy do we need data files?What are the different file opening modes?Write a program that reads data from a file "input.txt" and writes to "output.txt" file.[2+3+5]
Why do we need data files?What are the different file opening modes?Write a program that reads data from a file "input.txt" and writes to "output.txt" file.[2+3+5]
Data Files, File Opening Modes, and File Copy Program
(a) Why Do We Need Data Files?
When a program runs, all data is stored in main memory (RAM), which is volatile -- it is lost when the program ends or the computer is switched off. Data files solve this problem by providing permanent storage on secondary storage devices (hard disk, etc.).
Reasons we need data files:
- Persistence: Data stored in files remains even after the program terminates.
- Large data handling: Files allow processing of data too large to fit in memory at once.
- Data sharing: Multiple programs can read from and write to the same file.
- Reusability: Data entered once can be reused many times without re-entering.
- Record keeping: Files allow maintaining logs, reports, and databases permanently.
(b) Different File Opening Modes
As per the notes, the file opening modes used in C are:
| Mode | Description |
|---|---|
"r" | Open existing file for reading only. File must exist. Previous data is not erased. |
"w" | Open file for writing. Creates new file if it does not exist. Erases existing data if file exists. |
"a" | Open file for appending. Creates new file if it does not exist. New data is added at the end; existing data is not erased. |
"r+" | Open existing file for reading and writing (update mode). File must exist. Data is not erased. |
"w+" | Open file for writing and reading. Creates new file if not exists. Erases existing data if file exists. |
"a+" | Open file for appending and reading. Creates new file if not exists. Cannot modify existing data. |
"rb" | Open binary file for reading. |
"wb" | Open binary file for writing. |
"ab" | Open binary file for appending. |
"rb+" | Open binary file for reading and writing. |
"wb+" | Create binary file for reading and writing. |
"ab+" | Open binary file for appending and reading. |
(c) Program to Read from "input.txt" and Write to "output.txt"
Approach:
- Open
input.txtin"r"(read) mode. - Open
output.txtin"w"(write) mode. - Read characters one by one from
input.txtusingfgetc(). - Write each character to
output.txtusingfputc(). - Close both files after the operation.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp_in, *fp_out;
char ch;
/* Open input.txt for reading */
fp_in = fopen("input.txt", "r");
if (fp_in == NULL)
{
printf("Error: Cannot open input.txt\n");
exit(1);
}
/* Open output.txt for writing */
fp_out = fopen("output.txt", "w");
if (fp_out == NULL)
{
printf("Error: Cannot open output.txt\n");
fclose(fp_in);
exit(1);
}
/* Read from input.txt and write to output.txt character by character */
while ((ch = fgetc(fp_in)) != EOF)
{
fputc(ch, fp_out);
}
printf("Data successfully copied from input.txt to output.txt\n");
/* Close both files */
fclose(fp_in);
fclose(fp_out);
return 0;
}
Explanation of Key Steps:
| Step | Code | Purpose |
|---|---|---|
| Open input file | fopen("input.txt", "r") | Opens file for reading |
| Open output file | fopen("output.txt", "w") | Opens/creates file for writing |
| NULL check | if (fp_in == NULL) | Checks if file opened successfully |
| Read character | fgetc(fp_in) | Reads one character from input file and advances file pointer |
| Write character | fputc(ch, fp_out) | Writes one character to output file |
| EOF check | != EOF | Stops reading when end of file is reached |
| Close files | fclose() | Releases file resources |
Sample Output:
Data successfully copied from input.txt to output.txt
The contents of input.txt will be completely copied into output.txt.
asked 2xavg 8 marks · 2075, 2074AnswerHideWrite a program to check whether a number entered is even or odd. [5]
Write a program to check whether a number entered is even or odd. [5]
When a number is divided by 2: - If the remainder is 0, the number is even - If the remainder is not 0, the number is odd The modulus operator % is used to find the remainder. --- --- Line Description ------------------- include<stdio.h ...
Study every one of these with model answers, flashcards, and MCQs.
Open CSC115 study modes