Programming with C - Practice Questions

0

UNIVERSITY OF NORTH BENGAL 

B.Sc. Honours 1st Semester Examination

CC1-COMPUTER SCIENCE (12) 

PROGRAMMING FUNDAMENTALS USING C


1. Answer any 5 questions (5x1=5 marks)

 

i) Define constant variables with an example.

A constant is a value or variable that can’t be changed in the program, for example, 10, 20, ‘a’, 3.4, “c programming” etc. The const keyword is used to define constants in C programming.

 Const float PI=3.14; (code-box)

 ii) Write some names of the Header files?

<stdio.h>, <math.h>, <string.h>, <stdlib.h>, etc.    

iii) Differentiate between i++ and ++i.

i++ is known as a post-increment operator. Here the value of i is assigned to i before incrementing. 
++i is known as the post-increment operator. Here i will increment first and then the incremented value will be assigned. 

iv) What is a null pointer?

A null pointer is a pointer that does not point to any memory location and hence does not hold the address of any variables. 

v) What is garbage value?

The Garbage value is a random value at an address in a computer's memory. Whenever a variable is defined without giving any value to it, it contains the leftover values from the previous program. It is said to have a garbage value. 

vi) what is recursion?

Recursion is the technique of making a function call itself. This technique provides a way to break complicated problems down into smaller problems that are easier to solve. 

vii) Determine the value of x, where x = 7/2.


2. Answer any 3 questions (3x5=15)


i) Explain various parameter passing techniques in C.

In C, we can pass parameters in two different ways. The first one is call by value. In this technique, the parameters are copied to the function arguments. So if any modifications are done, that will update the copied value, not the actual value. The second method is call by reference. It works by passing the address of the variables into the function. So when the function updates the value pointed by that address, the actual value will also change. 

ii) WAP to find n! Using recursion.

#include<stdio.h>

int fac(int n); 

int main(){ 
int n, fact; 

printf("Enter a number: "); 
scanf("%d", &n); 

fact = fac(n); 
printf("Factorial of %d is %d \n", n, fact); 

return 0; 

int fac(int n){ 
    if(n==0) 
        return 1;
    else 
        return(n*fac(n-1)); 
} (code-box)

iii) Explain different loop control structures in C.

Loops are used in programming to repeat a specific block until some end condition is met. For loop is a repetitive and iterative looping control structure that executes a block of code a certain number of times. 
We have three Loops in C:
  • For Loop: This kind of loop performs the execution of a sequence of various statements at various times. It then abbreviates the available code that manages the variables of the loop.
  • While Loop: This type of loop is used for repeating any given statement or a group of various statements whenever the condition we have is true. Thus, it will perform the testing of the condition before the execution of the body of the loop.
  • Do-While Loop: This loop is just like the while statement. The only exception is that the do-while statement performs the testing of the condition that is present at the very end of a loop body.
Type of Loop Control Statements in C:
  • Goto: This type of statement transfers the control to any labeled statement.
  • Continue: This type of statement will cause a loop to skip the remainder present in its body and then retest its actual condition (immediately) before reiterating it.
  • Break: This type of statement ultimately terminates the switch statement and the loop statement. It then transfers the statement execution after following the switch or loop immediately.

iv) What are derived data types? Explain with examples the difference between structure and union in C.

Data types that are derived from fundamental data types are called derived data types. Derived data types do not create new data types. Instead, they add some functionality to the existing data types.
Given below are the various derived data types used in C: Arrays, Pointers, Functions,  Structures, Unions. 

Difference between Structure and Union:
Structure: In the case of a Structure, there is a specific memory location for every input data member. Thus, it can store multiple values of the various members.

typedef struct{ 
    char name[25]; 
    int id; 
    char group; 
    float marks[5];
     double interest; 
    }Student; (code-box)

Union: In the case of a Union, there is an allocation of only one shared memory for all the input data members. Thus, it stores one value at a time for all of its members.
The union is defined in the same way as a structure but with the keyword union.

union Student{ 
    char name[25]; 
    int id; 
    char group; 
    float marks[5]; 
    double interest; 
    }st1, st2; (code-box)

When we assign values to union data, union allocates enough memory to accommodate the largest data type defined. For example, since the name takes the biggest space in the memory out of all the other data types, the union will allocate the space taken by name. 
Let’s say we assign and print multiple values in the union at the same time.

st1.id = 1; 
st1.group = 'a'; 
strcpy(st1.name, "student1"); 
printf( "ID : %d\n", st1.id); 
printf( "Group : %c\n", st1.group); 
printf( "Name : %s\n", st1.name);  (code-box)

 

 Unlike struct, this will fetch output as –


ID : 1685419123 

Group : s 

Name : student1 (code-box)

 

Only the value of the member name is correct; other values have been corrupted. However, if we assign and print the values one by one, we will get all the values correctly.


st1.id = 1; 

printf( "ID : %d\n", st1.id); 

st1.group = 'a'; 

printf( "Group : %c\n", st1.group); 

strcpy(st1.name, "student1"); 

printf( "Name : %s\n", st1.name); (code-box)

 

Now, we get the output as –


ID : 1 

Group : a 

Name : student1 (code-box)

 

v) Explain the concept of storage classes in C.

A storage class defines the scope (visibility) and life-time of variables and/or functions within a C Program. They precede the type that they modify. We have four different storage classes in a C program:
  • The auto Storage Class: The auto storage class is the default storage class for all local variables.
  • The register Storage Class: The register storage class is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can't have the unary '&' operator applied to it (as it does not have a memory location).
  • The static Storage Class: The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls.
  • The extern Storage Class: The extern storage class is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern', the variable cannot be initialized however, it points the variable name at a storage location that has been previously defined.

3. Answer any two questions. (2x10=10)


i) WAP to multiply two matrices.

#include<stdio.h>
int main() {
    int m, n, p, q, i, j, k;
    int a[10][10], b[10][10], res[10][10];

    printf("Enter the order of first matrix\n");
    scanf("%d%d", & m, & n);
    printf("Enter the order of second matrix\n");
    scanf("%d%d", & p, & q);

    if (n != p) {
        printf("Matrix is incompatible for multiplication\n");
    } else {
        printf("Enter the elements of Matrix-A:\n");
        for (i = 0; i < m; i++) {
            for (j = 0; j < n; j++) {
                scanf("%d", & a[i][j]);
            }
        }

        printf("Enter the elements of Matrix-B:\n");
        for (i = 0; i < p; i++) {
            for (j = 0; j < q; j++) {
                scanf("%d", & b[i][j]);
            }
        }

        for (i = 0; i < m; i++) {
            for (j = 0; j < q; j++) {
                res[i][j] = 0;
                for (k = 0; k < p; k++) {
                    res[i][j] += a[i][k] * b[k][j];
                }
            }
        }

        printf("The product of the two matrices is:-\n");

        for (i = 0; i < m; i++) {
            for (j = 0; j < q; j++) {
                printf("%d\t", res[i][j]);
            }
            printf("\n");
        }
    }

    return 0;
} (code-box)

ii) Differentiate between static and dynamic memory allocation. What is the use of malloc(), calloc(), realloc(), and free() functions?

Memory allocation is a process by which computer programs and services are assigned with physical or virtual memory space. The memory allocation is done either before or at the time of program execution. There are two types of memory allocations:

Static Memory Allocation: Static Memory is allocated for declared variables by the compiler. The address can be found using the address of operator and can be assigned to a pointer. The memory is allocated during compile time. 

Dynamic Memory Allocation: Memory allocation done at the time of execution(run time) is known as dynamic memory allocation. Functions calloc() and malloc() support allocating dynamic memory. In the Dynamic allocation of memory space is allocated by using these functions when the value is returned by functions and assigned to pointer variables.

malloc(): The “malloc” or “memory allocation” method in C 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. It doesn’t Initialize memory at execution time so it has initialized each block with the default garbage value initially. It is a library function present in the <stdlib.h> header file.

General Syntax: 

ptr = (cast-type*) malloc(byte-size) (code-box)

Example Syntax:

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. (code-box)


calloc(): "calloc" or "contiguous allocation" method in C is used to dynamically allocate the specified number of blocks of memory of the specified type. It is very much similar to malloc() but has two different points and these are: 

  1. It initializes each block with a default value '0'. 
  2. It has two parameters or arguments as compared to malloc().

General Syntax:

ptr = (cast-type*)calloc(n, element-size); 
// here, n is the no. of elements and element-size is the size of each element. (code-box)


Example Syntax:


ptr = (float*)  calloc(25, sizeof(float)); 

// This statement allocates contiguous space in memory for 25 elements each with the size of the float. (code-box)


realloc(): "realloc" or "re-allocation" method in C 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. re-allocation of memory maintains the already present value and new blocks will be initialized with the default garbage value.


Syntax:


ptr = realloc(ptr, newSize); 

// where ptr is reallocated with new size 'newSize'. (code-box)

 

free(): "free" method in C is used to dynamically de-allocate the memory. The memory allocated using functions malloc() and calloc() is not de-allocated on its own. Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce the wastage of memory by freeing it.


Syntax:

free(ptr); (code-box)

 

iii) What are C Header files? Discuss the various in-built header files in C. How do you create your own header files?

A header file is a file with extension .h which contains C function declarations and macro definitions to be shared between several source files. There are two types of header files: the files that the programmer writes and the files that come with your compiler. We can request to use a header file in our program by including it with the C preprocessing directive #include. For example #include<stdio.h>
  • #include<stdio.h>: It is used to perform input and output operations using functions scanf() and printf().
  • #include<string.h>: It is used to perform various functionalities related to string manipulation like strlen(), strcmp(), strcpy(), size(), etc.
  • #include<math.h>: It is used to perform mathematical operations like sqrt(), log2(), pow(), etc.
  • #include<conio.h>: It is used for console input/output functions.
  • #include<stdlib.h>: It is used for general utility functions.

In order to create our own header file, we need to save our code as "filename.h", we can give any name but the extension should be .h indicating it is a header file.

For Example:

void add(int a, int b)
{
printf("Added value=%d\n", a + b);
}
void multiply(int a, int b)
{
printf("Multiplied value=%d\n", a * b);
} (code-box)

 

Now as we need to include stdio.h in order to use printf() function. We will also need to include the above header file as #include "filename.h". The "" here are used to instruct the preprocessor to look into the present folder and into the standard folder of all header files if not found in the present folder. So, if we wish to use angular brackets instead of "" to include our header file we have to save our file in the standard folder of header files.


Example code:

// C program to use the above-created header file

#include <stdio.h>

#include "filename.h"

int main()

{

add(4, 6);


/*This calls add function written in filename.h

and therefore no compilation error.*/

multiply(5, 5);


// Same for the multiply function in filename.h

printf("BYE!See you Soon");

return 0;

} (code-box)


iv) Write a note on Function in C.

A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions. We can divide up our code into separate functions. How we divide up our code among different functions is up to us, but logically the division is such that each function performs a specific task.

Defining a Function: The general form of a function definition in C programming language is as follows-

return_type function_name( parameter list ) {
   body of the function
} (code-box)

 

Return Type: A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void. 

Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature. 

Parameters: A parameter is like a placeholder. When a function is invoked, we pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters. 

Function Body: The function body contains a collection of statements that define what the function does.

Example:

/* function returning the max between two numbers */
int max(int num1, int num2) {

   /* local variable declaration */
   int result;
 
   if (num1 > num2)
      result = num1;
   else
      result = num2;
 
   return result; 
} (code-box)


Function Declaration: A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately.


A function declaration has the following parts:


return_type function_name( parameter list ); (code-box)


For the above-defined function max(), the function declaration is as follows:


int max(int num1, int num2); (code-box)


Calling a Function: To call a function, you simply need to pass the required parameters along with the function name, and if the function returns a value, then you can store the returned value.


For example: 


#include <stdio.h>

/* function declaration */

int max(int num1, int num2);

int main () {

   /* local variable definition */

   int a = 100;

   int b = 200;

   int ret;

   /* calling a function to get max value */

   ret = max(a, b);

   printf( "Max value is : %d\n", ret );

   return 0;

}

/* function returning the max between two numbers */

int max(int num1, int num2) {

   /* local variable declaration */

   int result;

   if (num1 > num2)

      result = num1;

   else

      result = num2;

   return result; 

} (code-box)

 

 

Post a Comment

0Comments
Post a Comment (0)