1. Home
  2. Docs
  3. Model Question Solutions ...
  4. C Programming
  5. Model Questions Solution of C programming (2024)

Model Questions Solution of C programming (2024)

Group – “A” ( 10 X 1=10)

1. Define algorithms.

Ans: An algorithm is a step-by-step procedure or set of rules designed to solve a specific problem or perform a particular task. It’s essentially a finite sequence of well-defined instructions or computational procedures that, when followed, will achieve the desired outcome.

2. What is preprocessor directive?

Ans: A preprocessor directive is a command in a programming language that is processed by the compiler or interpreter before the actual compilation or interpretation of the code begins.

3. Differentiate between scanf() and gets()?

Ans: Both scanf() and gets() are used for input operations, scanf() is preferred for formatted input and is safer regarding buffer overflow, while gets() is less safe and less commonly used due to its inherent risks.

4. What is conditional operator?

Ans: The conditional operator, also known as the ternary operator, is a compact way to express conditional statements in programming languages. It takes three operands: a condition, a result for true, and a result for false

5. Differentiate between break and exit.

Ans: “break” is used to exit a loop or switch statement, while “exit” is used to terminate the entire program or a specific block of code.

6. How to initialize two dimensional matrix?

Ans: We can initialize a two-dimensional matrix in several ways, including static initialization, dynamic memory allocation, and using loops to set values.

7. What is function protocol?

Ans: A function protocol, sometimes referred to as a function signature or function prototype, is a declaration of a function that specifies its name, return type, and parameters (their types and order) without necessarily including the function’s body.

8. What is the use of double pointer?

Ans: Double pointers (pointers to pointers) are used for several important purposes like:

  • Dynamic Memory Allocation of 2D Arrays
  • Modifying Pointer Variables in Functions

9. Differentiate between array and structure.

Ans: Arrays are collections of elements that are all of the same data type where as Structures can contain elements (members) of different data types.

10. List out the different modes of file in file handling.

Ans: Here are the different modes of file handling in C:

  • “r” (read)
  • “w” (write)
  • “a” (append)
  • “r+” (read/update)
  • “w+” (write/update)
  • “a+” (append/update)

Group – “B” ( 5 X 3=15)

11. Write a program to check if input given by the user is divisible by 5 or 7.

Ans: Here is a program to check if input given by the user is divisible by 5 or 7:

#include <stdio.h>

int main() {
    int number;

    // Prompt the user for input
    printf("Enter an integer: ");
    scanf("%d", &number);

    // Check if the number is divisible by 5 or 7
    if (number % 5 == 0 && number % 7 == 0) {
        printf("The number %d is divisible by both 5 and 7.\n", number);
    } else if (number % 5 == 0) {
        printf("The number %d is divisible by 5.\n", number);
    } else if (number % 7 == 0) {
        printf("The number %d is divisible by 7.\n", number);
    } else {
        printf("The number %d is not divisible by either 5 or 7.\n", number);
    }

    return 0;
}

12. Write a program that uses a while loop to compute and print the sum of given numbers of cube. For example, if 3 is input, then the program should print 36, which is equal to 12+ 22+32.

Ans: Here is a program that uses a while loop to compute and print the sum of given numbers of cube. For example, if 3 is input, then the program should print 36, which is equal to 12+ 22+32:

#include <stdio.h>

int main() {
    int n, i = 1;
    int sum = 0;

    // Ask the user to input a number
    printf("Enter a number: ");
    scanf("%d", &n);

    // Compute the sum of the cubes using a while loop
    while (i <= n) {
        sum += i * i * i; // Adding the cube of the current number
        i++;
    }

    // Print the result
    printf("The sum of the cubes of the first %d natural numbers is %d\n", n, sum);

    return 0;
}

13. Write a program to read a line of text and display the number of vowels in it.

Ans: Here is a program to read a line of text and display the number of vowels in it:

#include <stdio.h>
#include <ctype.h>

int main() {
    char text[1000]; // Define a sufficiently large array to hold the input text
    int vowel_count = 0;

    // Prompt the user to enter a line of text
    printf("Enter a line of text: ");
    fgets(text, sizeof(text), stdin); // Read the line of text including spaces

    // Loop through each character in the text to count vowels
    for (int i = 0; text[i] != '\0'; i++) {
        char ch = tolower(text[i]); // Convert the character to lowercase
        if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
            vowel_count++;
        }
    }

    // Display the number of vowels
    printf("Number of vowels: %d\n", vowel_count);

    return 0;
}

14. Write a program that takes string as input and display the length of it.

Ans: Here is a program that takes string as input and display the length of it:

#include <stdio.h>
#include <string.h>

int main() {
    char inputString[1000]; // Declare a character array to hold the input string

    printf("Enter a string: ");
    fgets(inputString, sizeof(inputString), stdin); // Read the input string

    // Remove the newline character that fgets includes
    size_t length = strlen(inputString);
    if (inputString[length - 1] == '\n') {
        inputString[length - 1] = '\0';
        length--; // Adjust the length after removing the newline
    }

    printf("The length of the entered string is: %zu\n", length);

    return 0;
}

15. Write a program to compute the factorial of number entered by the user using recursion.

Ans: Here is a program to compute the factorial of number entered by the user using recursion:

#include <stdio.h>

// Function to compute factorial recursively
int factorial(int n) {
    // Base case: factorial of 0 is 1
    if (n == 0)
        return 1;
    // Recursive case: compute factorial of (n-1) and multiply with n
    else
        return n * factorial(n - 1);
}

int main() {
    int num;
    printf("Enter a non-negative integer: ");
    scanf("%d", &num);
    // Check if the number is non-negative
    if (num < 0) {
        printf("Error: Please enter a non-negative integer.\n");
    } else {
        // Compute factorial and display the result
        printf("Factorial of %d is %d\n", num, factorial(num));
    }
    return 0;
}

16. Write a program to draw triangle using graphics function.

Ans: Here is a program to draw triangle using graphics function:

#include <stdio.h>
#include <graphics.h>

int main() {
    int gd = DETECT, gm;
    initgraph(&gd, &gm, "");

    // Coordinates of the triangle vertices
    int x1 = 100, y1 = 300;
    int x2 = 300, y2 = 100;
    int x3 = 500, y3 = 300;

    // Drawing the triangle
    line(x1, y1, x2, y2);
    line(x2, y2, x3, y3);
    line(x3, y3, x1, y1);

    getch();
    closegraph();
    return 0;
}

Group – “C” ( 3 X 5 = 15)

17. Explain the different logical operators in detail.

Ans: In C programming, logical operators are used to perform logical operations on boolean values (true or false). These operators allow you to combine or manipulate boolean expressions. C provides three main logical operators: && (logical AND), || (logical OR), and ! (logical NOT).

‣ Logical AND (&&)

The logical AND operator (&&) returns true if both operands are true, otherwise it returns false.

  • Syntax: expression1 && expression2
  • Example:
if (x > 0 && y < 10) {
    // Executes if both conditions are true
}

‣ Logical OR (||)

The logical OR operator (||) returns true if at least one of the operands is true, otherwise it returns false.

  • Syntax: expression1 || expression2
  • Example:
if (x == 0 || y == 0) {
    // Executes if either x or y (or both) is zero
}

‣ Logical NOT (!)

The logical NOT operator (!) is a unary operator that negates the value of its operand. If the operand is true, ! converts it to false, and if the operand is false, ! converts it to true.

  • Syntax: !expression
  • Example:
if (!(x == 0)) {
    // Executes if x is not equal to zero
}

18. How array can be passed as function arguments? Illustrate with suitable example.

Ans: Here is the through which array can be passed as function arguments:

#include <stdio.h>

// Function declaration
void printArray(int arr[], int size);

int main() {
    int array[] = {1, 2, 3, 4, 5};
    int size = sizeof(array) / sizeof(array[0]);

    // Calling the function and passing the array
    printArray(array, size);

    return 0;
}

// Function definition to print the array elements
void printArray(int arr[], int size) {
    printf("Array elements: ");
    for (int i = 0; i < size; ++i) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

19. What do you mean by Dynamic Memory Allocation(DMA)? Explain the use of malloc() and free() function with suitable example.

Ans: Dynamic Memory Allocation (DMA) refers to the allocation of memory at runtime, rather than at compile time. This allows programs to dynamically allocate memory as needed, enabling more flexible memory management. In languages like C and C++, DMA is commonly used when the size of memory required is not known until the program runs, or when memory needs to be allocated and deallocated during program execution.

In C programming, the malloc() function is used to dynamically allocate memory, and the free() function is used to deallocate memory when it’s no longer needed. Here’s an explanation along with an example:

‣ malloc() Function:

malloc() stands for “memory allocation”. It dynamically allocates a block of memory of the specified size and returns a pointer to the beginning of that block. If the allocation fails (i.e., if there is not enough memory available), malloc() returns NULL.

Syntax:

void* malloc(size_t size);

Example:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr;
    int size = 5;

    // Dynamically allocate memory for an array of integers
    arr = (int *)malloc(size * sizeof(int));

    // Check if memory allocation was successful
    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    // Populate the array with some values
    for (int i = 0; i < size; i++) {
        arr[i] = i * 2;
    }

    // Print the array
    printf("Array elements: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }

    // Free dynamically allocated memory
    free(arr);

    return 0;
}

‣ free() Function:

free() is used to deallocate memory that was previously allocated using malloc(), calloc(), or realloc(). It takes a pointer to the memory block to be deallocated as its argument.

Syntax:

void free(void *ptr);

Example (continued):

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr;
    int size = 5;

    arr = (int *)malloc(size * sizeof(int));

    // Check if memory allocation was successful
    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    // Populate the array with some values
    for (int i = 0; i < size; i++) {
        arr[i] = i * 2;
    }

    // Print the array
    printf("Array elements: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }

    // Free dynamically allocated memory
    free(arr);

    // Accessing arr after deallocation would result in undefined behavior
    // arr[0] = 10; // Uncommenting this would lead to undefined behavior

    return 0;
}

20. Write a program to create and write N number in a file “Number.txt”. Open this file to read it contents and write all positive numbers in the file “Positive.txt” and all negative numbers in the file “Negative.txt”.

Ans: Here is a program to create and write N number in a file “Number.txt”. Open this file to read it contents and write all positive numbers in the file “Positive.txt” and all negative numbers in the file “Negative.txt”:

#include <stdio.h>

int main() {
    int N;
    printf("Enter the number of elements: ");
    scanf("%d", &N);

    // Create and write N numbers to Number.txt
    FILE *numberFile = fopen("Number.txt", "w");
    if (numberFile == NULL) {
        printf("Error opening file.\n");
        return 1;
    }
    printf("Enter %d numbers:\n", N);
    int num;
    for (int i = 0; i < N; i++) {
        scanf("%d", &num);
        fprintf(numberFile, "%d\n", num);
    }
    fclose(numberFile);

    // Open Number.txt to read its contents
    numberFile = fopen("Number.txt", "r");
    if (numberFile == NULL) {
        printf("Error opening file.\n");
        return 1;
    }

    // Create Positive.txt and Negative.txt and write positive and negative numbers respectively
    FILE *positiveFile = fopen("Positive.txt", "w");
    FILE *negativeFile = fopen("Negative.txt", "w");
    if (positiveFile == NULL || negativeFile == NULL) {
        printf("Error creating or opening files.\n");
        return 1;
    }

    // Read numbers from Number.txt and write them to Positive.txt or Negative.txt
    while (fscanf(numberFile, "%d", &num) == 1) {
        if (num >= 0) {
            fprintf(positiveFile, "%d\n", num);
        } else {
            fprintf(negativeFile, "%d\n", num);
        }
    }

    // Close all files
    fclose(numberFile);
    fclose(positiveFile);
    fclose(negativeFile);

    printf("Positive and negative numbers written to Positive.txt and Negative.txt respectively.\n");

    return 0;
}

Group – “D” ( 2 X 10 = 20)

21. Why looping is used in programming ? Explain different looping statement with appropriate example.

Ans: Looping is used in C programming (as well as in many other programming languages) for several reasons:

» Repetition:

Loops allow you to execute a block of code repeatedly, which is useful when you need to perform a task multiple times without writing the same code over and over again.

» Iterating Over Data Structures:

Loops are commonly used to traverse arrays, strings, linked lists, and other data structures. They allow you to access each element of the data structure one by one.

» Conditional Execution:

Loops often involve a condition that determines whether the loop should continue executing or terminate. This allows you to control the flow of your program based on certain conditions.

» Efficiency:

Loops make code more efficient by reducing redundancy. Instead of writing the same code multiple times, you can use loops to iterate over a set of data or perform a task a specific number of times.

» Automation:

Loops are essential for automating repetitive tasks. For example, you might use a loop to process a batch of input data, perform calculations on each item, and generate corresponding output.

Different Looping Statements in C Programming:

for Loop: The for loop is commonly used when you know in advance how many times you want to execute a block of code.

#include <stdio.h>

int main() {
    // Example: Print numbers from 1 to 5
    for (int i = 1; i <= 5; i++) {
        printf("%d ", i);
    }
    return 0;
}

while Loop: The while loop is used when the number of iterations is not known in advance but a condition needs to be checked before each iteration.

#include <stdio.h>

int main() {
    // Example: Print numbers from 1 to 5 using while loop
    int i = 1;
    while (i <= 5) {
        printf("%d ", i);
        i++;
    }
    return 0;
}

do-while Loop: The do-while loop is similar to the while loop, but it ensures that the block of code is executed at least once before the condition is checked.

#include <stdio.h>

int main() {
    // Example: Print numbers from 1 to 5 using do-while loop
    int i = 1;
    do {
        printf("%d ", i);
        i++;
    } while (i <= 5);
    return 0;
}

Example Illustrating the Use of Different Looping Statements:

Let’s say you want to calculate the sum of numbers from 1 to 10:

#include <stdio.h>

int main() {
    int sum = 0;

    // Using for loop
    for (int i = 1; i <= 10; i++) {
        sum += i;
    }
    printf("Sum using for loop: %d\n", sum);

    sum = 0;
    int i = 1;

    // Using while loop
    while (i <= 10) {
        sum += i;
        i++;
    }
    printf("Sum using while loop: %d\n", sum);

    sum = 0;
    i = 1;

    // Using do-while loop
    do {
        sum += i;
        i++;
    } while (i <= 10);
    printf("Sum using do-while loop: %d\n", sum);

    return 0;
}

Output:

Sum using for loop: 55
Sum using while loop: 55
Sum using do-while loop: 55

22. What is structure? How is it different from union? create a structure “student” having the data members name, roll_number and percentage. Write a program to display the name of all students having percentage greater than or equal to 80.

Ans: In programming languages like C, a structure is a user-defined data type that allows you to group together variables of different types under a single name. Each variable within the structure is called a member or a field.

Here’s a tabular comparison between structures and unions:

FeatureStructureUnion
Definition Syntaxstructunion
Memory AllocationAllocates memory for each memberShares memory among members
SizeSize is sum of sizes of all membersSize is equal to size of largest member
Member AccessMembers accessed individuallyMembers accessed interchangeably
Memory EfficiencyLess memory efficient due to separate allocations for each memberMore memory efficient when only one member is active at a time
UsageWhen multiple types of data are to be stored simultaneouslyWhen only one type of data is needed at a time
InitializationCan initialize each member individuallyInitialized as a whole or individually, but changes to one member can affect others
Examplec struct Point { int x; int y; };c union Data { int i; float f; };

Here’s how you can define a structure “student” with the data members name, roll_number, and percentage in C:

#include <stdio.h>

// Define the structure
struct student {
    char name[50];
    int roll_number;
    float percentage;
};

int main() {
    // Declare an array of structures to store student data
    struct student students[5]; // Assuming we have 5 students

    // Example data initialization
    students[0].roll_number = 1;
    students[1].roll_number = 2;
    students[2].roll_number = 3;
    students[3].roll_number = 4;
    students[4].roll_number = 5;

    // Assuming names and percentages are provided elsewhere

    // Display names of students with percentage >= 80
    printf("Students with percentage >= 80:\n");
    for (int i = 0; i < 5; i++) {
        if (students[i].percentage >= 80.0) {
            printf("%s\n", students[i].name);
        }
    }

    return 0;
}

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *