[go: up one dir, main page]

0% found this document useful (0 votes)
14 views15 pages

C Important Questions

The document provides a comprehensive overview of various programming concepts, including the differences between call by value and call by reference, the structure and usage of for loops, and methods for returning multiple values from functions. It also discusses file pointers, storage classes in C, and the distinctions between recursion and iteration, as well as between break and continue statements. Additionally, it covers C tokens, self-referential structures, and the passing of arrays to functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views15 pages

C Important Questions

The document provides a comprehensive overview of various programming concepts, including the differences between call by value and call by reference, the structure and usage of for loops, and methods for returning multiple values from functions. It also discusses file pointers, storage classes in C, and the distinctions between recursion and iteration, as well as between break and continue statements. Additionally, it covers C tokens, self-referential structures, and the passing of arrays to functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 15

1.

Comparison between Call by Value and Call by Reference in Programming:

Call by Value Call by Reference

Purpose To pass arguments to another function To pass arguments to another function

Reference the location or address of


A copy of actual arguments is passed to
Arguments the actual arguments is passed to the
respective formal arguments
formal arguments

Any changes made in the formal


Changes are made in the own personal arguments will also reflect in the
Changes copy. Changes made inside the function actual arguments. Changes made
are not reflected on other functions inside the function are reflected
outside the function as well.

Value modification Original value is not modified. Original value is modified.

Actual and formal arguments will be Actual and formal arguments will be
Memory Location
created in different memory location created in same memory location

Actual arguments are not safe. They


Actual arguments remain safe, they can be accidentally modified. Hence
Safety
cannot be modified accidentally. care is required when handling
arguments.

Example #include <stdio.h> #include <stdio.h>


void swapByValue(int, int);
int main() void swapByReference(int*, int*); int
{ main()
int n1 = 10, n2 = 20;
swapByValue(n1, n2); {
printf("n1: %d, n2: %d\n", n1, n2);
} int n1 = 10, n2 = 20;

void swapByValue(int a, int b) swapByReference(&n1, &n2);


{
int t; printf("n1: %d, n2: %d\n", n1, n2);
t = a; a = b; b = t;
}
}

void swapByReference(int *a, int *b)

int t;

t = *a; *a = *b; *b = t;
OUTPUT
======
}
n1: 10, n2: 20
OUTPUT

======

n1: 20, n2: 10

2. Explain working of for loop with suitable example.

Basic syntax to use ‘for’ loop is:

for (initialization; test condition ; inc/dec)

statement 1;

statement 2;

..

..

 Initialization is the initialization of counter of loop.

 Test Condition is any logical condition that controls the number of times the loop statements are
executed.

 Increment/decrement shows update of counter.

Flowchart:
Working:

It is noted that when ‘for’ loop execution starts, first variable initialization is done, then condition
is checked before execution of statements; if and only if condition is TRUE, statements are
executed; after all statements are executed, iteration of counter of loop is done either increment or
decrement.

Example:

#include <stdio.h>

int main ()

int i ;
for (i=1; i < =5; i++)
{
printf("%d\t",i);
}
Output:

1 2 3 4 5

3. Can a function return more than one value? If yes, how?

Yes, function can return multiple values by using following ways:


i. By using pointer

We can pass multiple addresses of variables as input parameters to a function. Inside function
body, we can store the return values at the passed memory locations.

#include <stdio.h>

void swapByReference(int*, int*); int main()

int n1 = 10, n2 = 20;

swapByReference(&n1, &n2);

printf ("n1: %d, n2: %d\n", n1, n2);

void swapByReference (int *a, int *b)

int t;

t = *a; *a = *b; *b = t;

OUTPUT

======

n1: 20, n2: 10

ii. By using structure

Structure contains different types of data under single name so if we return structure object
then we can return multiple values using it.

#include<stdio.h>

struct data

int sum, product;

};
struct data myStruct;

myStruct getSumAndProduct(int a, int b){

myStruct s;

s.sum = a + b;

s.product = a * b;

return s;// returns both sum and product

int main()

int a, b;

myStruct result;

printf("Enter two integers\n");

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

result = getSumAndProduct(a, b);

printf("Sum = %d\nProduct = %d", result.sum, result.product);

return 0;

In above example, while returning object s , the values under it, sum and product will be
returned.

3. What is file pointer (Significance of file pointer)? Discuss about file opening modes.

File Pointer:

A file pointer is a pointer to a structure, which contains information about the file, including its
name, current position of the file, whether the file is being read or written, and whether errors or
end of the file have occurred.

Syntax: FILE *fp;

File opening modes in C


Mode Meaning

r Open a text file reading

W Create a text file writing

a Append to a text file

Rb Open a binary file for reading

Wb Create a binary file for writing

ab Append to a binary file

r+ Open a text file read/write

w+ Create a text file for read or write

a+f Append or create a text file for read/write

r+b Open a binary file for read/write

w+b Create a binary file for read/write

a+b Append a binary for read/write

4. Difference between macros and functions.

Difference between recursion and iteration

Recursion Iteration
Iteration is achieved by
Recursion refers to a an iterative function
recursive function in which loops to repeat
Definition
which it calls itself again some section of the code.
to repeat the code.

A base case needs to be A termination condition


Important point
determined needs to be determined

Performance Comparatively slow Comparatively fast

Memory Usage Comparatively more Comparatively less

Code Smaller Longer

Infinite recursion is
Infinite looping consumes
Infinite repetition capable of crashing the
CPU cycles repeatedly
system

Structure Selection Repetition

Local variables Not required Required

C Tokens

 C tokens are the basic buildings blocks in C language which are constructed together to write a C
program.

 Each and every smallest individual units in a C program are known as C tokens.

C tokens are of six types. They are,

1. Keywords (eg: int, while),

2. Identifiers (eg: main, total),


3. Constants (eg: 10, 20),

4. Strings (eg: “total”, “hello”),

5. Special symbols (eg: (), {}),

6. Operators (eg: +, /,-,*)

Selective and Repetitive Statements

A selection statement selects among a set of statements depending on the value of a controlling
expression. The selection statements are the if statement and the switch statement.

A repetitive statements are used to execute same statements repeatedly. (for, while, do…while).

Difference between entry controlled and exit controlled loop

No. Topics Entry controlled loops Exit controlled loops

01 Test condition Test condition appears at the Test condition appears at the end.
beginning.

02 Control Control variable is counter Control variable is counter &


variable variable. sentinel variable.

03 Execution Each execution occurs by testing Each execution except the first one
condition. occurs by testing condition.

04 Examples ======== ======

sum = 0; do

n = 1; {

while (n <= 10) printf(“Input a number.\n”);

{ scanf("%d", &num);

sum = sum + n*n; }

n = n+ 1; while(num>0);

} ======

========
Difference between break and continue statement

BASIS FOR
BREAK CONTINUE
COMPARISON

Task It terminates the execution of It terminates only the current iteration of the
remaining iteration of the loop. loop.

Control after 'break' resumes the control of the 'continue' resumes the control of the program to
break/continue program to the end of loop enclosing the next iteration of that loop enclosing 'continue'.
that 'break'.

Causes It causes early termination of loop. It causes early execution of the next iteration.

Continuation 'break' stops the continuation of 'continue' do not stops the continuation of loop, it
loop. only stops the current iteration.

Other uses 'break' can be used with 'switch', 'continue' can not be executed with 'switch' and
'label'. 'labels'.

Example int main(){ int main(){


int i; int i;
for(i=0; i<10; i++) for(i=0; i<10; i++)
{ {
if(i==5) if(i==5)
{ {
printf("\nComing out of loop when printf("\nSkipping %d from display using
i=5 \n"); continue \n", i);
break; continue;
} }
printf("%d", i); printf("%d", i);
} }
return 0; getch();
} }
Output Output
BASIS FOR
BREAK CONTINUE
COMPARISON

 Explain self referential structure with suitable example.

A self referential data structure is essentially a structure definition which includes at least one member
that is a pointer to the structure of its own kind. A chain of such structures can thus be expressed as
follows.

struct name {

member 1;

member 2;

...

struct name *pointer; // self referential structure

};

The above illustrated structure prototype describes one node that comprises of two logical segments. One
of them stores data/information and the other one is a pointer indicating where the next component can be
found. .Several such inter-connected nodes create a chain of structures.

The following figure depicts the composition of such a node. The figure is a simplified illustration of
nodes that collectively form a chain of structures or linked list.

Such self-referential structures are very useful in applications that involve linked data structures, such as
lists and trees.

Explain passing arrays to function with suitable example.

While passing arrays as arguments to the function, only the name of the array is passed (,i.e, starting
address of memory area is passed as argument).
“C program to pass an array containing age of person to a function. This function should find
average age and display the average age in main function.”

#include <stdio.h>

float average(float age[]);

int main()

float avg, age[] = { 23.4, 55, 22.6, 3, 40.5, 18 };

avg = average(age); /* Only name of array is passed as argument. */

printf("Average age=%.2f", avg);

return 0;

float average(float age[])

int i;

float avg, sum = 0.0;

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

sum += age[i];

avg = (sum / 6);

return avg;

Explain storage class in C.


In C language, each variable has a storage class which decides the following things:

 scope i.e where the value of the variable would be available inside a program.
 default initial value i.e if we do not explicitly initialize that variable, what will be its default
initial value.

 lifetime of that variable i.e for how long will that variable exist.

The following storage classes are most oftenly used in C programming,

1. Automatic variables

2. External variables

3. Static variables

4. Register variables

Automatic variables: auto

Scope: Variable defined with auto storage class are local to the function block inside which they
are defined.

Default Initial Value: Any random value i.e garbage value.

Lifetime: Till the end of the function/method block where the variable is defined.

A variable declared inside a function without any storage class specification, is by default
an automatic variable. They are created when a function is called and are
destroyed automaticallywhen the function's execution is completed. Automatic variables can
also be called local variablesbecause they are local to a function. By default they are
assigned garbage value by the compiler.

External or Global variable

Scope: Global i.e everywhere in the program. These variables are not bound by any function, t
hey are available everywhere.

Default initial value: 0(zero).

Lifetime: Till the program doesn't finish its execution, you can access global variables.

A variable that is declared outside any function is a Global Variable. Global variables remain
available throughout the program execution. By default, initial value of the Global variable is
0(zero). One important thing to remember about global variable is that their values can be
changed by any function in the program.

#include<stdio.h>

int number; // global variable

void main()

number = 10;

printf("I am in main function. My value is %d\n", number);

O/P: am in main function. My value is 10

Static variables
Scope: Local to the block in which the variable is defined

Default initial value: 0(Zero).

Lifetime: Till the whole program doesn't finish its execution.

A static variable tells the compiler to persist/save the variable until the end of program. Instead of
creating and destroying a variable every time when it comes into and goes out of
scope, staticvariable is initialized only once and remains into existence till the end of the
program. A staticvariable can either be internal or external depending upon the place of
declaration. Scope of internal static variable remains inside the function in which it is
defined. External static variables remain restricted to scope of file in which they are declared.

They are assigned 0 (zero) as default value by the compiler.


O/P: 1 2 3

Static variable
Scope: Local to the function in which it is declared.

Default initial value: Any random value i.e garbage value

Lifetime: Till the end of function/method block, in which the variable is defined.

Register variables inform the compiler to store the variable in CPU register instead of memory.
Register variables have faster accessibility than a normal variable. Generally, the frequently used
variables are kept in registers. But only a few variables can be placed inside registers. One
application of register storage class can be in using loops, where the variable gets used a number
of times in the program, in a very short span of time.

NOTE: We can never get the address of such variables.

Syntax :

register int number;

Even though we have declared the storage class of our variable number as register, we cannot
surely say that the value of the variable would be stored in a register. This is because the number
of registers in a CPU are limited. Also, CPU registers are meant to do a lot of important work.
Thus, sometimes they may not be free. In such scenario, the variable works as if its storage class
is auto.

You might also like