BCA C Programming Question Paper Solution 2018 , 2019 , 2020 - 2nd Semester

BCA C Programming Question Paper Solution  2018 , 2019 , 2020 - 2nd Semester

BCA C Programming Question Paper Solution  2018 , 2019 , 2020 - 2nd Semester



BCA C Programming Question Paper Solution 2018 - 2nd Semester

Bachelor in Computer Applications  

Course Title: C Programming

Code No: CACS151 

Semester: II  

Full Marks: 60  

Pass Marks: 24  

Time: 3 hours  


Candidates are required to answer the questions in their own words as far as possible. Attempt all the questions.


Group A: Circle (O) the correct answer.  [10x1 = 10] 

1. Which of the following doesn't require an & for the input in scanf()? [1]
   a. char name[10];
   b. float name[10];
   c. int name[10];
   d. double name[10];

2. What is the memory size of float data type in C? [1]
   a. 4 Bytes
   b. 8 Bytes
   c. Depends on the system/compiler
   d. Cannot be determined.

3. What will be the output of the following C code? [1]

#include<stdio.h>
int main()
{
    int x=3,y;
    y=(++x)+(x++);
    printf("%d",y);
    return 0;
}
   a. 6
   b. 8
   c. 7
   d. 9


4. Which keyword is used to come out of a loop only for that iteration? [1]
   a. break
   b. continue
   c. return
   d. void

5. Bitwise operators can operate upon? [1]
   a. Double and chars
   b. floats and doubles
   c. int and floats
   d. int and chars

6. In C, if you pass an array as an argument to a function, what actually gets passed? [1]
   a. Value of elements in an array.
   b. First element in an array.
   c. The address of first element in an array.
   d. The address of last element in an array.

7. Which operator is used to access the members of structure using structure variable? [1]
   a. Address operator (&)
   b. Dot operator (.)
   c. Pointer operator ()
   d. Arrow operator (→)

8. Which function is used to record input from file? [1]
   a. fprintf()
   b. fwrite()
   c. ftell()
   d. fread()

9. Which of the following is a keyword used for a storage class? [1]
   a. printf
   b. goto
   c. external
   d. break

10. What will be the size of the following union declaration? [1]
    union test {
        int x;
        char y;
        float z;
    };
    a. 8 bytes
    b. 13 bytes
    c. 1 byte
    d. 4 bytes

Group B: Attempt any SIX questions. [6x5 = 30]

11. What is software process model? Differentiate between cohesion and coupling in programming. 
[1+4]

Software Process Model:

A software process model is a simplified representation of a software development process. It outlines the steps involved in building software, from initial requirements gathering to final testing and deployment. Different software process models offer various approaches to organizing and managing the development process, each with its own set of advantages and disadvantages. Some common software process models include the waterfall model, agile methodologies like Scrum and Kanban, iterative models, and spiral models.

Cohesion and Coupling in Programming:

Cohesion:

Cohesion refers to the degree of interrelatedness or unity within a module or component in a software system.
It measures how closely the elements within a module are related to each other and how strongly they work together to achieve a common purpose.
High cohesion implies that the elements within a module are highly related and focused on performing a single, well-defined task or functionality.
There are different levels of cohesion, ranging from low cohesion (where the elements within a module are loosely related and perform multiple unrelated tasks) to high cohesion (where the elements within a module are tightly related and focused on a single task).

Coupling:

Coupling refers to the degree of interdependence between modules or components in a software system.
It measures how much one module relies on another module to accomplish its tasks and how closely they are connected to each other.
Low coupling implies that the modules are loosely connected and can be modified or replaced independently without affecting other parts of the system.
High coupling indicates that the modules are tightly interconnected, making it difficult to modify or replace one module without affecting others.
There are different types of coupling, including loose coupling (where modules have minimal dependencies on each other) and tight coupling (where modules have strong dependencies and rely heavily on each other).
In summary, cohesion focuses on the internal unity and organization within a module, while coupling deals with the external dependencies and interactions between modules in a software system.

12. Define keyword and identifiers. Explain rules for defining valid identifiers. [2+3]

Keyword: In programming languages, a keyword is a reserved word that has a predefined meaning and purpose. Keywords are fundamental building blocks of a programming language's syntax and are used to define the structure and behavior of programs. These words cannot be used as identifiers (variable names, function names, etc.) because they are already assigned specific meanings within the language.

Identifiers: Identifiers are names given to various program elements such as variables, functions, arrays, etc. They provide a way for programmers to reference and manipulate these elements within their code. Identifiers must follow specific rules and conventions defined by the programming language in order to be valid.

Rules for Defining Valid Identifiers:

Validity Rule: Identifiers must begin with a letter (uppercase or lowercase) or an underscore (_). They cannot begin with a digit.

Character Set Rule: After the first character, an identifier can contain letters (uppercase or lowercase), digits (0-9), or underscores (_).

Length Rule: There is typically a limit on the maximum length of an identifier imposed by the programming language. However, this length limit varies from language to language.

Reserved Word Rule: Identifiers cannot be the same as keywords or reserved words of the programming language.

Case Sensitivity Rule: Most programming languages are case-sensitive, meaning uppercase and lowercase letters are treated as distinct characters. Therefore, identifiers like "myVar" and "MyVar" would be considered different.

Meaningful Names Rule: While not enforced by the language itself, it is a good practice to choose meaningful and descriptive names for identifiers to enhance code readability and maintainability.

Following these rules ensures that identifiers are correctly recognized and processed by the compiler or interpreter, thereby preventing syntax errors and ambiguities in the code.


13. List the operators used in C on the basis of utility. Explain the concept of bitwise operator. [2+3]

Operators Used in C Based on Utility:

Operators in C can be categorized based on their utility into several groups:

a. Arithmetic Operators:

Used for arithmetic operations such as addition (+), subtraction (-), multiplication (), division (/), and modulus (%).

b. Relational Operators: 

Used for comparing two values. Examples include equal to (==), not equal to (!=), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=).

c. Logical Operators: 

Used to perform logical operations on boolean values. These include logical AND (&&), logical OR (||), and logical NOT (!).

d. Assignment Operators: 

Used to assign values to variables. Examples include assignment (=), addition assignment (+=), subtraction assignment (-=), multiplication assignment (=), division assignment (/=), etc.

e. Bitwise Operators: 

Used to perform bit-level operations on operands. These include bitwise AND (&), bitwise OR (|), bitwise XOR (^), bitwise NOT (~), left shift (<<), and right shift (>>).

f. Increment and Decrement Operators: 

Used to increment (++) or decrement (--) the value of a variable by one.

g. Conditional Operator (Ternary Operator): 

Used for conditional expressions. It has the form `condition ? expression1 : expression2`, where if the condition is true, expression1 is evaluated, otherwise expression2 is evaluated.

h. Comma Operator: 

Used to separate expressions. It evaluates each expression from left to right and returns the value of the rightmost expression.

Concept of Bitwise Operator:

Bitwise operators in C are used to perform operations at the bit-level. These operators manipulate individual bits of operands. The concept of bitwise operators stems from the fact that computers represent data at the lowest level using binary digits (bits), which can be either 0 or 1.

a. Bitwise AND (&): 

It performs a logical AND operation on each pair of corresponding bits of the operands. The result is 1 if both bits are 1; otherwise, it's 0.

b. Bitwise OR (|):

It performs a logical OR operation on each pair of corresponding bits of the operands. The result is 1 if at least one of the bits is 1.

c. Bitwise XOR (^): 

It performs a logical XOR (exclusive OR) operation on each pair of corresponding bits of the operands. The result is 1 if the bits are different; otherwise, it's 0.

d. Bitwise NOT (~): 

It performs a bitwise negation operation, which flips all the bits of the operand. It converts 1s to 0s and 0s to 1s.

e. Left Shift (<<) and Right Shift (>>): 

These operators shift the bits of the left or right operand to the left or right by a specified number of positions. The vacated positions are filled with zeros for left shift, and for right shift, the vacant positions are filled based on the type of shift (logical or arithmetic).

Bitwise operators are particularly useful in low-level programming, such as device driver development, embedded systems programming, and optimization of code involving bit manipulation.

14. Differentiate between while loop and do while loop. Write a C program to find input number is prime or composite. [2+3]

Differentiation between while loop and do-while loop:

a. While Loop:

   - The while loop checks the condition before executing the loop body.
   - If the condition is false initially, the loop body will not execute at all.
   - Syntax:

     while (condition) {
         // statements
     }


b. Do-While Loop:

   - The do-while loop checks the condition after executing the loop body.
   - The loop body is executed at least once, irrespective of the condition.
   - Syntax:

     do {
         // statements
     } while (condition);


C program to find whether the input number is prime or composite:

#include <stdio.h>

int main() {
    int num, i, isPrime = 1; // Assume the number is prime initially

    // Input number from the user
    printf("Enter a positive integer: ");
    scanf("%d", &num);

    // Check for prime or composite
    if (num <= 1) {
        isPrime = 0; // Numbers less than or equal to 1 are not prime
    } else {
        for (i = 2; i <= num / 2; ++i) {
            if (num % i == 0) {
                isPrime = 0; // If number is divisible by any other number, it's composite
                break;
            }
        }
    }

    // Output the result
    if (isPrime) {
        printf("%d is a prime number.\n", num);
    } else {
        printf("%d is a composite number.\n", num);
    }

    return 0;
}


Explanation:
- The program takes a positive integer input from the user.
- It checks whether the input number is less than or equal to 1. If so, it's not prime.
- Otherwise, it iterates from 2 to half of the input number.
- If the input number is divisible by any number within this range, it's marked as composite.
- Finally, the program prints whether the input number is prime or composite.

15. What is DMA? Write a program to find the largest and smallest number in a list of N number using DMA. [1+4]

DMA (Dynamic Memory Allocation):

DMA, short for Dynamic Memory Allocation, is a mechanism provided by programming languages like C and C++ to allocate memory dynamically during program execution. It allows the program to request memory from the system at runtime rather than at compile time.

Program to find the largest and smallest number in a list of N numbers using DMA:


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

int main() {
    int arr, n, i;
    int largest, smallest;

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

    // Dynamically allocate memory for the array
    arr = (int )malloc(n sizeof(int));
    
    // Check if memory allocation was successful
    if (arr == NULL) {
        printf("Memory allocation failed.\n");
        return 1; // Exit with error code 1
    }

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

    // Assume first element as both largest and smallest initially
    largest = smallest = arr[0];

    // Find the largest and smallest numbers in the list
    for (i = 1; i < n; i++) {
        if (arr[i] > largest) {
            largest = arr[i];
        }
        if (arr[i] < smallest) {
            smallest = arr[i];
        }
    }

    // Output the largest and smallest numbers
    printf("Largest number: %d\n", largest);
    printf("Smallest number: %d\n", smallest);

    // Free the dynamically allocated memory
    free(arr);

    return 0;
}

Explanation:
- The program dynamically allocates memory for an array of N integers.
- It then takes N integers as input from the user and stores them in the dynamically allocated array.
- It initializes variables `largest` and `smallest` with the first element of the array.
- Then, it iterates through the array to find the largest and smallest numbers.
- Finally, it prints the largest and smallest numbers.
- After the use of dynamically allocated memory, it deallocates the memory using `free()` to prevent memory leaks.

16. What is difference between binary file and text file? Write a C program to write some text "Welcome to BCA program" in a file test.text. [2+3]

Difference between Binary File and Text File:

a. Binary File:
   - Binary files contain data in a format that is directly interpretable by the computer. 
   - Data in binary files is stored in a binary format, which means it's not human-readable.
   - These files may contain any type of data, including images, audio, video, executable programs, etc.
   - Binary files are typically smaller in size compared to text files since they do not store extra formatting characters.
   - Reading and writing binary files require special handling to ensure data integrity.
   - Examples include executable files (.exe), image files (.jpg, .png), audio files (.mp3, .wav), etc.

b. Text File:
   - Text files contain data that is human-readable and composed of characters, typically encoded using ASCII or Unicode.
   - Data in text files is stored as a sequence of characters, including letters, digits, symbols, and whitespace.
   - These files are used for storing textual information such as program source code, configuration files, plain text documents, etc.
   - Text files may contain additional formatting characters like newline characters (\n), tab characters (\t), etc., to structure the data.
   - Reading and writing text files is straightforward and can be done using standard text editors or programming languages.
   - Examples include source code files (.c, .cpp, .java), document files (.txt, .docx), configuration files (.ini, .xml), etc.

C program to write some text "Welcome to BCA program" in a file test.txt:

#include <stdio.h>

int main() {
    FILE fp; // File pointer

    // Open the file in write mode ("w")
    fp = fopen("test.txt", "w");

    // Check if file opened successfully
    if (fp == NULL) {
        printf("Error opening file.\n");
        return 1; // Exit with error code 1
    }

    // Write text to the file
    fprintf(fp, "Welcome to BCA program");

    // Close the file
    fclose(fp);

    printf("Text written to file successfully.\n");

    return 0;
}

Explanation:
- The program uses the `fopen()` function to open a file named "test.txt" in write mode ("w").
- If the file opening operation fails, it prints an error message and exits.
- It then uses the `fprintf()` function to write the text "Welcome to BCA program" to the file.
- Finally, it closes the file using the `fclose()` function.
- Upon successful execution, it prints a message indicating that the text has been written to the file.

17. Explain any four graphics functions in C. Write a program to draw two concentric circles with center (50, 50) and radii 75 and 125. [2+3]

Explanation of Four Graphics Functions in C:

a. initgraph(): This function initializes the graphics system on the computer and opens a graphics window where graphical operations can be performed. It usually requires parameters like graphics driver and graphics mode to set up the environment for graphics.

b. circle(): The `circle()` function is used to draw a circle on the screen. It takes parameters specifying the coordinates of the center of the circle and its radius. This function is commonly used in graphics programming for creating circular shapes.

c. setcolor(): This function sets the current drawing color in graphics. It allows you to specify the color of the graphics primitives such as lines, circles, rectangles, etc. Colors are typically represented using integer codes or predefined color constants.

d. closegraph(): After completing the graphics operations, the `closegraph()` function is called to close the graphics window and release any resources associated with the graphics environment. It's important to call this function to properly terminate the graphics session.

C program to draw two concentric circles with center (50, 50) and radii 75 and 125:

#include <graphics.h>

int main() {
    int gd = DETECT, gm; // Graphics driver and mode
    int x = 50, y = 50; // Coordinates of the center of circles
    int radius1 = 75, radius2 = 125; // Radii of circles

    // Initialize the graphics system
    initgraph(&gd, &gm, NULL);

    // Set color to blue for the outer circle
    setcolor(BLUE);
    // Draw outer circle
    circle(x, y, radius2);

    // Set color to red for the inner circle
    setcolor(RED);
    // Draw inner circle
    circle(x, y, radius1);

    // Close the graphics system
    closegraph();

    return 0;
}

Explanation:
- The program initializes the graphics system using `initgraph()` function, which detects the graphics driver and mode automatically.
- It sets the center coordinates of the circles and their radii.
- Then, it sets the color of the outer circle to blue using `setcolor()` function and draws the outer circle using `circle()` function.
- Next, it sets the color of the inner circle to red and draws the inner circle.
- Finally, it closes the graphics system using `closegraph()` function to release resources.

Group-C: Attempt any two questions. [2x10=20]


18. What is one dimensional array? How it is initialized? Write a C program to find the sum of two matrix of order mxn. [1+1+8]

One-Dimensional Array:

A one-dimensional array is a linear collection of elements of the same data type that are stored sequentially in memory. It is a fundamental data structure that allows storing multiple values of the same type under a single name. Elements in a one-dimensional array are accessed using an index, which represents the position of an element within the array.

Initialization: 
One-dimensional arrays can be initialized either statically or dynamically.
- Static Initialization: In static initialization, the size of the array and its elements are specified at compile time. For example:

  int arr[5] = {1, 2, 3, 4, 5};

- Dynamic Initialization: In dynamic initialization, memory is allocated for the array at runtime using functions like `malloc()` or `calloc()`. For example:

  int arr;
  arr = (int )malloc(5 sizeof(int));

  
C program to find the sum of two matrices of order mxn:


#include <stdio.h>

#define MAX_SIZE 10 // Maximum size of matrices

int main() {
    int matrix1[MAX_SIZE][MAX_SIZE], matrix2[MAX_SIZE][MAX_SIZE], sum[MAX_SIZE][MAX_SIZE];
    int m, n, i, j;

    // Input the order of matrices
    printf("Enter the number of rows (m) and columns (n) of the matrices: ");
    scanf("%d %d", &m, &n);

    // Input elements of the first matrix
    printf("Enter the elements of the first matrix:\n");
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            printf("Enter element (%d, %d): ", i + 1, j + 1);
            scanf("%d", &matrix1[i][j]);
        }
    }

    // Input elements of the second matrix
    printf("Enter the elements of the second matrix:\n");
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            printf("Enter element (%d, %d): ", i + 1, j + 1);
            scanf("%d", &matrix2[i][j]);
        }
    }

    // Calculate the sum of matrices
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            sum[i][j] = matrix1[i][j] + matrix2[i][j];
        }
    }

    // Display the sum of matrices
    printf("Sum of the two matrices:\n");
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            printf("%d\t", sum[i][j]);
        }
        printf("\n");
    }

    return 0;
}


Explanation:
- The program defines arrays `matrix1`, `matrix2`, and `sum` to store the elements of two input matrices and their sum, respectively.
- It takes the order of the matrices (number of rows and columns) as input from the user.
- It then takes input elements of both matrices using nested loops.
- After inputting the matrices, it calculates the sum of corresponding elements from both matrices and stores the result in the `sum` array.
- Finally, it displays the sum of matrices.

19. Define structure and union? Write a C program using structure that reads the records of 35 students with members roll, name, address and makes and display the record of students who have obtained greater than 250 marks. [2+8]

Definition of Structure and Union:

a. Structure:
   - Structure is a user-defined data type in C that allows grouping together multiple variables of different data types under a single name.
   - Each variable within a structure is referred to as a member or field.
   - Structures provide a way to represent complex data in a hierarchical manner.
   - The members of a structure can be accessed using dot (.) operator.

b. Union:
   - Union is similar to a structure in that it can hold variables of different data types under a single name.
   - However, unlike structures, in a union, only one member can hold a value at a time.
   - Unions are useful when memory efficiency is a concern, as they share the same memory location for all their members.
   - The size of a union is determined by the size of its largest member.

C program using structure to read records of 35 students and display those who obtained greater than 250 marks:


#include <stdio.h>

#define MAX_STUDENTS 35
#define MAX_NAME_LENGTH 50
#define MAX_ADDRESS_LENGTH 100

// Define structure for student record
struct Student {
    int roll;
    char name[MAX_NAME_LENGTH];
    char address[MAX_ADDRESS_LENGTH];
    int marks;
};

int main() {
    struct Student students[MAX_STUDENTS];
    int i, numStudents;

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

    // Input student records
    for (i = 0; i < numStudents; i++) {
        printf("\nEnter details for student %d:\n", i + 1);
        printf("Roll: ");
        scanf("%d", &students[i].roll);
        printf("Name: ");
        scanf("%s", students[i].name);
        printf("Address: ");
        scanf("%s", students[i].address);
        printf("Marks: ");
        scanf("%d", &students[i].marks);
    }

    // Display records of students with marks greater than 250
    printf("\nRecords of students with marks greater than 250:\n");
    printf("Roll\tName\t\tAddress\t\tMarks\n");
    for (i = 0; i < numStudents; i++) {
        if (students[i].marks > 250) {
            printf("%d\t%s\t\t%s\t\t%d\n", students[i].roll, students[i].name, students[i].address, students[i].marks);
        }
    }

    return 0;
}

Explanation:
- The program defines a structure named `Student` to store the details of each student, including roll number, name, address, and marks.
- It declares an array of `Student` structures to hold the records of students.
- The user is prompted to input the number of students, and then the details of each student are entered using a loop.
- After inputting the records, the program displays the records of students who obtained marks greater than 250.

20. What is function? List its advantages. Explain the concept of function call by value and function call by reference with example. [1+2+7]

Function:

A function is a self-contained block of code that performs a specific task or operation. It consists of a sequence of statements that are grouped together to perform a particular action. Functions provide modularity and reusability to programs by allowing the code to be organized into smaller, manageable units.

Advantages of Using Functions:

1. Modularity: Functions allow breaking down complex tasks into smaller, more manageable units, making the code easier to understand, debug, and maintain.
2. Code Reusability: Functions can be reused multiple times in a program or across different programs, reducing code duplication and promoting efficiency.
3. Abstraction: Functions provide an abstraction layer by hiding the implementation details from the caller, thus facilitating a clear separation of concerns.
4. Ease of Debugging: With functions, errors can be isolated to specific parts of the code, making it easier to identify and fix issues.
5. Ease of Testing: Functions can be tested independently, which simplifies the testing process and improves the overall reliability of the code.

Function Call by Value and Function Call by Reference:

b. Function Call by Value:
   - In function call by value, the actual value of the arguments is passed to the function parameters.
   - Any changes made to the function parameters inside the function do not affect the original values of the arguments.
   - It is the default method of passing arguments to a function in C.
   - Simple data types like int, float, char, etc., are passed by value.

Example of Function Call by Value:

#include <stdio.h>

// Function to swap two integers using call by value
void swap(int x, int y) {
    int temp;
    temp = x;
    x = y;
    y = temp;
}

int main() {
    int a = 10, b = 20;
    
    printf("Before swap: a = %d, b = %d\n", a, b);
    
    swap(a, b); // Call by value
    
    printf("After swap: a = %d, b = %d\n", a, b);
    
    return 0;
}

Output:

Before swap: a = 10, b = 20
After swap: a = 10, b = 20

In this example, even though the `swap` function swaps the values of `x` and `y`, the original values of `a` and `b` remain unchanged because they are passed by value.

c. Function Call by Reference:
   - In function call by reference, the memory address (reference) of the actual arguments is passed to the function parameters.
   - Any changes made to the function parameters inside the function directly affect the original values of the arguments.
   - To achieve call by reference in C, pointers are used as function parameters.

Example of Function Call by Reference:

#include <stdio.h>

// Function to swap two integers using call by reference
void swap(int x, int y) {
    int temp;
    temp = x;
    x = y;
    y = temp;
}

int main() {
    int a = 10, b = 20;
    
    printf("Before swap: a = %d, b = %d\n", a, b);
    
    swap(&a, &b); // Call by reference
    
    printf("After swap: a = %d, b = %d\n", a, b);
    
    return 0;
}

Output:

Before swap: a = 10, b = 20
After swap: a = 20, b = 10

In this example, the `swap` function swaps the values of a and b by dereferencing the pointers passed as arguments, resulting in a successful swap of values.

BCA C Programming Question Paper Solution 2019 - 2nd Semester

Bachelor in Computer Applications  

Course Title: English II  

Code No: CACS151

Semester: II  

Full Marks: 60  

Pass Marks: 24  

Time: 3 hours  


Candidates are required to answer the questions in their own words as far as possible. Attempt all the questions.

Group B: Attempt any SIX questions. [6x5 = 30]  


2. What is computer programming? Differentiate between the top-down and bottom-up approach to programming.

Answer:

   Computer programming refers to the process of writing instructions for a computer to execute. It involves designing, writing, testing, debugging, and maintaining the source code of computer programs. Programming languages such as Java, C, C++, Python, PHP, Perl, and Ruby are used for this purpose.


 Top-Down Approach: - Divides a problem into smaller units and solves it. - Redundancy exists due to the division of the problem. - Communication among steps is not mandatory. - Structured programming languages like C use it. - Relation among modules is not always required. - Primarily used in implementation, test case generation, debugging, and module documentation. Bottom-Up Approach: - Starts from solving small modules and adds them together. - Redundancy is eliminated by thoroughly analyzing individual modules. - Communication among modules is mandatory. - Object-oriented programming (OOP) languages like C++ and Java use it. - Modules must be related for better communication and workflow. - Primarily used in testing.


3. What is the purpose of the sizeof operator? Write a C program to swap the values of two integers without using a third variable.


   Answer:

   The sizeof operator in C is used to determine the size of a variable or data type in bytes. It returns the amount of memory allocated to the specified data type or variable. 



   #include <stdio.h>

   

   int main() {

       int a = 10, b = 20;

       

       printf("Size of int: %lu\n", sizeof(int));

       printf("Size of float: %lu\n", sizeof(float));

       printf("Size of char: %lu\n", sizeof(char));

       printf("Size of double: %lu\n", sizeof(double));

       

       return 0;

   }



   Program to swap values of two integers without using a third variable:



   #include <stdio.h>

   

   int main() {

       int a = 10, b = 20;

       

       printf("Before swap: a=%d, b=%d\n", a, b);

       

       a = a + b;

       b = a - b;

       a = a - b;

       

       printf("After swap: a=%d, b=%d\n", a, b);

       

       return 0;

   }

   ```


4. Write a program in C to find all possible roots of the quadratic equation ax^2 + bx + c = 0.


   Answer:


   #include <stdio.h>

   #include <math.h>

   

   int main() {

       double a, b, c, discriminant, root1, root2, realPart, imagPart;

       

       printf("Enter coefficients a, b, and c: ");

       scanf("%lf %lf %lf", &a, &b, &c);

       

       discriminant = b  b - 4  a  c;

       

       if (discriminant > 0) {

           root1 = (-b + sqrt(discriminant)) / (2  a);

           root2 = (-b - sqrt(discriminant)) / (2  a);

           printf("Root 1 = %.2lf and Root 2 = %.2lf\n", root1, root2);

       } else if (discriminant == 0) {

           root1 = root2 = -b / (2  a);

           printf("Root 1 = Root 2 = %.2lf\n", root1);

       } else {

           realPart = -b / (2  a);

           imagPart = sqrt(-discriminant) / (2  a);

           printf("Root 1 = %.2lf + %.2lfi and Root 2 = %.2f - %.2fi\n", realPart, imagPart, realPart, imagPart);

       }

       

       return 0;

   }



5. Why is an array required in programming? Write a C program to input the age of 30 employees into an array and find out the second largest age from the array.


   Answer:

   Arrays are required in programming to store and manipulate multiple values of the same data type under a single name. They provide a convenient way to store large amounts of data and access them using indexing.


   Program to input the age of 30 employees into an array and find out the second largest age:



   #include <stdio.h>

   

   int main() {

       int ages[30], i, first, second;

       

       printf("Enter the ages of 30 employees:\n");

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

           scanf("%d", &ages[i]);

       }

       

       first = second = INT_MIN;

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

           if (ages[i] > first) {

               second = first;

               first = ages[i];

           } else if (ages[i] > second && ages[i] < first) {

               second = ages[i];

           }

       }

       

       printf("The second largest age is: %d\n", second);

       

       return 0;

   }



6. What is a recursive function? Write a C program to generate the Fibonacci series up to the 13th term using a recursive function.


   Answer:

   A recursive function is a function that calls itself directly or indirectly in order to solve a problem. It breaks down the problem into smaller sub-problems and calls itself to solve each sub-problem.


   Program to generate the Fibonacci series up to the 13th term using recursion:



   #include <stdio.h>

   

   int fibonacci(int n) {

       if (n <= 1) {

           return n;

       }

       return fibonacci(n - 1) + fibonacci(n - 2);

   }

   

   int main() {

       int i;

       printf("Fibonacci series up to 13th term:\n");

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

           printf("%d ", fibonacci(i));

       }

       printf("\n");

       return 0;

   }

   ```


7. What is the advantage of a pointer? Write a C program to store 10 integers into memory and find out the minimum and maximum using dynamic memory allocation (DMA).


   Answer:

   Pointers in C provide several advantages, including:

   - Efficient memory usage

   - Ability to work with dynamic memory allocation

   - Accessing array elements more efficiently

   - Facilitating dynamic data structures like linked lists, trees, and graphs


   Program to store 10 integers into memory and find out the minimum and maximum using dynamic memory allocation:



   #include <stdio.h>

   #include <stdlib.h>

   

   int main() {

       int arr, i, min


, max;

       

       arr = (int)malloc(10  sizeof(int));

       

       printf("Enter 10 integers:\n");

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

           scanf("%d", &arr[i]);

       }

       

       min = max = arr[0];

       for (i = 1; i < 10; i++) {

           if (arr[i] < min) {

               min = arr[i];

           }

           if (arr[i] > max) {

               max = arr[i];

           }

       }

       

       printf("Minimum number: %d\n", min);

       printf("Maximum number: %d\n", max);

       

       free(arr);

       return 0;

   }

   ```


8. What is the use of initgraph() in a C program? Write a program to draw a line, circle, and rectangle using graphic functions.


   Answer:

   The initgraph() function in C is used to initialize the graphics system by loading the appropriate graphics driver and setting the system to graphics mode. It also resets or initializes all graphics settings such as color, palette, and current position to their default values.


   Program to draw a line, circle, and rectangle using graphic functions:



   #include <graphics.h>

   #include <stdio.h>

   

   int main() {

       int gd = DETECT, gm;

       

       initgraph(&gd, &gm, "");

       

       // Draw a line

       line(100, 100, 300, 100);

       

       // Draw a circle

       circle(200, 200, 50);

       

       // Draw a rectangle

       rectangle(50, 50, 150, 150);

       

       getch();

       closegraph();

       return 0;

   }



Group C : Attempt any two questions. [10*2=20]


9. What is a structure? Write a C program to enter the id, name, and address of 25 employees into a structure variable called 'employee' and sort them in alphabetical order of their names.


   Answer:

A structure in C is a user-defined data type that allows storing a group of related data items under a single name. Each data item within a structure is called a member.


   Program to enter the id, name, and address of 25 employees into a structure variable and sort them alphabetically by name:



   #include <stdio.h>

   #include <stdlib.h>

   #include <string.h>

   

   struct Employee {

       int id;

       char name[50];

       char address[100];

   };

   

   int main() {

       int i, j, n = 25;

       struct Employee employees[n], temp;

       

       printf("Enter details of 25 employees:\n");

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

           printf("Employee %d:\n", i + 1);

           printf("Enter id: ");

           scanf("%d", &employees[i].id);

           printf("Enter name: ");

           scanf("%s", employees[i].name);

           printf("Enter address: ");

           scanf("%s", employees[i].address);

       }

       

       // Sorting employees alphabetically by name

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

           for (j = 0; j < n - i - 1; j++) {

               if (strcmp(employees[j].name, employees[j + 1].name) > 0) {

                   temp = employees[j];

                   employees[j] = employees[j + 1];

                   employees[j + 1] = temp;

               }

           }

       }

       

       printf("\nSorted list of employees by name:\n");

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

           printf("Id: %d, Name: %s, Address: %s\n", employees[i].id, employees[i].name, employees[i].address);

       }

       

       return 0;

   }



10. Is the 'break' keyword mandatory in a switch statement? Write a program to perform basic arithmetic operations (+, -, , /) using a switch-case statement.


    Answer:

    Yes, the 'break' keyword is mandatory in a switch statement to terminate the execution of a particular case and prevent fall-through to the next case.


    Program to perform basic arithmetic operations using a switch-case statement:


    #include <stdio.h>

    

    int main() {

        int a, b;

        char op;

        

        printf("Enter two numbers: ");

        scanf("%d %d", &a, &b);

        printf("Enter the operation (+, -, , /): ");

        scanf(" %c", &op);

        

        switch(op) {

            case '+':

                printf("Sum: %d\n", a + b);

                break;

            case '-':

                printf("Difference: %d\n", a - b);

                break;

            case '':

                printf("Product: %d\n", a  b);

                break;

            case '/':

                if (b != 0) {

                    printf("Quotient: %d\n", a / b);

                } else {

                    printf("Division by zero error!\n");

                }

                break;

            default:

                printf("Invalid operation!\n");

                break;

        }

        

        return 0;

    }



11. What do you mean by the Software Development Life Cycle (SDLC)? Explain the waterfall model with its advantages and disadvantages.


    Answer:

    The Software Development Life Cycle (SDLC) is a framework that outlines the processes involved in the development of software from inception to retirement. It consists of a set of phases, each with its own specific goals and deliverables. The typical phases include Planning, Requirements, Design, Implementation, Testing, Deployment, and Maintenance.


    Waterfall Model:

    The waterfall model is a linear sequential approach to software development in which progress flows downwards through several phases, similar to a waterfall cascading down. Each phase must be completed before the next phase begins.


    Advantages of the Waterfall Model:

    - Simple and easy to understand and use.

    - Well-defined deliverables and milestones make it easy to measure progress.

    - Provides a structured approach to development, making it easier to manage.


    Disadvantages of the Waterfall Model:

    - Lack of flexibility: Changes in requirements are difficult and costly to implement once a phase is completed.

    - High risk: It assumes that all requirements can be defined upfront, which may not be practical.

    - No working software until late in the project: Stakeholders may not see any tangible results until the end of the project, leading to potential misunderstandings and dissatisfaction.


    SDLC provides a structured approach to software development, ensuring that projects are completed efficiently, on time, and within budget. However, it's essential to select the appropriate model based on project requirements and constraints.


BCA C Programming Question Paper Solution 2020 - 2nd Semester

Bachelor in Computer Applications  

Course Title: C Programming

Code No: CACS151 

Semester: II  

Full Marks: 60  

Pass Marks: 24  

Time: 3 hours  


Candidates are required to answer the questions in their own words as far as possible. Attempt all the questions.


Group A: 1. Circle (O) the correct answer.  [10x1 = 10] 

i. Which compilation unit is responsible for adding header files content in the source code?


a) Linker  

b) Compiler  

c) Assembler  

d) Preprocessor  


ii. What is the meaning of the following line of code? void sum (int, int);


a) Sum is a function which takes int arguments  

b) Sum is a function which takes two int arguments and returns void  

c) It will produce a compilation error  

d) It will produce a runtime error  


iii. Which header file is essential for using strcmp() function?


a) stdlib.h  

b) string.h  

c) text.h  

d) strcmp.h  


iv. Which of the following is not a branching statement in C?


a) if  

b) else  

c) return  

d) continue  


v. Array can be considered as set of elements stored in consecutive memory locations but having


a) Same size  

b) Different data type  

c) Same scope  

d) None of the above  


vi. If int a=5, b=8, then what will be the value of int c = b++ - a--?


a) 3  

b) 5  

c) 2  

d) Can't comment  


vii. Suppose you are given a piece of code: circle(100,100,50); in C, then what is meant by 50?


a) Center  

b) Diameter  

c) Perimeter  

d) Radius  


viii. Suppose that the code:


struct student

{

    char name[20];

    int age;

    char address[25];

} std;



Then, what is the size of std?


a) 47 bytes  

b) 49 bytes  

c) 25 bytes  

d) 20 bytes  


ix. Suppose you are given a piece of code:


int a = 5, b;

b = &a;

printf("%u",b);



Then, what will be the output?


a) 5  

b) Address of b

c) Address of a  

d) Garbage value  


x. Which of the following is not a valid file opening mode?


a) read  

b) write  

c) execute  

d) append  


Group B : Attempt any SIX questions.[6×5=30]  

 


2. What are keywords? Explain the compiling process of C program. [1+4]


Answer:


Keywords:

These are the reserved words having predefined meanings in C. We cannot use keywords as programmer-defined identifiers. These keywords can be used only for their intended purpose. All keywords have fixed meaning and these meanings cannot be changed. Keywords serve as building blocks for program statements. All keywords must be written in lowercase. In standard C language, defined by ANSI, there are 32 keywords.


E.g. int, float, char, for, while etc. 


Compiling process of C program


The compilation is a process of converting the source code into object code. It is done with the help of the compiler. The compiler checks the source code for the syntactical or structural errors, and if the source code is error-free, then it generates the object code. The compilation process can be divided into four steps, i.e., Pre-processing, Compiling,

Assembling, and Linking.


Source code

1. Preprocessor: The source code is passed to the preprocessor, which expands the code by processing directives like #include, #define, etc.

2. Compiler: The preprocessed code is then passed to the compiler, which converts it into assembly code.

3. Assembler: The assembly code is converted into object code by the assembler.

4. Linker: Finally, the linker combines the object code with other necessary object files and libraries to generate the executable code.


3. Differentiate between iteration and recursion


Answer:

 Here are the differentiations between iteration and recursion presented in bullet points:


Iteration:

1. Iteration involves executing a set of instructions repeatedly in a loop until a certain condition is met or a specified number of iterations is reached.

2. It utilizes loop control mechanisms such as for loops, while loops, or do-while loops to repeat the instructions.

3. Typically consumes less memory as it does not involve function calls that create additional overhead on the stack.

4. Generally easier to understand and implement for simple repetitive tasks.

5. Examples of iterative constructs include for loops, while loops, and do-while loops in programming languages like C, Java, and Python.


Recursion:

1. Recursion is a process where a function calls itself, directly or indirectly, to solve a problem.

2. It breaks down the original problem into smaller subproblems with each recursive call until a base case is reached.

3. May use more memory because each recursive call creates a new activation record on the stack, potentially leading to stack overflow.

4. Well-suited for solving problems that can be broken down into smaller identical subproblems, such as factorial calculation or Fibonacci series generation.

5. Examples of recursive functions include calculating factorial, generating Fibonacci series, traversing tree structures, and solving problems like the Tower of Hanoi.



4. Define an array. Write a program to generate the following output using a loop. [1+4]


Answer:

An array is a data structure that contains a group of elements. Typically these elements are all of the same data type, such as an integer or string. Arrays are commonly used in computer programs to organize data so that a related set of values can be easily sorted or searched.


Program to generate the following output:


#include <stdio.h>

int main()

{

    int i, j, rows;

    printf("Enter the number of rows: ");

    scanf("%d", &rows);

    for (i=1; i<= rows; ++i)

    {

        for (j = 1; j <= i; ++j)

        {

            printf("%d ", j);

        }

        printf("\n");

    }

    return 0;

}



5. Define an operator. Explain any four types of operators available in C? [1+4]


Answer:


Operator:

Operators can be defined as basic symbols that help us work on logical and mathematical operations. Operators in C are tools or symbols that are used to perform mathematical operations concerning arithmetic, logical, conditional and bitwise operations. Arithmetic, Relational, Logical, Assignment, and Unary are the main types of operators available in C.


Arithmetic Operators:

All the basic arithmetic operations can be carried out in C. Unary operations operate on a single operand. Examples: + ,-, /, %, ++, --.


Relational Operators:

These operators compare the relationship between operands and return either true or false. Examples: ==, !=, >, <, >=, <=.


Logical Operators:

These operators are used to perform logical operations. Examples: && (logical AND), || (logical OR), ! (logical NOT).


Assignment Operators:

These operators are used to assign values to variables. Examples: =, +=, -=, =, /=, %=.


Unary Operators:

These operators operate on a single operand. Examples: ++, --, +, -, !.


6. Why is a function required in C programming? Write a program to find the smallest number from the array using a function. [1+4]


Answer:

Functions are required in C programming for several reasons:

- To improve the readability of code.

- To improve code reusability, as the same function can be used in different programs.

- To simplify debugging, as errors are easier to trace in modularized code.

- To reduce code redundancy and thus, the overall size of the code.


Program to find the smallest number from the array using a function:


#include<stdio.h>


void smallest(int a[], int n); // function prototype


int main()

{

    int a[100], i, n;

    printf("Enter the number of elements: ");

    scanf("%d", &n);

    printf("Enter %d elements:\n", n);

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

    {

        scanf("%d", &a[i]);

    }

    smallest(a, n); // function calling

    return 0;

}


void smallest(int a[], int n)

{

    int min = a[0];

    for (int i=1; i<n; ++i)

    {

        if (a[i] < min)

        {

            min = a[i];

        }

    }

    printf("Smallest Element: %d\n", min);

}


7. Why is DMA used in C language? Write a program to enter the age of 20 students and count ages between 18 and 25 from the array using DMA function. [1+4]


Answer:

DMA (Dynamic Memory Allocation) is used in C language to allocate memory during runtime. It allows the programmer to dynamically allocate memory as per the requirement during program execution. DMA functions are helpful when the size of data is not known at compile time or when memory needs to be allocated or deallocated based on certain conditions.


Program to enter the age of 20 students and count ages between 18 and 25 using DMA function:


#include<stdio.h>

#include<stdlib.h>


int main()

{

    int age;

    int i, count = 0;


    // Allocate memory for 20 elements dynamically

    age = (int)malloc(20  sizeof(int));


    printf("Enter ages of 20 students:\n");

    for(i = 0; i < 20; i++)

    {

        scanf("%d", &age[i]);

    }


    // Count ages between 18 and 25

    for(i = 0; i < 20; i++)

    {

        if(age[i] >= 18 && age[i] <= 25)

        {

            count++;

        }

    }


    printf("Number of Ages between 18 to 25: %d\n", count);


    // Free dynamically allocated memory

    free(age);


    return 0;

}


8. Write a C program to generate the following output using graphics functions. [5]


Answer:


#include <graphics.h>

#include <stdio.h>


int main(void)

{

    int gdriver = DETECT, gmode;

    int x = 200, y = 200;

    

    // Initialize graphics mode

    initgraph(&gdriver, &gmode, "c:\\tc\\bgi");


    // Display text

    outtextxy(x, y, "BCA Program");


    // Close graphics mode

    closegraph();


    return 0;

}


Group C : Attempt any two questions [2×10=20]


9. What is a union? Write a C program to enter the bid, title, price, pages of 100 books into a structure variable called book and sort them in descending order based on their title using pointers. [2+8]


Answer:

Union:

A union is a data type in C programming that allows different data types to be stored in the same memory locations. Union provides an efficient way of using memory, as only one of its members can be accessed at a time.


#include <stdio.h>

#include <stdlib.h>

#include <string.h>


struct Book

{

    char


 title[100];

    int bid;

    float price;

    int pages;

};


int main()

{

    int i, n = 2, j;

    struct Book b[n];

    char temp[100];


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

    {

        printf("Enter details of Book %d:\n", i+1);

        printf("Enter the title: ");

        scanf("%s", b[i].title);

        printf("Enter the book id: ");

        scanf("%d", &b[i].bid);

        printf("Enter the price of the book: ");

        scanf("%f", &b[i].price);

        printf("Enter the number of pages: ");

        scanf("%d", &b[i].pages);

    }


    // Sort the books based on title

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

    {

        for(j = 0; j < n - i - 1; j++)

        {

            if(strcmp(b[j].title, b[j + 1].title) < 0)

            {

                strcpy(temp, b[j].title);

                strcpy(b[j].title, b[j + 1].title);

                strcpy(b[j + 1].title, temp);

            }

        }

    }


    // Print the sorted books

    printf("\nBooks sorted by title in descending order:\n");

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

    {

        printf("Title: %s, Book ID: %d, Price: %.2f, Pages: %d\n", b[i].title, b[i].bid, b[i].price, b[i].pages);

    }


    return 0;

}


10. What is the use of a data file in C? Write a C program to accept 100 numbers from the user and store them in odd.txt file (if the number is odd) or even.txt file (if the number is even), then display odd numbers reading from odd.txt file. [1+9]


Answer:


A data file in C is used to store information permanently on an auxiliary storage device. It allows us to store data so that it can be accessed later and modified whenever necessary. Data files are essential for preserving data even after the program terminates, transferring data between different computers, and storing a large number of data efficiently.


#include<stdio.h>


int main()

{

    FILE all, even, odd;

    int number, i, records;


    // Open a file for writing

    all = fopen("ANYNUMBER.txt", "w");

    printf("INPUT THE TOTAL NUMBER OF RECORDS THAT YOU WANT TO ENTER: ");

    scanf("%d", &records);

    

    // Write numbers to the file

    printf("Enter %d numbers:\n", records);

    for(i = 1; i <= records; i++)

    {

        scanf("%d", &number);

        fprintf(all, "%d ", number);

    }

    fclose(all);


    // Open files for reading

    all = fopen("ANYNUMBER.txt", "r");

    even = fopen("even.txt", "w");

    odd = fopen("odd.txt", "w");


    // Read numbers from the file and write to even.txt or odd.txt accordingly

    while(fscanf(all, "%d", &number) != EOF)

    {

        if(number % 2 == 0)

        {

            fprintf(even, "%d ", number);

        }

        else

        {

            fprintf(odd, "%d ", number);

        }

    }

    fclose(all);

    fclose(even);

    fclose(odd);


    // Display odd numbers from odd.txt

    printf("Odd numbers:\n");

    odd = fopen("odd.txt", "r");

    while(fscanf(odd, "%d", &number) != EOF)

    {

        printf("%d ", number);

    }

    fclose(odd);


    return 0;

}


11. What do you mean by System Design Tools? Explain any four system design tools with suitable examples.


Answer:

System design tools are techniques or methodologies used in system development to define the architecture, components, modules, interfaces, and data of a system to meet specified requirements. These tools help in designing the blueprint of a system before actual construction begins. Some common system design tools are:


a. Context Diagram: A context diagram is a visual representation that shows the interaction between a system and its environment. It illustrates the scope and boundaries of the system and its interactions with external entities. Example: A context diagram for an online shopping system showing interactions with customers, payment gateways, and inventory systems.


b. Data Flow Diagram (DFD): A DFD is a graphical representation of the flow of data through a system. It shows how data is input, processed, and output within the system. DFDs are used to model the functional aspects of a system and identify the processes, data stores, and data flows. Example: A DFD for a banking system showing the flow of customer transactions, account balances, and ATM withdrawals.


c. Entity-Relationship Diagram (E-R Diagram): An E-R diagram is a visual representation of the entities, attributes, and relationships within a database. It shows how data is organized and related to each other in a database system. E-R diagrams are used to design relational databases and understand the structure of the data. Example: An E-R diagram for a university database showing entities like students, courses, and instructors, and their relationships.


d. Algorithm: An algorithm is a step-by-step procedure or set of rules for solving a problem or performing a task. It describes the logic or flow of control in a program without specifying the syntax of a particular programming language. Algorithms are used to design efficient and correct solutions to problems in various domains. Example: An algorithm for sorting an array of numbers using the bubble sort technique.


These system design tools help in analyzing, designing, and implementing complex systems by providing a structured approach to problem-solving and decision-making. They enable system designers to understand the requirements, constraints, and interactions of a system and develop solutions that meet the desired objectives.


Post a Comment

0 Comments