Open In App

AKTU 1st Year Sem 1 Solved Paper 2017-18 | COMP. SYSTEM & C PROGRAMMING | Sec C

Paper download link: Paper | Sem 1 | 2017-18

B.Tech. (SEM-I) THEORY EXAMINATION 2017-18 COMPUTER SYSTEM & PROGRAMMING IN C



Time: 3hrs Total Marks: 100 Note:-

Section – C



3. Attempt any two of the following: (2*5 = 10)

  1. What is meant by Storage Classes of a variable? Define all types of storage classes with example.
    Storage Classes are used to describe about the features of a variable/function. These features basically include the scope, visibility and life-time which help us to trace the existence of a particular variable during the runtime of a program. C language uses 4 storage classes, namely:
    1. auto: This is the default storage class for all the variables declared inside a function or a block. Hence, the keyword auto is rarely used while writing programs in C language. Auto variables can be only accessed within the block/function they have been declared and not outside them (which defines their scope). Of course, these can be accessed within nested blocks within the parent block/function in which the auto variable was declared. However, they can be accessed outside their scope as well using the concept of pointers given here by pointing to the very exact memory location where the variables resides. They are assigned a garbage value by default whenever they are declared.
    2. extern: Extern storage class simply tells us that the variable is defined elsewhere and not within the same block where it is used. Basically, the value is assigned to it in a different block and this can be overwritten/changed in a different block as well. So an extern variable is nothing but a global variable initialized with a legal value where it is declared in order to be used elsewhere. It can be accessed within any function/block. Also, a normal global variable can be made extern as well by placing the ‘extern’ keyword before its declaration/definition in any function/block. This basically signifies that we are not initializing a new variable but instead we are using/accessing the global variable only. The main purpose of using extern variables is that they can be accessed between two different files which are part of a large program. For more information on how extern variables work, have a look at this link.
    3. static: This storage class is used to declare static variables which are popularly used while writing programs in C language. Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve the value of their last use in their scope. So we can say that they are initialized only once and exist till the termination of the program. Thus, no new memory is allocated because they are not re-declared. Their scope is local to the function to which they were defined. Global static variables can be accessed anywhere in the program. By default, they are assigned the value 0 by the compiler.
    4. register: This storage class declares register variables which have the same functionality as that of the auto variables. The only difference is that the compiler tries to store these variables in the register of the microprocessor if a free register is available. This makes the use of register variables to be much faster than that of the variables stored in the memory during the runtime of the program. If a free register is not available, these are then stored in the memory only. Usually few variables which are to be accessed very frequently in a program are declared with the register keyword which improves the running time of the program. An important and interesting point to be noted here is that we cannot obtain the address of a register variable using pointers.
  2. Write a program to multiply two matrices ( read size and number of element of matrices from the keyboard). 




// C program to multiply two square matrices.
 
#include <stdio.h>
 
const int MAX = 100;
 
// Function to print Matrix
void printMatrix(int M[][MAX], int rowSize, int colSize)
{
    for (int i = 0; i < rowSize; i++) {
        for (int j = 0; j < colSize; j++)
            printf("%d ", M[i][j]);
 
        printf("\n");
    }
}
 
// Function to multiply two matrices A[][] and B[][]
void multiplyMatrix(int row1, int col1, int A[][MAX],
                    int row2, int col2, int B[][MAX])
{
    int i, j, k;
 
    // Matrix to store the result
    int C[MAX][MAX];
 
    // Check if multiplication is Possible
    if (row2 != col1) {
        printf("Not Possible\n");
        return;
    }
 
    // Multiply the two
    for (i = 0; i < row1; i++) {
        for (j = 0; j < col2; j++) {
            C[i][j] = 0;
            for (k = 0; k < row2; k++)
                C[i][j] += A[i][k] * B[k][j];
        }
    }
 
    // Print the result
    printf("\nResultant Matrix: \n");
    printMatrix(C, row1, col2);
}
 
// Driven Program
int main()
{
    int row1, col1, row2, col2, i, j;
    int A[MAX][MAX], B[MAX][MAX];
 
    // Read size of Matrix A from user
    printf("Enter the number of rows of First Matrix: ");
    scanf("%d", &row1);
    printf("%d", row1);
    printf("\nEnter the number of columns of First Matrix: ");
    scanf("%d", &col1);
    printf("%d", col1);
 
    // Read the elements of Matrix A from user
    printf("\nEnter the elements of First Matrix: ");
    for (i = 0; i < row1; i++) {
        for (j = 0; j < col1; j++) {
            printf("\nA[%d][%d]: ", i, j);
            scanf("%d", &A[i][j]);
            printf("%d", A[i][j]);
        }
    }
 
    // Read size of Matrix B from user
    printf("\nEnter the number of rows of Second Matrix: ");
    scanf("%d", &row2);
    printf("%d", row2);
    printf("\nEnter the number of columns of Second Matrix: ");
    scanf("%d", &col2);
    printf("%d", col2);
 
    // Read the elements of Matrix B from user
    printf("\nEnter the elements of First Matrix: ");
    for (i = 0; i < row2; i++) {
        for (j = 0; j < col2; j++) {
            printf("\nB[%d][%d]: ", i, j);
            scanf("%d", &B[i][j]);
            printf("%d", B[i][j]);
        }
    }
 
    // Print the Matrix A
    printf("\n\nFirst Matrix: \n");
    printMatrix(A, row1, col1);
 
    // Print the Matrix B
    printf("\nSecond Matrix: \n");
    printMatrix(B, row2, col2);
 
    // Find the product of the 2 matrices
    multiplyMatrix(row1, col1, A, row2, col2, B);
 
    return 0;
}

Output:
Enter the number of rows of First Matrix: 2
Enter the number of columns of First Matrix: 3
Enter the elements of First Matrix: 
A[0][0]: 1
A[0][1]: 2
A[0][2]: 3
A[1][0]: 4
A[1][1]: 5
A[1][2]: 6

Enter the number of rows of Second Matrix: 3
Enter the number of columns of Second Matrix: 2
Enter the elements of First Matrix: 
B[0][0]: 1
B[0][1]: 2
B[1][0]: 3
B[1][1]: 4
B[2][0]: 5
B[2][1]: 6

First Matrix: 
1 2 3 
4 5 6 

Second Matrix: 
1 2 
3 4 
5 6 

Resultant Matrix: 
22 28 
49 64 
  1. Discuss various data-types used in C with suitable examples.
    Each variable in C has an associated data type. Each data type requires different amounts of memory and has some specific operations which can be performed over it. Let us briefly describe them one by one: Following are the examples of some very common data types used in C:
    • char: The most basic data type in C. It stores a single character and requires a single byte of memory in almost all compilers.
    • int: As the name suggests, an int variable is used to store an integer.
    • float: It is used to store decimal numbers (numbers with floating point value) with single precision.
    • double: It is used to store decimal numbers (numbers with floating point value) with double precision.

4. Attempt any two of the following: (2*5 = 10)

  1. What is recursion? Write a recursive program to find factorial of a number. 
    Recursion: The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function. Using recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc. Base condition in recursion: In recursive program, the solution to base case is provided and solution of bigger problem is expressed in terms of smaller problems. Program to find factorial of a number: 




// C program to find factorial of given number
#include <stdio.h>
 
// function to find factorial of given number
unsigned int factorial(unsigned int n)
{
 
    // Base case
    if (n == 0)
        return 1;
 
    // Recursively call factorial function
    return n * factorial(n - 1);
}
 
int main()
{
 
    int num;
 
    // Get the number of which
    // factorial is to be calculated
    scanf("%d", &num);
    printf("Enter the number: %d", num);
 
    // Find the factorial
    // and print the result
    printf("\nFactorial of %d is %d",
           num, factorial(num));
 
    return 0;
}

  1. Output:
Enter the number: 5
Factorial of 5 is 120
  1. Explain the difference between parameter passing mechanism call by value and call by reference. Which is more efficient and why?
    There are different ways in which parameter data can be passed into and out of methods and functions. Let us assume that a function B() is called from another function A(). In this case A is called the “caller function” and B is called the “called function or callee function”. Also, the arguments which A sends to B are called actual arguments and the parameters of B are called formal arguments.

Terminology

  1. Pass By Value : This method uses in-mode semantics. Changes made to formal parameter do not get transmitted back to the caller. Any modifications to the formal parameter variable inside the called function or method affect only the separate storage location and will not be reflected in the actual parameter in the calling environment. This method is also called as call by value.  




// C program to illustrate
// call by value
#include <stdio.h>
 
void func(int a, int b)
{
    a += b;
    printf("In func, a = %d b = %d\n", a, b);
}
int main(void)
{
    int x = 5, y = 7;
 
    // Passing parameters
    func(x, y);
    printf("In main, x = %d y = %d\n", x, y);
    return 0;
}

  1. Output:
In func, a = 12 b = 7
In main, x = 5 y = 7
  1. Languages like C, C++, Java support this type of parameter passing. Java in fact is strictly call by value. Shortcomings:
    • Inefficiency in storage allocation
    • For objects and arrays, the copy semantics are costly
  2. Pass by reference(aliasing) : This technique uses in/out-mode semantics. Changes made to formal parameter do get transmitted back to the caller through parameter passing. Any changes to the formal parameter are reflected in the actual parameter in the calling environment as formal parameter receives a reference (or pointer) to the actual data. This method is also called as <em>call by reference. This method is efficient in both time and space.  




// C program to illustrate
// call by reference
#include <stdio.h>
 
void swapnum(int* i, int* j)
{
    int temp = *i;
    *i = *j;
    *j = temp;
}
 
int main(void)
{
    int a = 10, b = 20;
 
    // passing parameters
    swapnum(&a, &b);
 
    printf("a is %d and b is %d\n", a, b);
    return 0;
}

  1. Output:
a is 20 and b is 10
  1. C and C++ both support call by value as well as call by reference whereas Java does’nt support call by reference. Shortcomings:
    • Many potential scenarios can occur
    • Programs are difficult to understand sometimes
  2. Write a program to check a number is prime number or not. 
    Program to check a number is prime or not: 




// C program to check if a number is prime
 
#include <stdio.h>
 
// function check whether a number
// is prime or not
int isPrime(int n)
{
    // Corner case
    if (n <= 1)
        return 0;
 
    // Check from 2 to n-1
    for (int i = 2; i < n; i++)
        if (n % i == 0)
            return 0;
 
    return 1;
}
 
// Driver Program
int main()
{
 
    int num;
 
    // Get the number of which
    // is to be checked
    scanf("%d", &num);
    printf("Enter the number: %d", num);
 
    // Check the number
    // and print the result
    printf("\nIs %d prime: ", num);
 
    if (isPrime(num) == 1) {
        printf("Yes");
    }
    else {
        printf("No");
    }
 
    return 0;
}

  1. Output:
Enter the number: 5
Is 5 prime: Yes

5. Attempt any two of the following: (2*5 = 10)

  1. What is Macros? How it is substituted? Write macro definition with arguments for calculation of area and perimeter of a circle and rectangle. Store these macro definitions in a file called “areaperi.h”. Include this file in your program and call the macro definition for calculating area and perimeter for circle.
    1. Creating areaperi.h : Write the below code and then save the file as areaperi.h. The extension should be .h indicating its a header file. 




#define AREA_OF_CIRCLE(r) (3.14 * r * r)
#define PERIMETER_OF_CIRCLE(r) (3.14 * 2 * r)
#define AREA_OF_RECTANGLE(l, b) (l * b)
#define AREA_OF_RECTANGLE(l, b) (2 * (l * b))

  1. Including the areaperi.h file in other program : Now as we need to include stdio.h as #include in order to use printf() function. We will also need to include the above header file areaperi.h as #include”areaperi.h”. The ” ” here are used to instructs the preprocessor to look into the present folder and into the standard folder of all header files if not found in present folder. So, if you wish to use angular brackets instead of ” ” to include your header file you can save it in the standard folder of header files otherwise. If you are using ” ” you need to ensure that the header file you created is saved in the same folder in which you will save the C file using this header file.
  2. Using the created header file : 




// C program to find area and perimeter
// of circle and rectangle
 
#include "areaperi.h"
#include <stdio.h>
 
int main()
{
 
    float radius, length, breadth;
 
    // Get the radius of the circle;
    scanf("%f", &radius);
    printf("Enter the radius of the circle: %f", radius);
 
    // This calls AREA_OF_CIRCLE macro
    // written in areaperi.h and
    // therefore no compilation error.
    printf("\nThe area of circle: %f",
           AREA_OF_CIRCLE(radius));
 
    // This calls PERIMETER_OF_CIRCLE macro
    // written in areaperi.h and
    // therefore no compilation error.
    printf("\nThe perimeter of circle: %f",
           PERIMETER_OF_CIRCLE(radius));
 
    // Get the length of the Rectangle
    scanf("%f", &length);
    printf("\nEnter the length of the Rectangle: %f", length);
 
    // Get the breadth of the Rectangle
    scanf("%f", &breadth);
    printf("\nEnter the breadth of the Rectangle: %f", breadth);
 
    // This calls AREA_OF_RECTANGLE macro
    // written in areaperi.h and
    // therefore no compilation error.
    printf("\nThe area of Rectangle: %f",
           AREA_OF_RECTANGLE(length, breadth));
 
    // This calls PERIMETER_OF_CIRCLE macro
    // written in areaperi.h and
    // therefore no compilation error.
    printf("\nThe perimeter of Rectangle: %f",
           PERIMETER_OF_CIRCLE(length, breadth));
}

  1. Output:
 
  1. What are the different file opening modes in C? Write a program to copy the contents of one file into other file?
    File opening modes in C:
    • “r” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the first character in it. If the file cannot be opened fopen( ) returns NULL.
    • “w” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.
    • “a” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.
    • “r+” – Searches file. If is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the first character in it. Returns NULL, if unable to open the file.
    • “w+” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a new file is created. Returns NULL, if unable to open file.
    • “a+” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.
  2. Define structure with syntax. Also write a program that compares two given dates. To store date use structure say date that contains three members namely date, month, and year. If the dates are equal then display message as “Equal” otherwise “Unequal”. 
    A structure is a user-defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type. How to create a structure? ‘struct’ keyword is used to create a structure. Following is an example. 




struct address {
    char name[50];
    char street[100];
    char city[50];
    char state[20];
    int pin;
};

  1.   How to declare structure variables? A structure variable can either be declared with structure declaration or as a separate declaration like basic types. 




// A variable declaration with structure declaration.
struct Point {
    int x, y;
} p1; // The variable p1 is declared with 'Point'
 
// A variable declaration like basic data types
struct Point {
    int x, y;
};
 
int main()
{
    struct Point p1; // The variable p1 is declared like a normal variable
}

  1. Note: In C++, the struct keyword is optional before in declaration of a variable. In C, it is mandatory. Program that compares two given dates: 




#include <stdio.h>
 
// Declaring the structure of Date
struct Date {
    int date;
    int month;
    int year;
};
 
// Driver code
int main()
{
    int date1, date2, month1,
        month2, year1, year2;
 
    // Get the first date
    scanf("%d", &date1);
    printf("Enter the first date: %d", date1);
    scanf("%d", &month1);
    printf("\nEnter the first month: %d", month1);
    scanf("%d", &year1);
    printf("\nEnter the first year: %d", year1);
 
    // Initialise the structure with first date
    struct Date Date1 = { date1, month1, year1 };
 
    // Get the second date
    scanf("%d", &date2);
    printf("\nEnter the second date: %d", date2);
    scanf("%d", &month2);
    printf("\nEnter the second month: %d", month2);
    scanf("%d", &year2);
    printf("\nEnter the second year: %d", year2);
 
    // Initialise the structure with first date
    struct Date Date2 = { date2, month2, year2 };
 
    printf("\nThe given dates are: ");
 
    // Comparing the Dates
    if (Date1.date == Date2.date
        && Date1.month == Date2.month
        && Date1.year == Date2.year) {
        printf("Equal");
    }
    else {
        printf("Unequal");
    }
 
    return 0;
}

  1. Output:
Enter the first date: 10
Enter the first month: 11
Enter the first year: 2018
Enter the second date: 10
Enter the second month: 11
Enter the second year: 2018
The given dates are: Equal

6. Attempt any two of the following: (2*5 = 10)

  1. Suppose a file contains student’s records with each record containing name and age of a student. Write a C program to read these records and display them in sorted order by name. 




// C program to read Student records
// like id, name and age,
// and display them in sorted order by Name
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
// struct person with 3 fields
struct Student {
    char* name;
    int id;
    char age;
};
 
// setting up rules for comparison
// to sort the students based on names
int comparator(const void* p, const void* q)
{
    return strcmp(((struct Student*)p)->name,
                ((struct Student*)q)->name);
}
 
// Driver program
int main()
{
    int i = 0, n = 5;
 
    struct Student arr[n];
 
    // Get the students data
    arr[0].id = 1;
    arr[0].name = "bd";
    arr[0].age = 12;
 
    arr[1].id = 2;
    arr[1].name = "ba";
    arr[1].age = 10;
 
    arr[2].id = 3;
    arr[2].name = "bc";
    arr[2].age = 8;
 
    arr[3].id = 4;
    arr[3].name = "aaz";
    arr[3].age = 9;
 
    arr[4].id = 5;
    arr[4].name = "az";
    arr[4].age = 10;
 
    // Print the Unsorted Structure
    printf("Unsorted Student Records:\n");
    for (i = 0; i < n; i++) {
        printf("Id = %d, Name = %s, Age = %d \n",
            arr[i].id, arr[i].name, arr[i].age);
    }
    // Sort the structure
    // based on the specified comparator
    qsort(arr, n, sizeof(struct Student), comparator);
 
    // Print the Sorted Structure
    printf("\n\nStudent Records sorted by Name:\n");
    for (i = 0; i < n; i++) {
        printf("Id = %d, Name = %s, Age = %d \n",
            arr[i].id, arr[i].name, arr[i].age);
    }
 
    return 0;
}

  1. Output:
Unsorted Student Records:
Id = 1, Name = bd, Age = 12 
Id = 2, Name = ba, Age = 10 
Id = 3, Name = bc, Age = 8 
Id = 4, Name = aaz, Age = 9 
Id = 5, Name = az, Age = 10 


Student Records sorted by Name:
Id = 4, Name = aaz, Age = 9 
Id = 5, Name = az, Age = 10 
Id = 2, Name = ba, Age = 10 
Id = 3, Name = bc, Age = 8 
Id = 1, Name = bd, Age = 12
  1. Write a program to sort a set of names stored in an array in alphabetical order. 




#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
// Defining comparator function as per the requirement
static int myCompare(const void* a, const void* b)
{
 
    // setting up rules for comparison
    return strcmp(*(const char**)a, *(const char**)b);
}
 
// Function to sort the array
void sort(const char* arr[], int n)
{
    // calling qsort function to sort the array
    // with the help of Comparator
    qsort(arr, n, sizeof(const char*), myCompare);
}
 
int main()
{
 
    // Get the array of names to be sorted
    const char* arr[];
    = { "GeeksforGeeks",
        "GeeksQuiz",
        "CLanguage" };
    int n = sizeof(arr) / sizeof(arr[0]);
    int i;
 
    // Print the given names
    printf("Given array of names is\n");
    for (i = 0; i < n; i++)
        printf("%d: %s \n", i, arr[i]);
 
    // Sort the given names
    sort(arr, n);
 
    // Print the sorted names
    printf("\nSorted array of names is\n");
    for (i = 0; i < n; i++)
        printf("%d: %s \n", i, arr[i]);
 
    return 0;
}

  1. Output:
Given array of names is
0: GeeksforGeeks 
1: GeeksQuiz 
2: CLanguage 

Sorted array of names is
0: CLanguage 
1: GeeksQuiz 
2: GeeksforGeeks 
  1. Write a user define function to compare two strings where they are identical or not. 




// C program to check if
// two strings are identical
 
#include <stdio.h>
#include <string.h>
 
int main()
{
 
    char string1[100], string2[100];
 
    // Get the strings which
    // is to be checked
    scanf("%s", string1);
    printf("Enter the first string: %s", string1);
 
    // Get the strings which
    // is to be checked
    scanf("%s", string2);
    printf("\nEnter the second string: %s", string2);
 
    // Check if both strings are equal
    printf("\nAre both strings same: ");
 
    if (strcmp(string1, string2) == 0) {
        printf("Yes");
    }
    else {
        printf("No");
    }
 
    return 0;
}

Output:
Enter the first string: GeeksForGeeks
Enter the second string: GeeksForGeeks
Are both strings same: Yes

7. Attempt any two of the following: (2*5 = 10)

  1. Define the concept of pointer> Also define the dynamic memory allocation and various functions for dynamic memory allocation, with suitable examples. 
    Pointers are symbolic representation of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. It’s general declaration in C/C++ has the format: 
    Syntax:
datatype *var_name; 
int *ptr;   //ptr can point to an address which holds int data
  1. How to use a pointer?
    • Define a pointer variable
    • Assigning the address of a variable to a pointer using unary operator (&) which returns the address of that variable.
    • Accessing the value stored in the address using unary operator (*) which returns the value of the variable located at the address specified by its operand.
    • malloc()
    • calloc()
    • free()
    • realloc()
    • malloc() “malloc” or “memory allocation” method is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. Syntax:
ptr = (cast-type*) malloc(byte-size)

For Example:
ptr = (int*) malloc(100 * sizeof(int));

Since the size of int is 4 bytes, 
this statement will allocate 400 bytes of memory. 
And, the pointer ptr holds the address 
of the first byte in the allocated memory.
  1. If the space is insufficient, allocation fails and returns a NULL pointer. Example: 




#include <stdio.h>
#include <stdlib.h>
 
int main()
{
 
    // This pointer will hold the
    // base address of the block created
    int* ptr;
    int n, i, sum = 0;
 
    // Get the number of elements for the array
    n = 5;
    printf("Enter number of elements: %d\n", n);
 
    // Dynamically allocate memory using malloc()
    ptr = (int*)malloc(n * sizeof(int));
 
    // Check if the memory has been successfully
    // allocated by malloc or not
    if (ptr == NULL) {
        printf("Memory not allocated.\n");
        exit(0);
    }
    else {
 
        // Memory has been successfully allocated
        printf("Memory successfully allocated using malloc.\n");
 
        // Get the elements of the array
        for (i = 0; i < n; ++i) {
            ptr[i] = i + 1;
        }
 
        // Print the elements of the array
        printf("The elements of the array are: ");
        for (i = 0; i < n; ++i) {
            printf("%d, ", ptr[i]);
        }
    }
 
    return 0;
}

Output:
Enter number of elements: 5
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5,
  1. calloc() “calloc” or “contiguous allocation” method is used to dynamically allocate the specified number of blocks of memory of the specified type. It initializes each block with a default value ‘0’. Syntax:
ptr = (cast-type*)calloc(n, element-size);

For Example:
ptr = (float*) calloc(25, sizeof(float));

This statement allocates contiguous space in memory 
for 25 elements each with the size of float.
  1. If the space is insufficient, allocation fails and returns a NULL pointer. Example: 




#include <stdio.h>
#include <stdlib.h>
 
int main()
{
 
    // This pointer will hold the
    // base address of the block created
    int* ptr;
    int n, i, sum = 0;
 
    // Get the number of elements for the array
    n = 5;
    printf("Enter number of elements: %d\n", n);
 
    // Dynamically allocate memory using calloc()
    ptr = (int*)calloc(n, sizeof(int));
 
    // Check if the memory has been successfully
    // allocated by malloc or not
    if (ptr == NULL) {
        printf("Memory not allocated.\n");
        exit(0);
    }
    else {
 
        // Memory has been successfully allocated
        printf("Memory successfully allocated using calloc.\n");
 
        // Get the elements of the array
        for (i = 0; i < n; ++i) {
            ptr[i] = i + 1;
        }
 
        // Print the elements of the array
        printf("The elements of the array are: ");
        for (i = 0; i < n; ++i) {
            printf("%d, ", ptr[i]);
        }
    }
 
    return 0;
}

Output:
Enter number of elements: 5
Memory successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5,
  1. free() “free” method is used to dynamically de-allocate the memory. The memory allocated using functions malloc() and calloc() are not de-allocated on their own. Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it. Syntax:
free(ptr);
  1. Example: 




#include <stdio.h>
#include <stdlib.h>
 
int main()
{
 
    // This pointer will hold the
    // base address of the block created
    int *ptr, *ptr1;
    int n, i, sum = 0;
 
    // Get the number of elements for the array
    n = 5;
    printf("Enter number of elements: %d\n", n);
 
    // Dynamically allocate memory using malloc()
    ptr = (int*)malloc(n * sizeof(int));
 
    // Dynamically allocate memory using calloc()
    ptr1 = (int*)calloc(n, sizeof(int));
 
    // Check if the memory has been successfully
    // allocated by malloc or not
    if (ptr == NULL || ptr1 == NULL) {
        printf("Memory not allocated.\n");
        exit(0);
    }
    else {
 
        // Memory has been successfully allocated
        printf("Memory successfully allocated using malloc.\n");
 
        // Free the memory
        free(ptr);
        printf("Malloc Memory successfully freed.\n");
 
        // Memory has been successfully allocated
        printf("\nMemory successfully allocated using calloc.\n");
 
        // Free the memory
        free(ptr1);
        printf("Calloc Memory successfully freed.\n");
    }
 
    return 0;
}

Output:
Enter number of elements: 5
Memory successfully allocated using malloc.
Malloc Memory successfully freed.

Memory successfully allocated using calloc.
Calloc Memory successfully freed.
  1. realloc() “realloc” or “re-allocation” method is used to dynamically change the memory allocation of a previously allocated memory. In other words, if the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory. Syntax:
ptr = realloc(ptr, newSize);

where ptr is reallocated with new size 'newSize'.
  1. If the space is insufficient, allocation fails and returns a NULL pointer. Example: 




#include <stdio.h>
#include <stdlib.h>
 
int main()
{
 
    // This pointer will hold the
    // base address of the block created
    int* ptr;
    int n, i, sum = 0;
 
    // Get the number of elements for the array
    n = 5;
    printf("Enter number of elements: %d\n", n);
 
    // Dynamically allocate memory using calloc()
    ptr = (int*)calloc(n, sizeof(int));
 
    // Check if the memory has been successfully
    // allocated by malloc or not
    if (ptr == NULL) {
        printf("Memory not allocated.\n");
        exit(0);
    }
    else {
 
        // Memory has been successfully allocated
        printf("Memory successfully allocated using calloc.\n");
 
        // Get the elements of the array
        for (i = 0; i < n; ++i) {
            ptr[i] = i + 1;
        }
 
        // Print the elements of the array
        printf("The elements of the array are: ");
        for (i = 0; i < n; ++i) {
            printf("%d, ", ptr[i]);
        }
 
        // Get the new size for the array
        n = 10;
        printf("\n\nEnter the new size of the array: %d\n", n);
 
        // Dynamically re-allocate memory using realloc()
        ptr = realloc(ptr, n * sizeof(int));
 
        // Memory has been successfully allocated
        printf("Memory successfully re-allocated using realloc.\n");
 
        // Get the new elements of the array
        for (i = 5; i < n; ++i) {
            ptr[i] = i + 1;
        }
 
        // Print the elements of the array
        printf("The elements of the array are: ");
        for (i = 0; i < n; ++i) {
            printf("%d, ", ptr[i]);
        }
 
        free(ptr);
    }
 
    return 0;
}

Output:
Enter number of elements: 5
Memory successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5, 

Enter the new size of the array: 10
Memory successfully re-allocated using realloc.
The elements of the array are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
  1. What is string? Also explain different string functions with examples. 
    Strings in C: Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character ‘\0’. Some of the most commonly used String functions are:
    • strcat: The strcat() function will append a copy of the source string to the end of destination string. The strcat() function takes two arguments: 1) dest 2) src It will append copy of the source string in the destination string. The terminating character at the end of dest is replaced by the first character of src . Return value: The strcat() function returns dest, the pointer to the destination string.
    • strchr: In C/C++, strrchr() is a predefined function used for string handling. cstring is the header file required for string functions. This function Returns a pointer to the last occurrence of a character in a string. The character whose last occurrence we want to find in passed as the second argument to the function and the string in which we have to find the character is passed as the first argument to the function. Syntax
char *strrchr(const char *str, int c) 
int strcmp(const char *leftStr, const char *rightStr );
char* strcpy(char* dest, const char* src);
int strlen(const char *str);
char *strncpy( char *dest, const char *src, size_t n )
const char* strrchr( const char* str, int ch )
            or
char* strrchr( char* str, int ch )
  1. Write short note on following (Any two):
    • (i) Stack with push and pop operation: Stack is a linear data structure which follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out).

Mainly the following three basic operations are performed in the stack:




// A linked list node
struct Node {
    int data;
    struct Node* next;
};

int main() { /* ... */ } 
int main(int argc, char *argv[]) { /* ... */ }
int main(int argc, char **argv) { /* ... */ }

Article Tags :