C Question Set

Note: In mobile, turn on "Desktop Site" mode for better visuals.

 Algorithm And Flowchart


1. What is algorithm?

Ans

An algorithm is a set of instructions for solving a problem or accomplishing a task.

Example of an algorithm is a recipe, which consists of specific instructions for preparing a dish or meal.

 

2.    What is flowchart?

Ans

A flowchart is a type of diagram that represents a workflow or process. A flowchart can also be defined as a diagrammatic representation of an algorithm, a step-by-step approach to solving a task.



C Language Structure and Features

 

3.    What is C language?

Ans

C  is general purpose, procedural programming language developed by Dennis Ritchie. It supports structured programming. Structured Programming is a type of programming that generally converts large or complex programs into more manageable and small pieces of code. These small pieces of codes are usually known as functions or modules or sub-programs of large complex programs.

 

4.    C program structure

Ans

·       Documentation Section (more information about program code)

·       Preprocessor Statements (header files)

·       Global Declarations

·       The main() function

o   Local Declarations

o   Program Statements and Expressions

·       User Defined Functions

 

5.    Features of C language?

Ans

·       Simple

·       Portable (C program written for one computer system can be compiled and run on another system with little or no modification.)

·       Structured programming language (to solve a large problem, C programming language divides the problem into smaller structural blocks each of which handles a particular responsibility.)

·       Speed

·       Pointers

·       Recursion (we can call the function within the function)

·       Extensible (It can easily adopt new features)

 

6.    List built-in functions in C?

Ans

·       Printf : used to print the result onto the output screen.

·       Scanf : used to accept user input from keyboard

·       Strlen : calculates the length of screen

·       Tolower : convert character to lowercase

·       Toupper : convert character to upper case

·       Exit : terminate program normally



Tokens in C

 

7.    What is token in C?

Ans

Every individual element of a program is called as token.

Classification of tokens in C

o   Keywords in C

o   Identifiers in C

o   Strings in C

o   Operators in C

o   Constant in C

o   Special Characters in C

 

8.    What are keywords?

Ans

Keywords are predefined, reserved words used in programming that have special meanings to the compiler. Keywords are part of the syntax and they cannot be used as an identifier.

Ex. Int, float, void, break, switch, while, for,etc.

 

9.    What is identifier.

Ans

Identifier refers to name given to entities such as variables, functions, structures etc.

Identifiers must be unique. They are created to give a unique name to an entity to identify it during the execution of the program.

For example:

Int marks;

Void total ();

 

10.What are constant?

Ans

A constant is a value or variable that can't be changed in the program.

There are two ways to define constant in C programming

1)    const keyword

Ex. const float PI=3.14; 

2)    #define pre-processor

Ex. #define PI 3.14 



Types of operator

 

11.Types of operators?

Ans

An operator is a symbol that tells the compiler to perform specific mathematical or logical functions.

Types of operator :

1.    Arithmetic Operators : C Arithmetic operators are used to perform mathematical calculations like addition, subtraction, multiplication, division and modulus in C programs.

Operator

Description

Example

Relational+

Adds two operands.

A + B = 30

−

Subtracts second operand from the first.

A − B = -10

*

Multiplies both operands.

A * B = 200

/

Divides numerator by de-numerator.

B / A = 2

%

Modulus Operator and remainder of after an integer division.

B % A = 0

++

Increment operator increases the integer value by one.

A++ = 11

--

Decrement operator decreases the integer value by one.

A-- = 9

 

2.    Relational Operators : A relational operator checks the relationship between two operands.

Operator

Description

Example

==

Checks if the values of two operands are equal or not.

(A == B) is not true.

!=

Checks if the values of two operands are equal or not.

(A != B) is true.

> 

Checks if the value of left operand is greater than the value of right operand.

(A > B) is not true.

< 

Checks if the value of left operand is less than the value of right operand.

(A < B) is true.

>=

Checks if the value of left operand is greater than or equal to the value of right operand.

(A >= B) is not true.

<=

Checks if the value of left operand is less than or equal to the value of right operand.

(A <= B) is true.


3.    Logical Operators : These operators are used to perform logical operations on the given expressions.

Operator

Description

Example

&&

Called Logical AND operator. If both the operands are non-zero, then the condition becomes true.

(A && B) is false.

||

Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true.

(A || B) is true.

!

Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false.

!(A && B) is true.

 

4.    Assignment Operators : Assignment operators are used to assigning value to a variable.

Operator

Description

Example

=

Simple assignment operator. Assigns values from right side operands to left side operand

C = A + B will assign the value of A + B to C

+=

Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand.

C += A is equivalent to C = C + A

-=

Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand.

C -= A is equivalent to C = C - A

*=

Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand.

C *= A is equivalent to C = C * A

/=

Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand.

C /= A is equivalent to C = C / A

%=

Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand.

C %= A is equivalent to C = C % A

 

5.    Bitwise Operator : The bitwise operators are the operators used to perform the operations on the data at the bit-level. When we perform the bitwise operations, then it is also known as bit-level programming. It consists of two digits, either 0 or 1. It is mainly used in numerical computations to make the calculations faster.         

Operator

Description

 

 

&

Bitwise AND operator

|

Bitwise OR operator

^

Bitwise exclusive OR operator

~

One's complement operator (unary operator)

<< 

Left shift operator

>> 

Right shift operator



Data types and type casting

 

12.Data types in C?

Ans

a.     Primary(Built-in)DataTypes:
void, int, char, double and float.

b.    Derived Data Types:
Array, References, and Pointers.

c.     User Defined Data Types:
Structure, Union, and Enumeration.

 

13.What is type-casting?

Ans

Converting one datatype into another is known as type casting or, type-conversion.

 


Variables


14.What are variables in C?

Ans

A variable is a name of the memory location. It is used to store data. Its value can be changed, and it can be reused many times.

It is a way to represent memory location through symbol so that it can be easily identified.

15.Diff between local and global variables.

Ans

·       Global variables

o   Global variables are those variables which are declared outside of all the functions or block and can be accessed globally in a program.

o   It can be accessed by any function present in the program.

·       Local variables

o   Variables that are declared within or inside a function block are known as Local variables.

o   These variables can only be accessed within the function in which they are declared.

  


Escape Sequences


16.What are Escape Sequences?

Ans

\a

Alarm or Beep

\b

Backspace

\n

New Line

\t

Tab (Horizontal)

\0

NULL

 


Format Specifiers


17.What are format specifiers?

Ans

Format specifiers define the type of data to be printed on standard output. You need to use format specifiers whether you're printing formatted output with printf() or  accepting input with scanf().

 

SPECIFIER

USED FOR

%c

a single character

%s

a string

%d

a decimal integer

%f

a floating point number for floats

 



Decision making statements


18.What is decision making statements?

Ans

There come situations in real life when we need to make some decisions and based on these decisions, we decide what should we do next. Similar situations arise in programming also where we need to make some decisions and based on these decisions we will execute the next block of code.

Decision making statements in C/C++ :

·       If

It is used to decide whether a certain statement or block of statements will be executed or not i.e. if a certain condition is true then a block of statement is executed otherwise not.

 

·       If else

The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the C else statement. We can use the else statement with if statement to execute a block of code when the condition is false.

 

·        If else if ladder

A user can decide among multiple options. The C if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions are true, then the final else statement will be executed.

 

·       Nested if else

A nested if in C is an if statement that is the target of another if statement. Nested if statements mean an if statement inside another if statement.

 

·       Switch

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.

Default case must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true.

 

·       Jump Statements

·       Break

This loop control statement is used to terminate the loop. As soon as the break statement is encountered from within a loop, the loop iterations stop there, and control returns from the loop immediately to the first statement after the loop.

 

·       Continue

This loop control statement is just like the break statement. The continue statement is opposite to that of the break statement, instead of terminating the loop, it forces to execute the next iteration of the loop.

(Skips a single iteration)

 

·       Return

The return in C or C++ returns the flow of the execution to the function from where it is called. This statement does not mandatorily need any conditional statements. As soon as the statement is executed, the flow of the program stops immediately and return the control from where it was called. The return statement may or may not return anything for a void function, but for a non-void function, a return value is must be returned.

 

19.Switch statement (Advantage of switch)

Ans

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.

 

Advantages of switch :

§  The switch statement is easier to read than if-else statements.

§  It overcomes the challenges of the “if-else if” statement that makes compilation difficult because of deep nesting. The switch statement has a fixed depth.

§  It allows the best-optimized implementation for faster code execution than the “if-else if” statement.

§  It is easy to debug and maintain the programs using switch statements.

§  The switch statement has faster execution power.



Looping statements


20.What is looping?

Ans

In computer science, a loop is a programming structure that repeats a sequence of instructions until a specific condition is met.

 

21.Why do we need looping in programming?

Ans

The purpose of loops is to repeat the same, or similar, code a number of times. This number of times could be specified to a certain number, or the number of times could be dictated by a certain condition being met.

 

22.Use of while loop?

Ans

A while loop in C programming repeatedly executes a target statement or a block of code as long as a given condition is true.

 

while(condition) {

   statement(s);

}

 

The loop iterates while the condition is true. When the condition becomes false, the program control passes to the line immediately following the loop.

 

23.Use of do while loop?

Ans

A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one time.

 

do {

   statement(s);

} while( condition );

 

The conditional expression appears at the end of the loop, so the statement(s) in the loop executes once before the condition is tested.

If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop executes again. This process repeats until the given condition becomes false.

 

24.Difference between while and do while?

Ans

While loop is executed only when given condition is true. So it is an entry control loop.

 

Whereas, do-while loop is executed for first time irrespective of the condition. After executing while loop for first time, then condition is checked. So it is an exit control loop.

 

25.Use of for loop?

Ans

A for loop is a repetition control structure which allows us to write a loop that is executed a specific number of times.

 

for (initial value; condition; incrementation or decrementation )

{

  statements;

}

 

1)    The initial value of the for loop is performed only once.

2)    The condition is a Boolean expression that tests and compares the counter to a fixed value after each iteration, stopping the for loop when false is returned.

3)    The incrementation/decrementation increases (or decreases) the counter by a set value.

 

26.Difference between while and for? (when to use while and for loop)

Ans

The difference between for loop and while loop is that in for loop the number of iterations to be done is already known and is used to obtain a certain result whereas in while loop the command runs until a certain condition is reached and the statement is proved to be false.

 


Arrays


27.What is an array?

Ans

An array is defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in C programming language which can store the primitive type of data such as int, char, double, float, etc.

 

Syntax : data_type array_name[array_size]; 

 

Ex. int marks[5]; 

 

Initialization of array :

(Array index starts with 0, so arr[0] always gives the first element of the array.)

 

1)    Int marks[5] = {85,90,80,90,100};

2)    Int marks[] = {85,90,80,100};

3)    Int marks[5];

marks[0] = 80;

marks[1] = 80;

marks[2] = 80;

marks[3] = 80;

marks[4] = 80;

4)    Using loop

Int marks[5];

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

{

    printf("Enter number \n");

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

}

            Accessing an element of an  array :

1)    Printf(“%d”,marks[0]);

Printf(“%d”,marks[1]);

.

.

 

2)    Using loop

for(int i = 0; i<5; i++)

{

    Printf(“%d ”,marks[i] );  

}

 

28.Characteristics of array.

Ans

Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.

Elements of the array are stored at contiguous memory locations where the first element is stored at the smallest memory location.

Elements of the array can be randomly accessed since we can calculate the address of each element of the array with the given base address and the size of the data element.

 

29.Types of array?

Ans

1)    Single  Dimensional Array (One dimensional array)

In c programming language, single dimensional arrays are used to store list of values of same datatype. In other words, single dimensional arrays are used to store a row of values. In single dimensional array, data is stored in linear form. Single dimensional arrays are also called as one-dimensional arrays, Linear Arrays or simply 1-D Arrays.

 

Declaration : datatype arrayName [ size ] ;

Initialization : d atatype arrayName [ size ] = {value1, value2, ...} ;

To Access Element : arrayName [ indexValue ];

  

2)    Multi Dimensional Array

An array of arrays is called as multi dimensional array. In simple words, an array created with more than one dimension (size) is called as multi dimensional array. Multi dimensional array can be of two dimensional array or three dimensional array or four dimensional array or more...

Most popular and commonly used multi dimensional array is two dimensional array. The 2-D arrays are used to store data in the form of table. We also use 2-D arrays to create mathematical matrices.

 

Declaration : datatype arrayName [ rowSize ] [ columnSize ] ;

Initialization : datatype arrayName [rows][colmns] =

{{r1c1value, r1c2value, ...},{r2c1, r2c2,...}...} ;

                     To Access Element : arrayName [ rowIndex ] [ columnIndex ];

 

30.Advantages and disadvantages of array?

Ans

Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.

3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.

 

Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.

 


String in C


31.What is String?

Ans

In C programming, a string is a sequence of characters terminated with a null character \0 .

The string can be defined as the one-dimensional array of characters terminated by a null ('\0'). The character array or the string is used to manipulate text such as word or sentences. Each character in the array occupies one byte of memory, and the last character must always be 0. The termination character ('\0') is important in a string since it is the only way to identify where the string ends. When we define a string as char s[10], the character s[10] is implicitly initialized with the null in the memory.

 

There are two ways to declare a string in c language.

 

1)    By char array

char name[8] = {'P', 'r', 'a', 'j', 'v', 'a', 'l'};

char name[] = {'P', 'r', 'a', 'j', 'v', 'a', 'l'};

 

2)    By string literal

 char name[10] = "Prajval";

char name[] = "Prajval";

 

 

32.Built-in string functions? (string.h header file)

Ans

There are many important string functions defined in "string.h" library.

 

No.

Function

Description

1)

strlen(string_name)

 

returns the length of string name.

2)

strcpy(destination, source)

 

copies the contents of source string to destination string.

3)

strcat(first_string, second_string)

 

concats or joins first string with second string. The result of the string is stored in first string.

4)

strcmp(first_string, second_string)

 

compares the first string with second string. If both strings are same, it returns 0.

5)

strrev(string)

 

returns reverse string.

6)

strlwr(string)

 

returns string characters in lowercase.

7)

strupr(string)

 

returns string characters in uppercase.

 



Structure

 

33.What is structure?

Ans

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.

Structure is a user-defined datatype in C language which allows us to combine data of different types together. Structure helps to construct a complex data type which is more meaningful. It is somewhat similar to an Array, but an array holds data of similar type only. But structure on the other hand, can store data of any type, which is practical more useful.

struct keyword is used to define a structure. struct defines a new data type which is a collection of primary and derived data types.

 

Syntax:

 

struct [structure_tag]

{

    //member variable 1

    //member variable 2

    //member variable 3

    ...

}[structure_variables];

 

 

34.Difference between array and structure?

Ans

Sr. No.

Key

Structure

Array

1

Definition

Structure can be defined as a data structure used as container which can hold variables of different types.

On other hand Array is a type of data structure used as container which can hold variables of same type and do not support multiple data type variables.

2

Memory Allocation

Memory allocation for input data in structure does not necessary to be in consecutive memory location.

While in case of array the input data stored in contiguous memory allocation which implies that array stores data in such memory model where it assigns consecutive memory blocks (that is, memory blocks having consecutive addresses).

3

Accessibility

In order to access the element in Structure we require to have the name of that element i.e it is mandatory to have element name for its retrieval from Structure.

On other hand in case of Array we can access the element by index.

4

Pointer

Structure do not have concept of Pointer internally.

On other hand in case of Array it internally implements Pointer which always points to the first element of Array.

5

Instantiation

Structure object can be created after declaration later in the program.

On other hand in case of Array we can't create its object after declaration.

6

DataType

Structure supports multiple data-type variables as input.

On other hand in case of Array we can't have different data-type variable as input as it only supports same type data variables.

7

Performance

Structure due to use defined data type become slow in performance as access and searching of element is slower in Structure as compare to Array.

On other hand in case of Array access and searching of element is faster and hence better in performance.

 



Union

 

35.What is union?

Ans

Union can be defined as a user-defined data type which is a collection of different variables of different data types in the same memory location. The union can also be defined as many members, but only one member can contain a value at a particular point in time.

 

Union is a user-defined data type, but unlike structures, they share the same memory location.

 

Syntax :

union [union tag] {

   member definition;

   member definition;

   ...

   member definition;

} [one or more union variables]; 


 

36.Difference between structure and union?

Ans

BASIS OF COMPARISON

STRUCTURE

UNION

Basic

The separate memory location is allotted to each member of the 'structure'.

All members of the 'union' share the same memory location.

Declaration

struct struct_name{
type element1;
type element2;
.
.
} variable1, variable2, ...;

union u_name{
type element1;
type element2;
.
.
} variable1, variable2, ...;

keyword

'struct'

'union'

Size

Size of Structure= sum of size of all the data members.

Size of Union=size of the largest members.

Store Value

Stores distinct values for all the members.

Stores same value for all the members.

At a Time

A 'structure' stores multiple values, of the different members, of the 'structure'.

A 'union' stores a single value at a time for all members.

Way of Viewing

Provide single way to view each memory location.

Provide multiple way to to view same memory location.

Anonymous feature

No Anonymous feature.

Anonymous union can be declared.




Function

 

37.What is function?

Ans

A function is a block of code that performs a specific task.

In c, we can divide a large program into the basic building blocks known as function. The function contains the set of programming statements enclosed by {}. A function can be called multiple times to provide reusability and modularity to the C program. In other words, we can say that the collection of functions creates a program.

 

Syntax to create use-defined function :

 

Return_type  function_name (argument1,argument2,….(optional)){

             Statements/Expressions;

             Return {value};    // (only if return type of function is not void)

}

 

Syntax to call function :

Function_name (arguments (if any));

 

 

38.Types of  functions?

Ans

Types of function :

 

1)    Standard library functions

 

The standard library functions are built-in functions in C programming.

These functions are defined in header files.

 

For example,

The printf() is a standard library function to send formatted output to the screen (display output on the screen). This function is defined in the stdio.h header file.

Hence, to use the printf()function, we need to include the stdio.h header file using #include <stdio.h>.

 

The sqrt() function calculates the square root of a number. The function is defined in the math.h header file. 

 

2)    User-defined functions

You can also create functions as per your need. Such functions created by the user are known as user-defined functions.

 

39.Advantages of function.

Ans

1)    The program will be easier to understand, maintain and debug.

2)    Reusable codes that can be used in other programs

3)    A large program can be divided into smaller modules. Hence, a large project can be divided among many programmers.

 

40.Math functions?

Ans

C Programming allows us to perform mathematical operations through the functions defined in <math.h> header file. The <math.h> header file contains various methods for performing mathematical operations such as sqrt(), pow(), ceil(), floor() etc.

 

C Math functions :

No.

Function

Description

1)

ceil(number)

rounds up the given number. It returns the integer value which is greater than or equal to given number.

2)

floor(number)

rounds down the given number. It returns the integer value which is less than or equal to given number.

3)

sqrt(number)

returns the square root of given number.

4)

pow(base, exponent)

returns the power of given number.

5)

abs(number)

returns the absolute value of given number.

 



Recursion

 

41.What is recursion?

Ans

Recursion is the process which comes into existence when a function calls a copy of itself to work on a smaller problem. Any function which calls itself is called recursive function, and such function calls are called recursive calls.

 

Example

Find factorial of number :

 

#include <stdio.h>

#include <conio.h>

 

int factorial(int n)

{

    if (n == 0 || n == 1)

    {

        return 1;

    }

    else

    {

        return n * factorial(n - 1);

    }

}

 

int main()

{

 

    int n = 5;

    printf("Factorial of %d is %d.", n, factorial(n));

    return 0;

}

 



Pointer


42.What is pointer?

Ans

The pointer in C language is a variable which stores the address of another variable. This variable can be of type int, char, array, function, or any other pointer.

 

To access address of a variable to a pointer, we use the unary operator & (ampersand) that returns the address of that variable.

 

One more operator is unary * (Asterisk) which is used for two things :

§  To declare a pointer variable: When a pointer variable is declared in C/C++, there must be a * before its name.

§  To access the value stored in the address we use the unary operator (*) that returns the value of the variable located at the address specified by its operand. This is also called Dereferencing.

 

Ex. int n = 10;  

int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer

 

            Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol). It is also known as indirection pointer used to dereference a pointer.

int *a;//pointer to int 

char *c;//pointer to char

 

43.Benefit of pointer?

Ans

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees, etc. and used with arrays, structures, and functions.

2) We can return multiple values from a function using the pointer.

3) It makes you able to access any memory location in the computer's memory.

 

Usage of pointer

There are many applications of pointers in c language.

 

1) Dynamic memory allocation

 

In c language, we can dynamically allocate memory using malloc() and calloc() functions where the pointer is used.

 

2) Arrays, Functions, and Structures

 

Pointers in c language are widely used in arrays, functions, and structures. It reduces the code and improves the performance.

 



Static keyword in C


44. Static keyword in C.

Ans

The static keyword in C is a storage-class specifier. It has different meanings, depending on the context. Inside a function it makes the variable to retain its value between multiple function calls. Outside of a function it restrains the visibility of the function or variable to the current file (compilation unit).

 

Syntax for static variable :

static <variable type> <variable name>;

<variable type> static <variable name>;

 

Syntax for static function :

static <function type> <function name>();

<function type> static <function name>();

 

§  Static variable

In C, inside a function, we use the static modifier to declare variables with static storage duration. Such variables retain their value throughout multiple calls of the function. These variables are initialized only once at compile time. Their life time matches the life time of our program. Example,

 

#include <stdio.h>

#include <conio.h>

 

void printB()

{

    static int b = 10;

    printf("value of b : %d\n", b);

    b += b; // b = b + b; (b = 10 + 10)

}

 

int main()

{

    printB();

    printB();

    return 0;

}

 

Output :

 

value of b : 10

value of b : 20

 

§  Static function

The static keyword is used before the function's name to make any function as the static function. And the scope of the static function in C is limited to its object files or only a program. It means that the static function is only visible to its program files and restricts other files or programs from accessing the static function.

 

Static function in C

Syntax

 

<function data_type> static <function_ name> ( ){} 

or 

static int function_name () 

{ 

// define the statement to be executed 

} 

 

1)    A static keyword can be used before the name of a function to make it static.

2)    However, the scope of the static function is throughout the program only. It means the static function can be called inside the same program or file.

3)    If we try to access the static function from another file, it throws an error.

4)    We can make a global function as the static by adding the static before the function name of a program.


Comments