1. Home
  2. Docs
  3. Model Question Solutions ...
  4. C Programming
  5. Questions and Answers of C programing of 2023(exam)

Questions and Answers of C programing of 2023(exam)

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

1. Define object code?

Ans: “object code” refers to the intermediate representation of a program after it has been compiled from source code but before it is linked into an executable file.

2. Write a rule to define the variable?

Ans: In C programming, a variable is defined using the following rule:

Syntax:

data_type variable_name;

3. Is printf() is formatted or unformatted I/O ? Justify.

Ans: The printf() function in C is considered a formatted I/O function because it allows the programmer to specify the format of the output.

4. What do you mean by implicit type conversion?

Ans: Implicit type conversion, also known as type coercion, refers to the automatic conversion of a value from one data type to another by the compiler or interpreter during program execution.

5. Why we need exit function?

Ans: Here are several reasons why we need the exit function:

  • Termination of Program
  • Error Handling

6. Define null character.

Ans: The null character is a special character used to indicate the end of a string. It is represented by the escape sequence \0. The null character has an ASCII value of 0.

7. How do complier determine the life time of variable?

Ans: the compiler determines the lifetime of a variable based on its scope and storage duration like:

‣ Automatic (Local) Variables:

Lifetime: Starts when the block in which they are declared is entered and ends when the block is exited.

‣ Global variables:

Lifetime: Lasts for the entire duration of the program execution.

8. List any one advantages and disadvantages of pointer.

Ans:

Advantages of Pointers:

  • Efficient Memory Management: Pointers allow for dynamic memory allocation, enabling the creation of complex data structures like linked lists, trees, and graphs. This helps in efficiently using memory and optimizing performance for specific tasks.

Disadvantages of Pointers:

  • Complexity and Risk of Errors: Pointers can be challenging to use correctly, especially for beginners. Incorrect handling can lead to serious issues such as memory leaks, segmentation faults, and buffer overflows, which can be difficult to debug and fix.

9. When do you prefer union rather than structure ? Give reasons.

Ans: we prefer a union when memory efficiency is crucial, when dealing with variant data types that are mutually exclusive, or when interfacing with hardware at a low level. we Use structures when you need to store multiple related variables simultaneously and need clear data organization.

10. What is the different between append mode and write mode in file handling ?

Ans: Here’s the difference between append mode and write mode:

In write mode, if the file already exists, it gets truncated (emptied) before writing.

In append mode, if the file exists, data is written to the end of the file without truncating the existing content.

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

11. Draw a flowchart to find the smallest among three given integers.

Ans: Here is a flowchart to find the smallest among three given integers:

Screenshot 2024 05 19 165140

12. what are the different data types in C programming and how are they use?

Ans: Here are the different data types in C programming and how are they use:

‣ int: Used to store integer values (whole numbers) like -1, 0, 1, 100, etc.

int age = 25;

‣ float: Used to store floating-point numbers (decimal numbers) like 3.14, -0.5, etc.

float pi = 3.14;

‣ double: Similar to float but with double precision. Used for more accurate floating-point calculations.

double salary = 50000.50;

‣ char: Used to store a single character like ‘a’, ‘b’, ‘7’, ‘$’, etc.

char grade = 'A';

‣ _Bool: Used to store boolean values. In C, 0 represents false and any non-zero value represents true.

_Bool isTrue = 1; // true

‣ void: Represents the absence of a type. It is commonly used as a return type for functions that don’t return a value, or as a pointer to an unspecified type.

void printMessage() {
    printf("Hello, World!\n");
}

‣ Arrays: Used to store multiple values of the same type in contiguous memory locations.

Arrays: Used to store multiple values of the same type in contiguous memory locations.

‣ Pointers: Variables that store memory addresses. They can point to variables, arrays, or functions.

int *ptr;

13. Describe the significant of escape sequence and delimiter with examples.

Ans: In C programming, escape sequences and delimiters play significant roles in handling special characters within strings.

→ Escape Sequences:

Escape sequences are combinations of characters that have a special meaning when encountered in a string. They typically start with a backslash \. Here are some common escape sequences in C:

  1. \n: Represents a newline character. It moves the cursor to the beginning of the next line.
  2. \t: Represents a tab character. It causes the cursor to move to the next tab stop.
  3. \\: Represents a backslash character itself.
  4. \": Represents a double quote character within a string.
  5. \': Represents a single quote character within a character constant.

Example:

#include <stdio.h>

int main() {
    printf("Hello\nWorld\n");   // Output: Hello
                                 //         World

    printf("Tab\tSeparated\n");  // Output: Tab   Separated

    printf("This is a backslash: \\ \n");  // Output: This is a backslash: \

    printf("This is a double quote: \" \n");  // Output: This is a double quote: "
    
    printf("This is a single quote: \' \n");  // Output: This is a single quote: '
    
    return 0;
}

→Delimiters:

Delimiters are characters used to mark the boundaries of strings or tokens in C. In C programming, the most commonly used delimiter for strings is the double quote ("). It is used to indicate the beginning and end of a string literal.

Example:

#include <stdio.h>

int main() {
    char str1[] = "Hello, World!";  // Delimited by double quotes

    printf("%s\n", str1);  // Output: Hello, World!

    return 0;
}

14. How pointer is used in arithmetic operations. illustrate with an example.

Ans: In C programming, pointers can be used in arithmetic operations to navigate through memory addresses, allowing for dynamic memory allocation and manipulation. When performing arithmetic operations on pointers, the compiler takes into account the size of the data type being pointed to.

Here’s a simple example illustrating how pointers are used in arithmetic operations:

#include <stdio.h>

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int *ptr = arr; // Pointer pointing to the first element of the array

    printf("Value at ptr: %d\n", *ptr); // Prints the value at ptr, which is 10

    // Move the pointer to the next element of the array using pointer arithmetic
    ptr++; // Incrementing the pointer moves it to the next integer in memory
    printf("Value at ptr after incrementing: %d\n", *ptr); // Prints the value at ptr, which is now 20

    // Move the pointer back to the previous element of the array using pointer arithmetic
    ptr--; // Decrementing the pointer moves it back to the previous integer in memory
    printf("Value at ptr after decrementing: %d\n", *ptr); // Prints the value at ptr, which is now 10

    // Adding an integer to the pointer moves it forward by that many elements
    ptr = ptr + 2; // Move the pointer two elements ahead
    printf("Value at ptr after adding 2: %d\n", *ptr); // Prints the value at ptr, which is now 30

    return 0;
}

15. Create a structure “Mobile” with the data member model and price and display the model of mobile having price more than Rs. 10,000.

Ans: Here is a structure “Mobile” with the data member model and price and display the model of mobile having price more than Rs. 10,000.

#include <stdio.h>

// Define the structure Mobile
struct Mobile {
    char model[50];
    float price;
};

// Function to display models of mobiles with price > 10000
void displayExpensiveMobiles(struct Mobile *mobiles, int size) {
    printf("Mobiles with price more than Rs. 10,000:\n");
    for (int i = 0; i < size; i++) {
        if (mobiles[i].price > 10000) {
            printf("%s\n", mobiles[i].model);
        }
    }
}

int main() {
    // Sample mobile data
    struct Mobile mobiles[] = {
        {"Model1", 9000},
        {"Model2", 12000},
        {"Model3", 8000},
        {"Model4", 15000}
    };

    int size = sizeof(mobiles) / sizeof(mobiles[0]);

    // Display mobiles with price > 10000
    displayExpensiveMobiles(mobiles, size);

    return 0;
}

16. Write a program to copy the content of one file to another file.

Ans: Here is a program to copy the content of one file to another file:

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

int main() {
    FILE *source_file, *destination_file;
    char source_filename[100], destination_filename[100];
    char ch;

    // Get the source file name
    printf("Enter the source file name: ");
    scanf("%s", source_filename);

    // Open the source file in read mode
    source_file = fopen(source_filename, "r");
    if (source_file == NULL) {
        printf("Error opening the source file.\n");
        exit(1);
    }

    // Get the destination file name
    printf("Enter the destination file name: ");
    scanf("%s", destination_filename);

    // Open the destination file in write mode
    destination_file = fopen(destination_filename, "w");
    if (destination_file == NULL) {
        printf("Error opening the destination file.\n");
        exit(1);
    }

    // Copy content from source to destination
    while ((ch = fgetc(source_file)) != EOF) {
        fputc(ch, destination_file);
    }

    printf("File copied successfully.\n");

    // Close both files
    fclose(source_file);
    fclose(destination_file);

    return 0;
}

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

17. Write a program to find the sum of digits of a given integer using recursion. ( example: input= 123 , output is 1+2+3=6).

Ans: Here is a program to find the sum of digits of a given integer using recursion:

#include <stdio.h>

// Function to calculate the sum of digits recursively
int sumOfDigits(int num) {
    // Base case: If the number is single digit, return it
    if (num < 10)
        return num;
    // Recursive case: Add the last digit to the sum of digits of the remaining number
    else
        return (num % 10) + sumOfDigits(num / 10);
}

int main() {
    int num;
    printf("Enter an integer: ");
    scanf("%d", &num);
    
    // Calculate sum of digits using recursion
    int sum = sumOfDigits(num);
    
    printf("Sum of digits of %d is %d\n", num, sum);
    
    return 0;
}

18. How do you draw a rectangle in Graphics in C? Write a code.

Ans: Here is code to draw a rectangle in graphics in C:

#include <graphics.h>

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

    // Coordinates of the rectangle
    int left = 100, top = 100, right = 300, bottom = 200;

    // Drawing rectangle
    rectangle(left, top, right, bottom);

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

19. Describe any four storage classes in C with example.

Ans: Here are four main storage classes in C: auto, register, static, and extern. Here’s a brief description of each along with an example:

‣ auto: Variables declared with the auto storage class are automatically allocated memory when the block they are defined in is entered, and deallocated when the block is exited. This is the default storage class for all local variables.

#include <stdio.h>

int main() {
    auto int x = 10; // 'auto' keyword is optional
    printf("Value of x: %d\n", x);
    return 0;
}

‣ register: The register storage class is similar to auto, but it hints to the compiler to store the variable in a CPU register for faster access, though the compiler may ignore this hint.

#include <stdio.h>

int main() {
    register int y = 20;
    printf("Value of y: %d\n", y);
    return 0;
}

‣ static: Variables with the static storage class are allocated memory at the start of the program and retain their value between function calls. If declared within a function, they retain their value across function calls.

#include <stdio.h>

void func() {
    static int z = 30;
    printf("Value of z: %d\n", z);
    z++;
}

int main() {
    func(); // Output: Value of z: 30
    func(); // Output: Value of z: 31
    return 0;
}

‣ extern: The extern storage class is used to declare a global variable that is defined in another source file. It allows multiple files to share a global variable.

    File1.c:

    #include <stdio.h>
    
    int count = 5;
    

    File2.c:

    #include <stdio.h>
    
    extern int count;
    
    int main() {
        printf("Value of count: %d\n", count); // Output: Value of count: 5
        return 0;
    }
    

    20. Display the following pattern using loop.

    BIMMIB

    IMMI

    MM

    Ans: Here is the required code:

    #include <stdio.h>
    
    int main() {
        int rows = 3;
        int i, j;
    
        for (i = 0; i < rows; i++) {
            // Print 'M' characters
            for (j = i; j < rows; j++) {
                printf("M");
            }
            
            // Print 'I' characters
            for (j = 0; j <= i * 2; j++) {
                printf("I");
            }
    
            // Print 'B' characters
            for (j = i; j < rows; j++) {
                printf("B");
            }
    
            printf("\n");
        }
    
        return 0;
    }

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

    21. Discuss some commonly used string library functions in C programming. Provide example of each function.

    Ans: Here are some commonly used string library functions in C programming along with examples for each:

    ‣ strlen(): Calculates the length of a string.

    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char str[] = "Hello, World!";
        int length = strlen(str);
        printf("Length of the string: %d\n", length);
        return 0;
    }
    

    ‣ strcpy(): Copies one string to another.

    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char source[] = "Hello, World!";
        char destination[20];
        strcpy(destination, source);
        printf("Copied string: %s\n", destination);
        return 0;
    }
    

    ‣ strcat(): Concatenates (appends) one string to the end of another.

    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char str1[20] = "Hello, ";
        char str2[] = "World!";
        strcat(str1, str2);
        printf("Concatenated string: %s\n", str1);
        return 0;
    }
    

    ‣ strcmp(): Compares two strings.

    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char str1[] = "apple";
        char str2[] = "banana";
        int result = strcmp(str1, str2);
        if (result == 0)
            printf("Strings are equal\n");
        else if (result < 0)
            printf("str1 is less than str2\n");
        else
            printf("str1 is greater than str2\n");
        return 0;
    }
    

    ‣ strncmp(): Compares specified number of characters of two strings.

    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char str1[] = "apple";
        char str2[] = "apply";
        int result = strncmp(str1, str2, 3); // Compare only first 3 characters
        if (result == 0)
            printf("First 3 characters are equal\n");
        else if (result < 0)
            printf("First 3 characters of str1 are less than str2\n");
        else
            printf("First 3 characters of str1 are greater than str2\n");
        return 0;
    }
    

    ‣ strchr(): Finds the first occurrence of a character in a string.

    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char str[] = "Hello, World!";
        char *ptr = strchr(str, 'o');
        printf("Character found at position: %ld\n", ptr - str);
        return 0;
    }
    

    ‣ strstr(): Finds the first occurrence of a substring in a string.

    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char str[] = "Hello, World!";
        char *ptr = strstr(str, "World");
        printf("Substring found at position: %ld\n", ptr - str);
        return 0;
    }
    

    ‣ strtok(): Splits a string into tokens based on a delimiter.

    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char str[] = "Hello, World! How are you?";
        char *token = strtok(str, " ");
        while (token != NULL) {
            printf("%s\n", token);
            token = strtok(NULL, " ");
        }
        return 0;
    }
    

    ‣ strncpy(): Copies a specified number of characters from one string to another.

    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char source[] = "Hello, World!";
        char destination[20];
        strncpy(destination, source, 5); // Copy only first 5 characters
        destination[5] = '\0'; // Null-terminate the string
        printf("Copied string: %s\n", destination);
        return 0;
    }
    

    ‣ strncat(): Concatenates a specified number of characters from one string to another.

    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char str1[20] = "Hello, ";
        char str2[] = "World!";
        strncat(str1, str2, 3); // Concatenate only first 3 characters of str2
        printf("Concatenated string: %s\n", str1);
        return 0;
    }
    

    22. Compare and contrast passing arguments by value and passing arguments by address in C programming. Provide example.

    Ans: Let’s compare and contrast these two approaches:

    ‣ Passing by Value:

    • In passing by value, a copy of the argument’s value is passed to the function.
    • Changes made to the parameter inside the function do not affect the original variable in the calling function.
    • Typically used for passing basic data types like integers, floats, characters, etc.
    • Simple and straightforward but can be less efficient for large data structures.

    Example:

    #include <stdio.h>
    
    // Function prototype
    void changeValue(int x);
    
    int main() {
        int num = 10;
        
        // Passing num by value
        changeValue(num);
        
        // num remains unchanged
        printf("Value of num: %d\n", num); // Output will be 10
        
        return 0;
    }
    
    // Function definition
    void changeValue(int x) {
        x = 20; // Changes made to x inside this function do not affect num in main
    }
    

    ‣ Passing by Address (Passing by Reference):

    • In passing by address, the memory address of the argument is passed to the function.
    • Changes made to the parameter inside the function affect the original variable in the calling function.
    • Used for passing complex data structures like arrays, structures, and for modifying the original variables.
    • Slightly more complex but more efficient for large data structures.

    Example:

    #include <stdio.h>
    
    // Function prototype
    void changeValue(int *x);
    
    int main() {
        int num = 10;
        
        // Passing num by address
        changeValue(&num);
        
        // num has been changed
        printf("Value of num: %d\n", num); // Output will be 20
        
        return 0;
    }
    
    // Function definition
    void changeValue(int *x) {
        *x = 20; // Changes made to *x (which is the value at the address pointed to by x) affect num in main
    }
    

    In conclusion, passing by value creates a copy of the value being passed, while passing by address allows the function to directly modify the original variable by working with its memory address. Each method has its advantages and use cases, depending on the specific requirements of the program.

    How can we help?

    Leave a Reply

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