C Programming
Community
C Programming
2080 Boards
Section A
Answer any two questions.
Structure: A structure in C is a user-defined data type that allows grouping variables of different types under a single name.
Example:
struct Student {
int id;
char name[20];
float marks;
};
Nested Structure: A nested structure is a structure that contains another structure as a member.
Example:
struct Date {
int day, month, year;
};
struct Student {
int id;
char name[20];
struct Date dob; // nested structure
};
#include <stdio.h>
struct Fibonacci {
int n;
int term;
};
struct Result {
struct Fibonacci fib; // nested structure
int isPrime;
};
// Function to generate nth Fibonacci term
int generateFibonacci(int n) {
if(n == 1) return 0;
if(n == 2) return 1;
return generateFibonacci(n - 1) + generateFibonacci(n - 2);
}
// Function to check whether a number is prime
int isPrime(int num) {
if(num <= 1) return 0;
for(int i = 2; i*i <= num; i++) {
if(num % i == 0) return 0;
}
return 1;
}
int main() {
struct Result res;
printf("Enter the value of n: ");
scanf("%d", &res.fib.n);
res.fib.term = generateFibonacci(res.fib.n);
res.isPrime = isPrime(res.fib.term);
printf("The %dth Fibonacci term is %d.\n", res.fib.n, res.fib.term);
if(res.isPrime)
printf("%d is a prime number.\n", res.fib.term);
else
printf("%d is not a prime number.\n", res.fib.term);
return 0;
}
Relation between Array and Pointer:
-
In C, the name of an array acts as a pointer to its first element.
-
Array elements can be accessed using pointer arithmetic.
-
Example:
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr; // ptr points to arr[0]
printf("%d\n", *(ptr + 2)); // Outputs 30
Call by Value vs Call by Reference:
| Aspect | Call by Value | Call by Reference |
|---|---|---|
| Parameter Passing | Copies the actual value to the function | Passes the address of the variable |
| Effect on Original Variable | Original variable is not affected | Original variable can be changed |
| Memory Usage | Uses extra memory for copy | Less memory (directly modifies original) |
| Use | When function should not modify original | When function should modify original |
Example Program:
#include <stdio.h>
// Call by Value
void squareByValue(int x) {
x = x * x;
}
// Call by Reference
void squareByReference(int *x) {
*x = (*x) * (*x);
}
int main() {
int a = 5, b = 5;
squareByValue(a); // a remains 5
squareByReference(&b); // b becomes 25
printf("After call by value, a = %d\n", a);
printf("After call by reference, b = %d\n", b);
return 0;
}
Output:
After call by value, a = 5
After call by reference, b = 25
Connect with us on Discord to become a contributor.
Section B
Answer any eight questions.
In C, file handling uses File Pointers (FILE *) and different I/O functions. They are mainly of three types:
1. Character I/O Functions
-
Read/write one character at a time.
-
Syntax:
int fgetc(FILE *fp); // read a character
int fputc(int ch, FILE *fp); // write a character
2. String/Line I/O Functions
-
Read/write strings or lines.
-
Syntax:
char *fgets(char *str, int n, FILE *fp); // read a line
int fputs(const char *str, FILE *fp); // write a string
3. Formatted I/O Functions
-
Read/write formatted data (numbers, strings).
-
Syntax:
int fscanf(FILE *fp, const char *format, ...); // read formatted data
int fprintf(FILE *fp, const char *format, ...); // write formatted data
C program that reads a P × Q matrix, finds the largest integer in each row, and displays it.
#include <stdio.h>
int main() {
int P, Q, i, j;
printf("Enter number of rows (P): ");
scanf("%d", &P);
printf("Enter number of columns (Q): ");
scanf("%d", &Q);
int matrix[P][Q];
// Input matrix elements
printf("Enter the elements of the matrix:\n");
for(i = 0; i < P; i++) {
for(j = 0; j < Q; j++) {
scanf("%d", &matrix[i][j]);
}
}
// Find and display largest element of each row
printf("Largest element of each row:\n");
for(i = 0; i < P; i++) {
int max = matrix[i][0];
for(j = 1; j < Q; j++) {
if(matrix[i][j] > max) {
max = matrix[i][j];
}
}
printf("Row %d: %d\n", i+1, max);
}
return 0;
}
This program will correctly handle any P × Q matrix of integers and display the largest number of each row.
#include <stdio.h>
long long factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}
int main() {
int num;
scanf("%d", &num);
if(num < 0)
printf("Factorial is not defined for negative numbers.\n");
else
printf("%lld\n", factorial(num));
return 0;
}
def check_palindrome():
word = input("Enter a word: ")
processed_word = word.lower()
reversed_word = processed_word[::-1]
if processed_word == reversed_word:
print(f"'{word}' is a palindrome.")
else:
print(f"'{word}' is not a palindrome.")
if __name__ == "__main__":
check_palindrome()
Different types of operators are used to perform operations on variables and values.
The common types of operators include:
- Arithmetic Operators
- Relational Operators
- Logical Operators
- Assignment Operators
- Bitwise Operators
- Unary Operators
- Ternary/Conditional Operator
- Special Operators (e.g.,
sizeof, address-of&, dereference*, member access.and->)
Explanation of four types of operators:
-
Arithmetic Operators
These operators perform basic mathematical calculations. They operate on numerical operands and return a numerical result.- Operators:
+(Addition): Adds two operands.-(Subtraction): Subtracts the second operand from the first.*(Multiplication): Multiplies two operands./(Division): Divides the first operand by the second. For integer division, it truncates the fractional part.%(Modulus): Returns the remainder of an integer division.
- Example:
int a = 10, b = 3; int sum = a + b; // sum is 13 int remainder = a % b; // remainder is 1
- Operators:
-
Relational Operators
These operators compare two operands and return a Boolean result (true or false, often represented as 1 or 0 in languages like C/C++). They are primarily used in conditional statements and loops.- Operators:
==(Equal to): Returns true if both operands are equal.!=(Not equal to): Returns true if operands are not equal.>(Greater than): Returns true if the first operand is greater than the second.<(Less than): Returns true if the first operand is less than the second.>=(Greater than or equal to): Returns true if the first operand is greater than or equal to the second.<=(Less than or equal to): Returns true if the first operand is less than or equal to the second.
- Example:
int x = 20, y = 15; bool is_greater = (x > y); // is_greater is true (1) bool are_equal = (x == y); // are_equal is false (0)
- Operators:
-
Logical Operators
These operators are used to combine or negate Boolean expressions. They evaluate conditions and return a Boolean result (true or false).- Operators:
&&(Logical AND): Returns true if both operands are true.||(Logical OR): Returns true if at least one operand is true.!(Logical NOT): Reverses the logical state of its operand (true becomes false, false becomes true).
- Example:
bool condition1 = true, condition2 = false; bool result_and = condition1 && condition2; // result_and is false bool result_or = condition1 || condition2; // result_or is true bool result_not = !condition1; // result_not is false
- Operators:
-
Assignment Operators
Assignment operators are used to assign a value to a variable. The simple assignment operator=assigns the value on the right to the variable on the left. Compound assignment operators combine an arithmetic (or bitwise) operation with assignment, providing a shorthand for common operations.- Operators:
=(Simple Assignment): Assigns the value of the right operand to the left operand.+=(Add and Assign):x += yis equivalent tox = x + y.-=(Subtract and Assign):x -= yis equivalent tox = x - y.*=(Multiply and Assign):x *= yis equivalent tox = x * y./=(Divide and Assign):x /= yis equivalent tox = x / y.%=(Modulus and Assign):x %= yis equivalent tox = x % y.
- Example:
int value = 5; value += 3; // value is now 8 (equivalent to value = 5 + 3) value *= 2; // value is now 16 (equivalent to value = 8 * 2)
- Operators:
Program Trace:
-
Initialization:
iis initialized to0.kis declared.
-
Loop Execution (
for(k=5; k>=0; k--)):- k = 5:
i = i + kbecomesi = 0 + 5→i = 5. - k = 4:
i = i + kbecomesi = 5 + 4→i = 9. - k = 3:
i = i + kbecomesi = 9 + 3→i = 12. - k = 2:
i = i + kbecomesi = 12 + 2→i = 14. - k = 1:
i = i + kbecomesi = 14 + 1→i = 15. - k = 0:
i = i + kbecomesi = 15 + 0→i = 15. - k = -1: The loop condition
k >= 0(-1 >= 0) is false. Loop terminates.
- k = 5:
-
Print Statement:
printf("%d\t", i);prints the final value ofi.
Output:
15
#include<stdio.h>
int calculateSum(int num, int count, int sum){
if(count!=0){
return calculateSum(num+2,count-1,sum+num);
}
return sum;
}
int main(){
printf("The sum of first 10 even number is: %d",calculateSum(2,12,0));
return 0;
}
Dynamic memory allocation is the process of allocating memory during program execution (runtime) from the heap segment of memory, rather than at compile time or upon function call (stack). This allows programs to handle variable amounts of data whose size is not known until the program is running.
Key characteristics:
- Runtime allocation: Memory is requested and allocated while the program is actively executing.
- Heap memory: The allocated memory resides in the heap, a large pool of free memory managed by the operating system.
- Flexibility: It enables programs to create data structures (like arrays or lists) whose size can change dynamically based on user input or other runtime conditions.
- Manual management: Programmers are responsible for both allocating and deallocating (freeing) dynamically allocated memory. Failure to deallocate leads to memory leaks.
- Pointers: Memory is accessed via pointers returned by allocation functions.
Program Example (C Language):
This program demonstrates allocating an integer array of user-specified size at runtime using malloc and then deallocating it with free.
#include <stdio.h>
#include <stdlib.h> // Required for malloc and free
int main() {
int *arr; // Pointer to hold the base address of the allocated memory
int n, i;
printf("Enter the number of elements: ");
scanf("%d", &n);
// Allocate memory for 'n' integers using malloc
// malloc returns a void pointer, which is then cast to int*
// If allocation fails, malloc returns NULL
arr = (int *) malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1; // Indicate an error
}
printf("Enter %d integers:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]); // Store values in the allocated memory
}
printf("Elements entered are: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]); // Access values
}
printf("\n");
// Free the allocated memory to prevent memory leaks
free(arr);
printf("Memory freed successfully.\n");
return 0; // Indicate successful execution
}
#include <stdio.h>
int main() {
int arr[10], i, j, temp;
// Input 10 numbers
for(i = 0; i < 10; i++) {
scanf("%d", &arr[i]);
}
// Sorting in ascending order (Bubble Sort)
for(i = 0; i < 9; i++) {
for(j = 0; j < 9 - i; j++) {
if(arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// Display sorted array
for(i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}