This Blog is protected by DMCA.com

MCS-011,June, 2022, QUESTION AND ANSWER

 1. (a) Draw a flowchart and write an algorithm to calculate the factorial of a given number.






(b) Write a program to display string ‘INFINITY’ in the following pattern (using ‘‘LOOP’’ control statement) : 
I
I N
I N F
I N F I
I N F I N
I N F I N I
I N F I N I T
I N F I N I T Y



You can achieve this pattern using nested loops in C. Here's a program to display the string "INFINITY" in the specified pattern:

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

int main() {
    char str[] = "INFINITY";
    int len = strlen(str);
    int i, j;

    for (i = 0; i < len; i++) {
        for (j = 0; j <= i; j++) {
            printf("%c ", str[j]);
        }
        printf("\n");
    }

    return 0;
}


This program first calculates the length of the string "INFINITY". Then, it iterates through each character of the string, printing characters up to the current position in the inner loop and adding a newline after each inner loop iteration.


(c) Write a program to generate Fibonacci series using recursion.








(d) Write an interactive C program for each to
illustrate the following concepts : 
(i) Enumerated data type
(ii) Macros in C
(iii) Typedef
(iv) Goto statement





here are interactive C programs illustrating each of the concepts you mentioned:

(i) Enumerated data type:

#include <stdio.h>

enum Day {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY};

int main() {
    enum Day today;

    printf("Enter the day (0-6): ");
    scanf("%d", &today);

    switch (today) {
        case SUNDAY:
            printf("It's Sunday.\n");
            break;
        case MONDAY:
            printf("It's Monday.\n");
            break;
        case TUESDAY:
            printf("It's Tuesday.\n");
            break;
        case WEDNESDAY:
            printf("It's Wednesday.\n");
            break;
        case THURSDAY:
            printf("It's Thursday.\n");
            break;
        case FRIDAY:
            printf("It's Friday.\n");
            break;
        case SATURDAY:
            printf("It's Saturday.\n");
            break;
        default:
            printf("Invalid day.\n");
    }

    return 0;
}





(ii) Macros in C:

#include <stdio.h>

#define PI 3.14159
#define AREA(r) (PI * r * r)

int main() {
    float radius;

    printf("Enter the radius of the circle: ");
    scanf("%f", &radius);

    printf("Area of the circle: %.2f\n", AREA(radius));

    return 0;
}

#include <stdio.h>

typedef struct {
    int hours;
    int minutes;
    int seconds;
} Time;

int main() {
    Time t;

    printf("Enter hours, minutes, and seconds separated by spaces: ");
    scanf("%d %d %d", &t.hours, &t.minutes, &t.seconds);

    printf("Time entered: %02d:%02d:%02d\n", t.hours, t.minutes, t.seconds);

    return 0;
}


(iii) Typedef:

#include <stdio.h>

typedef struct {
    int hours;
    int minutes;
    int seconds;
} Time;

int main() {
    Time t;

    printf("Enter hours, minutes, and seconds separated by spaces: ");
    scanf("%d %d %d", &t.hours, &t.minutes, &t.seconds);

    printf("Time entered: %02d:%02d:%02d\n", t.hours, t.minutes, t.seconds);

    return 0;
}

(iv) Goto statement:

#include <stdio.h>

int main() {
    int num;

input:
    printf("Enter a positive number: ");
    scanf("%d", &num);

    if (num <= 0) {
        printf("Invalid input. Please enter a positive number.\n");
        goto input;
    }

    printf("You entered: %d\n", num);

    return 0;
}


These programs demonstrate the concepts of enumerated data types, macros, typedef, and the goto statement in C.


2. (a) Write an algorithm and draw the corresponding flowchart to calculate whether the given number is prime or not. 




(b) Write a C program to perform the following operation on matrices :
 D = (A*B) + C where A, B and C are matrices of (3 * 3)size and D is the resultant matrix.


Below is a C program that performs the operation D = (A*B) + C, where A, B, C are matrices of size 3x3, and D is the resultant matrix:


#include <stdio.h>

#define SIZE 3

void matrix_multiply(int A[][SIZE], int B[][SIZE], int result[][SIZE]) {
    int i, j, k;
    for (i = 0; i < SIZE; i++) {
        for (j = 0; j < SIZE; j++) {
            result[i][j] = 0;
            for (k = 0; k < SIZE; k++) {
                result[i][j] += A[i][k] * B[k][j];
            }
        }
    }
}

void matrix_add(int A[][SIZE], int B[][SIZE], int result[][SIZE]) {
    int i, j;
    for (i = 0; i < SIZE; i++) {
        for (j = 0; j < SIZE; j++) {
            result[i][j] = A[i][j] + B[i][j];
        }
    }
}

void print_matrix(int mat[][SIZE]) {
    int i, j;
    for (i = 0; i < SIZE; i++) {
        for (j = 0; j < SIZE; j++) {
            printf("%d ", mat[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int A[SIZE][SIZE] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int B[SIZE][SIZE] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
    int C[SIZE][SIZE] = {{1, 1, 1}, {1, 1, 1}, {1, 1, 1}};
    int D[SIZE][SIZE];

    matrix_multiply(A, B, D); // D = A * B
    matrix_add(D, C, D);      // D = D + C

    printf("Matrix A:\n");
    print_matrix(A);
    printf("\nMatrix B:\n");
    print_matrix(B);
    printf("\nMatrix C:\n");
    print_matrix(C);
    printf("\nResultant Matrix D:\n");
    print_matrix(D);

    return 0;
}


This program first multiplies matrices A and B to get a temporary result, then adds matrix C to this result to obtain the final matrix D. Finally, it prints all the matrices involved.



3. (a) Write a program to find the minimum marks among the given marks of 20 students. 


Certainly! Here's a simple C program to find the minimum marks among the given marks of 20 students:


#include <stdio.h>

int main() {
    int marks[20];
    int min_mark;
    
    // Input marks for 20 students
    printf("Enter marks of 20 students:\n");
    for(int i = 0; i < 20; i++) {
        printf("Enter marks of student %d: ", i + 1);
        scanf("%d", &marks[i]);
    }
    
    // Assume the first student's marks as minimum
    min_mark = marks[0];
    
    // Loop through the marks to find the minimum
    for(int i = 1; i < 20; i++) {
        if(marks[i] < min_mark) {
            min_mark = marks[i];
        }
    }
    
    // Display the minimum marks
    printf("Minimum marks among the given marks: %d\n", min_mark);
    
    return 0;
}


This program prompts the user to input the marks of 20 students one by one. Then, it iterates through the array of marks to find the minimum value. Finally, it prints out the minimum marks among the given marks.




(b) Write a program to find the string length without using strlen( ) function.


Certainly! Here's a simple C program to find the length of a string without using the strlen() function:

#include <stdio.h>

// Function to find length of string
int stringLength(char *str) {
    int length = 0;
    // Iterate through the string until '\0' (null terminator) is encountered
    while (*str != '\0') {
        length++; // Increment length for each character
        str++;    // Move to the next character in the string
    }
    return length;
}

int main() {
    char str[100]; // Declare a character array to store the string
    printf("Enter a string: ");
    scanf("%[^\n]", str); // Read string from the user until newline is encountered

    int length = stringLength(str); // Call the function to find the length of the string

    printf("Length of the string is: %d\n", length);
    return 0;
}


This program defines a function `stringLength()` that calculates the length of a string by iterating through it until it finds the null terminator (`'\0'`). Then, in the `main()` function, it reads a string from the user and calls `stringLength()` to find its length.



4. (a) Define function. How are functions declared in C language ? What are function prototypes and what is the use of return statements ?



In programming, a function is a block of code that performs a specific task. Functions help in organizing code, promoting reusability, and enhancing readability. In C language, functions are declared using the following syntax:

return_type function_name(parameter_list) {
    // Function body
}

Here's what each part means:

return_type: It specifies the data type of the value that the function returns to the calling code. It can be `int`, `float`, `void`, etc. If the function doesn't return any value, `void` is used.

function_name: It is the name given to the function. It should follow the rules of naming identifiers in C.

-parameter_list: It specifies the parameters that the function accepts. Parameters are optional, and if a function doesn't take any parameters, the parameter list is left empty.

For example, a simple function in C to add two integers might look like this:


int add(int a, int b) {
    return a + b;
}


In C, function prototypes are declarations that provide the compiler with information about the function before its actual definition. They specify the return type of the function, its name, and the types of its parameters. Function prototypes are typically placed at the beginning of a C file or in a header file. They are declared using the same syntax as the function declaration, but without the function body. Here's an example:


int add(int a, int b);


The purpose of function prototypes is to inform the compiler about the existence and signature of functions that are defined elsewhere in the code. This allows the compiler to perform type checking and ensure that the function is called correctly.

Return statements are used within functions to specify the value that the function should return to its caller. When a return statement is encountered in a function, the function stops executing, and control is returned to the calling code. The value provided in the return statement is passed back to the caller. If the return type of the function is `void`, there's no value to return, so return statements can be omitted or can simply use `return;` without any value.



(b) Explain the function ‘‘call by reference’’ in C language. Give advantages and disadvantages of it

In C language, "call by reference" is a method of passing arguments to a function where the memory address of the actual parameter (variable) is passed to the function, rather than a copy of the value itself. This means that any changes made to the parameter within the function will directly affect the original variable outside the function.

Here's a simple example to illustrate call by reference:


#include <stdio.h>

// Function prototype
void changeValue(int *num);

int main() {
    int x = 10;

    // Passing the address of x to the function
    changeValue(&x);

    // x has been changed inside the function
    printf("New value of x: %d\n", x);

    return 0;
}

// Function definition
void changeValue(int *num) {
    *num = 20; // Dereferencing the pointer to change the value at the address
}


Advantages of call by reference:

1. **Efficiency**: Passing large data structures by reference avoids the overhead of copying the entire structure, which can be costly in terms of memory and performance.

2. **Ability to modify variables**: Since the function receives the memory address of the variable, any modifications made to it within the function directly affect the original variable outside the function. This can be useful when you need a function to modify the value of a variable.

Disadvantages of call by reference:

1. **Complexity and potential for errors**: Managing pointers and memory addresses can be error-prone, especially for inexperienced programmers. Incorrect usage, such as dereferencing a null pointer or accessing memory out of bounds, can lead to bugs like segmentation faults or undefined behavior.

2. **Side effects**: Because call by reference allows functions to modify variables outside their scope, it can lead to unexpected side effects if not used carefully. This can make code harder to understand and debug, especially in larger programs where the flow of data is more complex.

3. **Dependency on external state**: Functions using call by reference are dependent on the state of variables outside their scope. This can make the code less modular and harder to test, as changes to one part of the program may have unintended consequences elsewhere.


5. (a) Explain the following statements with the
help of an example for each : 
(i) Break
(ii) Goto
(iii) Continue



Sure, here's an explanation of each of these statements in C along with an example for each:

(i) **Break:**
The `break` statement in C is used to exit the innermost loop (for, while, or do-while) or switch statement. It helps in prematurely terminating the loop's execution based on certain conditions.

Example:

#include <stdio.h>

int main() {
    int i;
    for(i = 1; i <= 10; i++) {
        if(i == 5) {
            break; // exit loop when i equals 5
        }
        printf("%d\n", i);
    }
    return 0;
}

In this example, when the value of `i` becomes 5, the `break` statement is encountered, and the loop terminates.

(ii) **Goto:**
The `goto` statement in C allows transferring the control of the program to another part of the code. Although widely discouraged due to its potential to create spaghetti code and make the program hard to understand, it can be useful in certain scenarios.

Example:

#include <stdio.h>

int main() {
    int i = 1;
start:
    printf("%d\n", i);
    i++;
    if (i <= 5) {
        goto start; // jump to the 'start' label
    }
    return 0;
}
In this example, the program jumps back to the `start` label whenever `i` is less than or equal to 5.

(iii) **Continue:**
The `continue` statement in C is used within loops to skip the rest of the code inside the loop for the current iteration and proceed to the next iteration of the loop.

Example:

#include <stdio.h>

int main() {
    int i;
    for(i = 1; i <= 5; i++) {
        if(i == 3) {
            continue; // skip printing when i equals 3
        }
        printf("%d\n", i);
    }
    return 0;
}

In this example, when `i` equals 3, the `continue` statement is encountered, and the loop proceeds to the next iteration without executing the `printf` statement.



(b) Using File Handling Concept, write a program to copy one file to another. 

Sure, here's a simple C program that copies the contents of one file to another using file handling:


#include <stdio.h>

int main() {
    FILE *sourceFile, *destinationFile;
    char sourceFileName[100], destinationFileName[100];
    char ch;

    // Get the name of the source file from the user
    printf("Enter the name of the source file: ");
    scanf("%s", sourceFileName);

    // Open the source file in read mode
    sourceFile = fopen(sourceFileName, "r");

    if (sourceFile == NULL) {
        printf("Error opening source file.\n");
        return 1;
    }

    // Get the name of the destination file from the user
    printf("Enter the name of the destination file: ");
    scanf("%s", destinationFileName);

    // Open the destination file in write mode
    destinationFile = fopen(destinationFileName, "w");

    if (destinationFile == NULL) {
        printf("Error opening destination file.\n");
        fclose(sourceFile);
        return 1;
    }

    // Copy contents from source file to destination file
    while ((ch = fgetc(sourceFile)) != EOF) {
        fputc(ch, destinationFile);
    }

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

    // Close both files
    fclose(sourceFile);
    fclose(destinationFile);

    return 0;
}


This program prompts the user to enter the name of the source file and the destination file. Then it opens both files, reads characters from the source file, and writes them to the destination file until the end of the source file is reached. Finally, it closes both files and prints a success message.







(c) Write a short note on Ternary Operator with an illustration.

The ternary operator in C, represented by "? :", offers a concise way to express conditional statements. Its syntax is: condition ? expression1 : expression2. If the condition evaluates to true, expression1 is executed; otherwise, expression2 is executed. Here's an example:

#include <stdio.h>

int main() {
    int num = 10;
    char* result = (num % 2 == 0) ? "Even" : "Odd";
    printf("%d is %s\n", num, result);
    return 0;
}

In this example, if num is even, "Even" is assigned to result; otherwise, "Odd" is assigned.



Comments

College Admission

Best Career Option After Class 12 Course List

slider1

Blog E-commerce Auto Slider
Product 1
Product 4
Product 4
Product 4
Product 4
Product 4
Product 4

IIM Calcutta

 

IIM Calcutta

 

Apply For Admission


SUBSCRIBE

This Blog is protected by DMCA.com

Admission

SUBSCRIBE

OlderPost

Contact Form

Name

Email *

Message *

Share