Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

c Programming

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 38

History of C Language

C language has evolved from three different structured language ALGOL, BCPL and B Language.
It uses many concepts from these languages while introduced many new concepts such as
datatypes, struct, pointer etc. In 1988, the language was formalised by American National
Standard Institute(ANSI). In 1990, a version of C language was approved by the International
Standard Organisation(ISO) and that version of C is also referred to as C89.

The idea behind creating C language was to create an easy language which requires a simple
compiler and enables programmers to efficiently interact with the machine/system, just like
machine instructions.
C language compiler converts the readable C language program into machine instruction.

Why C Language is so popular?


C language is a very good language to introduce yourself to the programming world, as it is a
simple procedural language which is capable of doing wonders.
Programs written in C language takes very less time to execute and almost executes at the
speed of assembly language instructions.
Initially C language was mainly used for writing system level programs, like designing operating
systems, but there are other applications as well which can be very well designed and
developed using C language, like Text Editors, Compilers, Network Drivers etc.
Latest Version of C
The current latest version of C language is C11, which was introduced in 2011. It is supported by
all the standard C language compilers.
Many new features have been introduced in this version and an overall attempt to improve
compatibility of the C language with C++ language has been made. We will learn about
the C11edition, once we are done with learning C language, towards the end of this tutorial
series.
Features of C Language

 It is a robust language with rich set of built-in functions and operators that can be used to
write any complex program.
 The C compiler combines the capabilities of an assembly language with features of a high-level
language.
 Programs Written in C are efficient and fast. This is due to its variety of data type and powerful
operators.
 It is many time faster than BASIC.
 C is highly portable this means that programs once written can be run on another machines
with little or no modification.
 Another important feature of C program, is its ability to extend itself.
 A C program is basically a collection of functions that are supported by C library. We can also
create our own function and add it to C library.
 C language is the most widely used language in operating systems and embedded system
development today.

First C Program and its Structure


Lets see how to write a simple and most basic C program:
#include <stdio.h>
int main()
{
printf("Hello,World"); //single line comment
return 0;
/*
multi
line
comments
/*
}

Hello,World

Different Parts of C Program

 Pre-processor
 Header file
 Function
 Variables
 Statements & expressions
 Comments

All these are essential parts of a C language program.

Pre-processor
#include is the first word of any C program. It is also known as a pre-processor. The task of a
pre-processor is to initialize the environment of the program, i.e to link the program with the
header files required.
So, when we say #include <stdio.h>, it is to inform the compiler to include the stdio.h header file
to the program before executing it.

Header File
A Header file is a collection of built-in(readymade) functions, which we can directly use in our
program. Header files contain definitions of the functions which can be incorporated into any C
program by using pre-processor #include statement with the header file. Standard header files
are provided with each compiler, and covers a range of areas like string handling, mathematical
functions, data conversion, printing and reading of variables.
With time, you will have a clear picture of what header files are, as of now consider as a
readymade piece of function which comes packaged with the C language and you can use them
without worrying about how they work, all you have to do is include the header file in your
program.
To use any of the standard functions, the appropriate header file must be included. This is done
at the beginning of the C source file.
For example, to use the printf() function in a program, which is used to display anything on the
screen, the line #include <stdio.h> is required because the header file stdio.h contains
the printf() function. All header files will have an extension .h

main() Function
main() function is a function that must be there in every C program. Everything inside this
function in a C program will be executed. In the above example, int written before
the main() function is the return type of main() function. we will discuss about it in detail later.
The curly braces { } just after the main() function encloses the body of main() function.

Comments
We can add comments in our program to describe what we are doing in the program. These
comments are ignored by the compiler and are not executed.
To add a single line comment, start it by adding two forward slashses // followed by the
comment.
To add multiline comment, enclode it between /* .... */, just like in the program above.

Return Statement - return 0;


A return statement is just meant to define the end of any C program.
All the C programs can be written and edited in normal text editors like Notepad or Notepad++
and must be saved with a file name with extension as .c
If you do not add the extension .c then the compiler will not recognise it as a C language
program file.

Compile and Run C Program


To compile and run a C language program, you need a C compiler. To setup a C language
compiler in your Computer/laptop, there are two ways:

1. Download a full fledged IDE like Turbo C or Microsoft Visual C++, which comes along with a C
language compiler.
2. Or, you use any text editor to edit the program files and download the C compiler separately.

Here we have a simple video, explaining how to setup Tubrbo C/C++ for writing, compiling and
running C programs.

C Language Basic Syntax Rules


C language syntax specify rules for sequence of characters to be written in C language. In simple
language it states how to form statements in a C language program - How should the line of
code start, how it should end, where to use double quotes, where to use curly brackets etc.
The rule specify how the character sequence will be grouped together, to form tokens. A
smallest individual unit in C program is known as C Token. Tokens are either keywords,
identifiers, constants, variables or any symbol which has some meaning in C language. A C
program can also be called as a collection of various tokens.
In the following program,
#include <stdio.h>
int main()
{
printf("Hello,World");
return 0;
}

if we take any one statement:


printf("Hello,World");

Then the tokens in this statement are→ printf, (, "Hello,World", ) and ;.


So C tokens are basically the buildingblocks of a C program.

Semicolon ;
Semicolon ; is used to mark the end of a statement and beginning of another statement.
Absence of semicolon at the end of any statement, will mislead the compiler to think that this
statement is not yet finished and it will add the next consecutive statement after it, which may
lead to compilation(syntax) error.
#include
int main()
{
printf("Hello,World")
return 0;
}
In the above program, we have omitted the semicolon from the printf("...") statement, hence
the compiler will think that starting from printf uptill the semicolon after return 0 statement, is
a single statement and this will lead to compilation error.
Comments
Comments are plain simple text in a C program that are not compiled by the compiler. We write
comments for better understanding of the program. Though writing comments is not
compulsory, but it is recommended to make your program more descriptive. It make the code
more readable.
There are two ways in which we can write comments.

1. Using // This is used to write a single line comment.


2. Using /* */: The statements enclosed within /* and */ , are used to write multi-line comments.

Example of comments :
// This is a comment

/* This is a comment */

/* This is a long
and valid comment */

// this is not
a valid comment

Some Basic Syntax Rule for C Program

 C is a case sensitive language so all C instructions must be written in lower case letter.
 All C statement must end with a semicolon.
 Whitespace is used in C to describe blanks and tabs.

Whitespace is required between keywords and identifiers.

Explain Algorithm in detail.


Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a
certain order to get the desired output. Algorithms are generally created independent of
underlying languages, i.e. an algorithm can be implemented in more than one programming
language.

Characteristics of an Algorithm
Not all procedures can be called an algorithm. An algorithm should have the following
characteristics −

 Unambiguous − Algorithm should be clear and unambiguous. Each of its steps (or
phases), and their inputs/outputs should be clear and must lead to only one meaning.
 Input − An algorithm should have 0 or more well-defined inputs.
 Output − An algorithm should have 1 or more well-defined outputs, and should match the
desired output.
 Finiteness − Algorithms must terminate after a finite number of steps.
 Feasibility − Should be feasible with the available resources.
 Independent − An algorithm should have step-by-step directions, which should be
independent of any programming code.

How to Design an Algorithm?

In order to write an algorithm, the following things are needed as a pre-requisite:

1. The problem that is to be solved by this algorithm i.e. clear problem definition.
2. The constraints of the problem must be considered while solving the problem.
3. The input to be taken to solve the problem.
4. The output to be expected when the problem is solved.
5. The solution to this problem, is within the given constraints

Advantages of Algorithms:

 It is easy to understand.
 An algorithm is a step-wise representation of a solution to a given problem.
 In Algorithm the problem is broken down into smaller pieces or steps hence, it is easier for
the programmer to convert it into an actual program.
Disadvantages of Algorithms:

 Writing an algorithm takes a long time so it is time-consuming.


 Understanding complex logic through algorithms can be very difficult.
 Branching and Looping statements are difficult to show in Algorithms
Explain in detail the various DATA TYPES used in C language.
Ans : A program usually contains different types of data types (integer, float, character etc.)
and need to store the values being used in the program. C language is rich of data types. A C
programmer has to employ proper data type as per his requirements. C has different data
types for different types of data and can be broadly classified as:
1. Primary Data Types
2. Secondary Data Types

 Primary Data Types:


1. Integer Data Types: An integer is a whole number (a number without a fractional part). It
can be positive or negative numbers like 1, -2, 3, etc., or zero. The sizes of the integer
variables depend on the hardware and operating system of the computer. C has three
classes of integer storage namely short int, int and long int. All three data types have signed
and unsigned forms.
Syntax:
int <variable name>;
Integer Data Type Memory Allocation:

2. Floating point numbers: Floating point numbers are numbers with a decimal point. The
float type can take large floating point numbers with a small degree of precision (Precision is
simply the number of decimal places to which a number can be calculated. Floating point
numbers are denoted by the keyword float.
Syntax: float <variable name>; Floating Point Data Type Memory Allocation:

3. Character Data Type: Character type variable can hold a single character and are declared
by using the keyword char. As there are singed and unsigned int (either short or long), in the
same way there are signed and unsigned chars; both occupy 1 byte each, but having
different ranges. Unsigned characters have values between 0 and 255, signed characters
have values from –128 to 127.
Syntax:
char <variable name>;
char ch = ‘a’;
4. Void Type:
The void type has no values therefore we cannot declare it as variable. The void data type is
usually used with function to specify its type. C program we declared “main()” as void type
because it does not return any value.
 Secondary Data Type
Arrays
Array is basically a collection of same data types. Array is a group of same type of data
elements that have been given a common name.
Structures
Some times we require a data in terms of records. In array we take data of same type but in
the form of records we must require a data type in which different types of data can be
clubbed together i.e int,float and char.
Union
Unions are also the derived data types almost same as that of structures. They are declared
in the same way as structures. The only difference is that in structures, each variable has the
separate memory allocation for each element but in union variables use the same memory
location.
Pointers
Pointers are also the derived data type basically used to store the memory address of a data
type.

What are functions? Differentiate between Call by value and Call by reference with the
help of example.
Ans: Function in programming is a segment that groups a number of program statements to
perform specific task.A C program has at least one function main( ).
Without main() function, there is technically no C program.
Types of C functions
Basically, there are two types of functions in C on basis of whether it is defined by user or
not.
 Library function
 User defined function
Syntax: return-type function-name(parameters)
{
declarations
statements
return value;
}
Call by Value : If we call a function in C by passing values of variables as the
parameters/arguments to the function then such type of function call is known as Call by
value.
During call by value method the ‘value’ of each of the actual arguments in the calling
function is copied into corresponding formal arguments of the called function. In this
method, the changes made to the formal arguments in the called function have no effect on
the values of actual arguments in the calling function.
Program Code to demonstrate call by value method
#include<stdio.h>
int sum(int x, int y); /*function declaration*/
int main()
{
int num1, num2, add;
printf(” Enter any two numbers \n”);
scanf(“%d, %d”, &num1, &num2);
add = sum(num1, num2); /*Calling the add function */
return 0;
}
int add( int x, int y) /* Function Definitions */
{
int sum;
sum=x+y;
return sum;
}

Call by Reference : instead of passing values of variables as parameters to the function, if


we pass address of those variables and somehow able to access data contained inside those
addresses then we will be able to call functions. Concepts of Pointers provide us the
advantage of manipulating addresses. So calling a function by passing addresses of variables
as the parameters to the function is known as Call by Reference.
During call by reference, the addresses of actual arguments in the calling function are
copied into the formal arguments of the called function. In this method we can alter the
actual arguments by doing some changes to formal arguments.
Program code to demonstrate call by reference method
#include<stdio.h>
void swap(int *, int *); /*function declarations */
int main();
{
int a=5, b=6;
swap(&a, &b); /*Calling functions by reference //passing the address */
printf(“a=%d b=%d \n”,a,b);
return 0;
}
void swap ( int *x, int *y) /*Function Definitions */
{
int temp;
temp= *x;
*x=*y;
*y=temp;
}
What are pointers? How pointers are declared? Explain the syntax. With the help of
example, explain the working of pointer to pointer.
Ans : pointers are special variables that can hold the address of a variable. Since they store
memory address of a variable, the pointers are very commonly said to “point to variables”

A pointer is declared as :
<pointer type> *<pointer-name>
In the above declaration :
1. pointer-type : It specifies the type of pointer. It can be int,char, float etc. This type specifies
the type of variable whose address this pointer can store.
2. pointer-name : It can be any name specified by the user.
3. Following are the valid pointer declaration:
4. int *ip; /* pointer to an integer */

Working of Pointers to pointers


C++ allows the use of pointers that point to pointers, that these, in its turn, point to data (or
even to other pointers). The syntax simply requires an asterisk (*) for each level of
indirection in the declaration of the pointer:
1 char a;
2 char * b;
3 char ** c;
4 a = 'z';
5 b = &a;
6 c = &b;
This, assuming the randomly chosen memory locations for each variable of 7230, 8092,
and 10502, could be represented as:

With the value of each variable represented inside its corresponding cell, and their
respective addresses in memory represented by the value under them.
The new thing in this example is variable c, which is a pointer to a pointer, and can be used
in three different levels of indirection, each one of them would correspond to a different
value:
 c is of type char** and a value of 8092
 *c is of type char* and a value of 7230
 **c is of type char and a value of 'z'
4. Explain difference between structure and union by giving appropriate example.
STRUCTURE UNION
1.The keyword struct is used 1. The keyword union is used
to define a structure to define a union.
2. When a variable is associated with 2. When a variable is associated with
a structure, the compiler allocates a union, the compiler allocates
the memory for each member. The the memory by considering the size
size of structure is greater than or of the largest memory. So, size of
equal to the sum of sizes of its union is equal to the size of largest
members. The smaller members may member.
end with unused slack bytes.
3. Each member within a structure is 3. Memory allocated is shared by
assigned uniquestorage area individual members of union.
of location.
4. The address of each member will 4. The address is same for all the
be in ascending order This indicates members of a union. This indicates
that memory for each member will that every member begins at the
start at different offset values. same offset value.
5 Altering the value of a member will 5. Altering the value of any of the
not affect other members of the member will alter other member
structure. values.
6. Individual member can be accessed 6. Only one member can be accessed
at a time at a time.
7. its Syntax : 7. Its Syntax is:
struct struct_name union union_name
{ {
structure element 1; union element 1;
structure element 2; union element 2;
---------- ----------
---------- ----------
structure element n; union element n;
}struct_var_nm; }union_var_nm;

8. Several members of a structure can 8. Only the first member of a union


initialize at once. can be initialized.

What are the various types of operators in c? Define their usage with appropriate
examples.
 Arithmetic Operators
Operato
Meaning
r
addition or unary
+
plus
subtraction or
-
unary minus
* multiplication
/ division
remainder after
% division( modulo
division)
 Increment and decrement operators
In C, ++ and -- are called increment and decrement operators respectively. Both of these
operators are unary operators, i.e, used on single operand. ++ adds 1 to operand
and -- subtracts 1 to operand respectively. For example:
Let a=5 and b=10
a++; //a becomes 6
a--; //a becomes 5
 Assignment Operators
The most common assignment operator is =. This operator assigns the value in right side to
the left side. For example:
var=5 //5 is assigned to var
a=c; //value of c is assigned to a
5=c; // Error! 5 is a constant.
Operator Meaning Example
= a=b a=b
+= a+=b a=a+b
-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b
 Relational Operator
Relational operators checks relationship between two operands. If the relation is true, it
returns value 1 and if the relation is false, it returns value 0. For example:
a>b
Here, > is a relational operator. If a is greater than b, a>b returns 1 if not then, it returns 0.
Relational operators are used in decision making and loops in C programming.
Operato
Meaning Example
r
5==3 returns
== Equal to
false (0)
5>3 returns
> Greater than
true (1)
5<3 returns
< Less than
false (0)
5!=3 returns
!= Not equal to
true(1)
Greater than or 5>=3 returns
>=
equal to true (1)
Less than or equal 5<=3 return
<=
to false (0)
 Logical Operators
Logical operators are used to combine expressions containing relation operators. In C, there
are 3 logical operators:
Operato
Meaning Example
r
If c=5 and d=2 then,
Logial
&& ((c==5) && (d>5)) returns
AND
false.
If c=5 and d=2
Logical
|| then, ((c==5) || (d>5))
OR
returns true.
Logical If c=5 then, !(c==5)
!
NOT returns false.
 Conditional Operator
Conditional operator takes three operands and consists of two symbols ? and : . Conditional
operators are used for decision making in C. For example:
c=(c>0)?10:-10;
If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.
 Bitwise Operators
A bitwise operator works on each bit of data. Bitwise operators are used in bit level
programming.
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right

What is an array? Explain the process to read the values in array.


Array is a collection of homogenous data stored under unique name. The values in an array
is called as 'elements of an array.' These elements are accessed by numbers called as
'subscripts or index numbers.' Arrays may be of any variable type.
Array is also called as 'subscripted variable.'
Types of an Array:
1. One / Single Dimensional Array
2. Two Dimensional Array
Single / One Dimensional Array :
The array which is used to represent and store data in a linear form is called as 'single or one
dimensional array.'
Syntax:
<data-type> <array_name> [size];
Example:
int a[3] = {2, 3, 5};
char ch[20] = "TechnoExam" ;
Accessing array elements
scanf("%d",&age[2]);
/* statement to insert value in the third element of array age[]. */
printf("%d",age[0]);
/* statement to print first element of an array. */
/* C program to find the sum marks of n students using arrays */

#include <stdio.h>
int main(){
int marks[10],i,n,sum=0;
printf("Enter number of students: ");
scanf("%d",&n);
for(i=0;i<n;++i){
printf("Enter marks of student%d: ",i+1);
scanf("%d",&marks[i]);
sum+=marks[i];
}
printf("Sum= %d",sum);
return 0;
}

What is the use of the Recursion? How it is different from the other functions?
A function that calls itself is known as recursive function and the process of calling function
itself is known as recursion in C programming. A function is called “recursive” if a statement
within body of that function calls the same function. On the other hand A function in C
language is a block of code that performs a specific task. It has a name and it is reusable i.e.
it can be executed from as many different parts in a C Program as required. It also optionally
returns a value to the calling program
attributes of “recursive function”:-
1. A recursive function is a function which calls itself.
2. The speed of a recursive program is slower because of stack overheads. (This attribute is
evident if you run above C program.)
3. A recursive function must have recursive conditions, terminating conditions, and recursive
expressions.
#include<stdio.h>
#include<conio.h>
int factorial(int);
int factorial (int i)
{
int f;
if(i==1)
return 1;
else
f = i* factorial (i-1);
return f;
}
void main()
{
int x;
clrscr();
printf("Enter any number to calculate factorial :");
scanf("%d",&x);
printf("\nFactorial : %d", factorial (x));
getch();
}

Write in detail about various storage classes available in C.


A storage class defines the scope (visibility) and life time of variables and/or functions within
a C Program.
There are following storage classes which can be used in a C Program
 auto
 register
 static
 extern
AUTOMATIC STORAGE CLASS: :in this automatic storage class,Variable is stored in memory.
Default value is garbage value. Scope is local to the blockLife is, with in the block in which
the variable is defined
Example 1:
main()
{
auto int i=10;
printf(“%d”,i);
}
Output: 10
REGISTER STORAGE CLASS: Variable is stored in CPU registers.Default value is garbage
value.Scope is local to the block. Life is,with in the block in which the variable is defined. We
can not use register storage class for all types of variables. For example:
register float f;
STATIC STORAGE CLASS: Variable is stored in memory. Default value is zero. Scope is local
to the block. Life is, value of the variable persists between different function calls.
Example :
main()
{
add();
add();
}
add()
{
static int i=10;
printf(“\n%d”,i);
i+=1;
}
Output:
10
11
EXTERNAL STORAGE CLASS: Variable is stored in memory. Default value is zero. Scope is
local to the block. Life is, as long as the program execution doesn’t come to an end.
Example :
int i=10;
main()
{
int i=2;
printf(“%d”,i);
display();
}
display()
{
printf(“\n%d”,i);
}
Output:
2
10

(a) Difference between Break and Continue.


Ans : break - The break statement is used to jump out of loop. After the break statement
control passes to the immediate statement after the loop. For break, break keyword is used.
E.g.
#include<stdio.h>
#include<conio.h>
Void main()
{
For(int i=0;i<=10;i++)
{
Printf(“%d”,i);
If(i==4)
Break;
}
}
continue - Using continue we can go to the next iteration in loop. The continue statement is
used to alter the sequence of execution. Instead of coming out of the loop like the break
statement did, the continue statement stops the current iteration and simply returns
control back to the top of the loop. E.g
#include<stdio.h>
#include<conio.h>
Void main()
{
For(int i=0;i<=10;i++)
{
Printf(“%d”,i);
If(i==4)
Continue;
}
}
(b) Explain difference between Do-while and while
Do-While While
1. In do while the statements are 1. the condition is
executed for the first time and tested first and then the statements
then the conditions are executed if the condition turns
out to
be true.
2. A do while is used for a block 2. while is more commonly used
of code that must be executed at because it test the condtion first.
least once.
3. A do while loop runs at least 3. while loop do not run in case the
once condition given is false
even though the the condition
given is false
4. 4. In a while loop the condition is
In a do-while loop the condition is first tested and if it returns true then
tested at the last. it goes in the loop
5. do while is exit control loop. 5. While loop is entry control loop
6.Syntax: 6. Syntax:
Do while loop :
{
Statements; while (condition)
}while(condition); {
Statements;
}
Explain different Control statements in C.
Ans: C provides two styles of flow control:
 Branching
 Looping
Branching is deciding what actions to take and looping is deciding how many times to take a
certain action.
a. Branching:
Branching is so called because the program chooses to follow one branch or another.
a. if statement: This is the simplest form of the branching statements.
It takes an expression in parenthesis and an statement or block of statements. if the
expression is true then the statement or block of statements gets executed otherwise these
statements are skipped. Syntax:
if (expression)
{
Block of statements;
}
b. If-else statement:
if (expression)
{
Block of statements;
}
else
{
Block of statements;
}
c. ? : Operator
The ? : operator is just like an if ... else statement except that because it is an operator you
can use it within expressions.
? : is a ternary operator in that it takes three values, this is the only ternary operator C has.
? : takes the following form:
Show Example
if condition is true ? then X return value : otherwise Y value;
d. switch.
Its purpose is to check for a value among a number of possible constant expressions. It is
something similar to concatenating if-else statements, but limited to constant expressions.
Its most typical syntax is:
switch (expression)
{
case constant1:
group-of-statements-1;
break;
case constant2:
group-of-statements-2;
break;
.
.
.
default:
default-group-of-statements
}
b. Iteration statements (loops)
Loops repeat a statement a certain number of times, or while a condition is fulfilled. They
are introduced by the keywords while, do, and for.
a. while loop
The most basic loop in C is the while loop.A while statement is like a repeating if statement.
Like an If statement, if the test condition is true: the statments get executed. The difference
is that after the statements have been executed, the test condition is checked again. If it is
still true the statements get executed again.This cycle repeats until the test condition
evaluates to false.
Basic syntax of while loop is as follows:
Show Example
while ( expression )
{
Single statement
or
Block of statements;
}
b. for loop
for loop is similar to while, it's just written differently. for statements are often used to
proccess lists such a range of numbers:
Basic syntax of for loop is as follows:
Show Example
for( expression1; expression2; expression3)
{
Single statement
or
Block of statements;
}

c. do...while loop
do ... while is just like a while loop except that the test condition is checked at the end of
the loop rather than the start. This has the effect that the content of the loop are always
executed at least once.
Basic syntax of do...while loop is as follows:
Show Example
do
{
Single statement
or
Block of statements;
}while(expression);
d. break and continue statements
C provides two commands to control how we loop:
 break -- exit form loop or switch.
 continue -- skip 1 iteration of loop.

What is Type Casting? Give example


Ans: Typecasting is a way to make a variable of one type, such as an int, act like another
type, such as a char, for one single operation. To typecast something, simply put the type of
variable you want the actual variable to act as inside parentheses in front of the actual
variable. (char)a will make 'a' function as a char.
For example:
#include <stdio.h>
int main()
{
printf( "%c\n", (char)65 );
getchar();
}

Define Identifiers.
Ans: In C programming, identifiers are names given to C entities, such as variables,
functions, structures etc. Identifier are created to give unique name to C entities to identify
it during the execution of program. For example:
int money;
int mango_tree;
Here, money is a identifier which denotes a variable of type integer. Similarly, mango_tree is
another identifier, which denotes another variable of type integer.

What is the purpose of strcat() and strcmp() functions?


Ans: strcat( ) function in C language concatenates two given strings. It concatenates source
string at the end of destination string.
Example :
strcat ( str2, str1 ); - str1 is concatenated at the end of str2.
strcpy( ) function copies contents of one string into another string.
Example:
strcpy ( str1, str2) – It copies contents of str2 into str1.

What is input, output function in C?


Ans: Input : In any programming language input means to feed some data into program.
This can be given in the form of file or from command line. C programming language
provides a set of built-in functions to read given input and feed it to the program as per
requirement. Scanf() function is used for input.
Output : In any programming language output means to display some data on screen,
printer or in any file. C programming language provides a set of built-in functions to output
required data. Printf() function is used for output.

What is use of getch() function in C program?


Ans: “The getch = get character. This function is used to get a single character input from
the user” during execution of program. It also force to wait the output to stay on screen
until any key pressed from keyboard.
Syntax:
For value input: Variable name= getch();
For screen holding at the end of program: getch();

Differentiate Compiler and Interpreter.


Ans: The interpreter takes one statement then translates it and executes it and then takes
another statement. While the compiler translates the entire program in one go and then
executes it.
Compiler generates the error report after the translation of the entire page while an
interpreter will stop the translation after it gets the first error.
Compiler takes a larger amount of time in analyzing and processing the high level language
code comparatively interpreter takes lesser time in the same process.

Define the term keyword.


Ans: Keywords are the reserved words used in programming. Each keywords has fixed
meaning and that cannot be changed by user. For example:
int money;
Here, int is a keyword that indicates, 'money' is of type integer.
As, C programming is case sensitive, all keywords must be written in lowercase. Some of the
keywords are: int, char, double, auto, break, if, else, do, continue, while, void, float, goto,
short, etc.
What is a pointer variable.
Ans: A pointer is a variable that stores a memory address. Pointers are used to store the
addresses of other variables or memory items. Pointers are very useful for another type of
parameter passing, usually referred to as Pass By Address. Pointers are essential for
dynamic memory allocation. Pointer declarations use the * operator.
int n; // declaration of a variable n
int * p; // declaration of a pointer, called p

Give the difference between getchar() and getch().


Ans: Getchar ( ) - It will accept a character from keyboard, displays immediately while typing
and we need to press Enter key for proceeding.
Getch ( ) - It just accepts a keystroke and never displays it and proceeds further. Normally
we use it at the end of the main ( ).

Why we use return statement?


Ans: The return statement terminates the execution of the current function and return
control to the calling function. Meaning, the return statement immediately ends the
function, ignoring everything else in the function after it is called. It immediately returns to
the calling function and continue from the point that it is called. Return also able to "return"
a value to the calling function.

Explain :
a. Difference between Structure and union.
Ans:
STRUCTURE UNION
1.The keyword struct is used to define a 1. The keyword union is used to define a
structure union.
2. When a variable is associated with a 2. When a variable is associated with a
structure, the compiler allocates the union, the compiler allocates
memory for each member. The size of the memory by considering the size of
structure is greater than or equal to the the largest memory. So, size of union is
sum of sizes of its members. The smaller equal to the size of largest member.
members may end with unused slack
bytes.
3. Each member within a structure is 3. Memory allocated is shared by
assigned unique storage area of individual members of union.
location.
4. The address of each member will be 4. The address is same for all the
in ascending order This indicates that members of a union. This indicates that
memory for each member will start at every member begins at the same offset
different offset values. value.
5 Altering the value of a member will 5. Altering the value of any of the
not affect other members of the member will alter other member values.
structure.
6. Individual member can be accessed at 6. Only one member can be accessed at
a time a time.
7. Several members of a structure can 7. Only the first member of a union can
initialize at once. be initialized.

Difference between call by value and call by reference.


Ans:
Call by Value:
while passing Parameters using call by value copy the value of actual argument into
formal arguments
any update made inside method will not affect the original value of variable in calling function.
e.g.
void fun(int x)
{
x=x+1;
}
void main()
{
int y=10;
printf(“\nBefore fun() call Value of y is %d”, y);
fun(y);
printf(“\nAfter fun() call Value of y is %d”, y);

}
output:
Before fun() call Value of y is 10
After fun() call Value of y is 10

Pass By Reference:
while passing parameter using call by address, we are passing actual address of variable
to called function. any updates made inside the called function will modify the original copy
since we are directly modifying the content of the exact memory loctaion.
e.g.
void fun(int *x)
{
*x= *x + 1;
}
void main()
{
int y=10;
printf(“\nBefore fun() call Value of y is %d”, y);
fun(&y);
printf(“\nAfter fun() call Value of y is %d”, y);

}
output:
Before fun() call Value of y is 10
After fun() call Value of y is 11

Difference between break and continue.


Ans:
There are two statement built in C, break; and continue; to interrupt the normal flow of
control of a program. Loops performs a set of operation repeately until certain condition
becomes false but, it is sometimes desirable to skip some statements inside loop and
terminate the loop immediately without checking the test expression. In such cases,
break and continue statements are used.

break Statement
In C programming, break is used in terminating the loop immediately after it is
encountered. The break statement is used with conditional if statement.

The break statement can be used in terminating all three loops for, while and do...while
loops.

The figure below explains the working of break statement in all three type of loops.
continue Statement
It is sometimes desirable to skip some statements inside the loop. In such cases, continue
statements are used.

Just like break, continue is also used with conditional if statement.

For better understanding of how continue statements works in C programming. Analyze the
figure below which bypasses some code/s inside loops using continue statement.

What is an array? How are they declared in 'C'? What are the rules to be followed while
using arrays?
Ans:
Arrays
Array by definition is a variable that hold multiple elements which has the same data type. Array
is variables that hold multiple elements which has same data type.
An array is a multi element box, uses an indexing system.

Declaring the array: We can declare an array by specify its data type, name and the number of
elements the array holds between square brackets immediately following the array name.
Name;
Type of array
Number of element "data type array name[size];"

There are some rules for array declaration. The data type can be any valid C data types
including structure and union. The array name has to follow the rule of variable and the size of
array has to be a positive constant integer. We can access array elements via indexes
array_name[index]. Indexes of array starts from 0 not 1 so the highest elements of an array is
array_name[size-1].

Initializing the array: It is like a variable, an array can be initialized. To initialize an array, you
provide initializing values which are enclosed within curly braces in the declaration and placed
following an equals sign after the array name.
int list[5]={2,3,4,5,6} OR int list[5] = {2,1,3,7,8};

Character arrays: char string1[]=”first”;, "Here ,we using char string and its array size is six."
char string[]={‘f’,’g’,’t’,’y’,’u’,’I’,’\0’}; // \0 null character terminating the string.

Passing the array To pass an array argument in a function specifies the name of array to pass
without any bracket.
int myarray[24];
myfunction(my array,24).

• array usually pass to the function


• array using call by reference
• function knows where the array stored

passing array element:


• using call by value
• pass subscripted name (ex: myarray[5]) to function.

Function prototype: void modify array (int b[],int array size);


Parameter name may be optional.
int b[] may be int[]
int array size may be int
2. Explain the term Dynamic memory allocation. Also explain malloc, calloc and realloc
functions in C with the suitable example.
Ans:

Dynamic memory allocation is a technique in which programs determine as they are running
where to store some information. You need dynamic allocation when the number of memory
blocks you need, or how long you continue to need them, depends on the data you are working
on.

When you use dynamic allocation, the allocation of a block of memory is an action that the
program requests explicitly. You call a function or macro when you want to allocate space, and
specify the size with an argument. If you want to free the space, you do so by calling another
function or macro. You can do these things whenever you want, as often as you want.

1. The malloc() function dynamically allocates memory when required. This function
allocates ‘size’ byte of memory and returns a pointer to the first byte or NULL
Syntax: void * malloc (size_t size);
int * p;
p = (int *) malloc (sizeof (int));
* p = 5;

2. The C library function void *calloc(size_t nitems, size_t size) allocates the requested
memory and returns a pointer to it. The difference in malloc and calloc is that malloc
does not set the memory to zero where as calloc sets allocated memory to zero.

int *a;

a=(int*) calloc(5,sizeof(int));

3. The function realloc() reallocates a memory block with a specific new size. If you call
realloc() the size of the memory block pointed to by the pointer is changed to the given
size in bytes.

int *p;

p = (int *) malloc (sizeof (int));


---------

---------

p=(int*) realloc(p,20*sizeof(int));
What do you mean by recursive functions? Explain with example.
Ans:
Recursion is a process by which a function calls itself repeatedly, until some specified condition
has been satisfied. The process is used for repetitive computation in which each action is stated
in terms of previous result.
In order to solve a problem recursively, two conditions must be satisfied:
1. The problem must be written in recursive form.
2. The problem statement must include a stopping condition.
main( )
{
int n;
long int fact (int);
printf (“\n n = “);
scanf (“%d”, &n);
printf (“\n n! = % ld” fact (n));
}
long int fact (int n)
{
if (n < = 1)
return 1;
else
return (n * factorial (n-1));
}
What do you mean by the “File Handling”? Explain the concept of file handling with a C
program.
Ans:
disks and read whenever necessary. This method employs the concept of files to store data. A
file
is a place on disk where a group of related data is stored. C supports a number of functions that
have the ability to perform basic file operations, which include:
1. Naming a file
2. Opening a file
3. Reading data from a file
4. Writing data to a file
5. Closing a file
e.g.
void main()
{
FILE *fpt;
char c;
fpt = fopen(“sample.dat”, “w”);
do
{ putc (toupper ( c = getchar() ), fpt);
}while (c != ‘\n’);
fclose (fpt);

if ((fpt = fopen(“sample.dat”, “r”)) == NULL)


printf(“\nERROR - Cannot open the designated file\n”);
else
putchar(c = getc(fpt));
while (c != ‘\n’);
fclose(fpt);
}
}
How pointers are initialized and implemented in C? Write a program to explain the
concept.
Ans:
pointer initialization :
it is a process of asiging address of a variable to pointer variable. pointer variable contains
address of variable of same data type. in c language address operator (&) is used to
determine address of a variable. the & return the address of the variable associated with it.
once a pointer has been assigned the address of a variable. toaccess the value of
variable ,pointer is dereferenced , using the indirection operator (*).
void main()
{
int a,*p;
a=10; p= &a;
printf(“\n %d”,*p); // this will print the value of a variable
printf(“\n%d”, *&a); // this will also print the value of a variable
printf(“\n%u”,&a); // this will print the address of a variable
printf(“\n%u”,p); // this will also print the address of a variable
}

What are the different Storage classes used in C? Explain with proper examples.
Ans:
A storage class is an attribute that tells us where the variable would be stored, what will be the
initial value of the variable if no value is assigned to that variable, life time of the variable and
scope of the variable.
There are four storage classes in C:
1) Automatic storage class
2) Register storage class
3) Static storage class
4) External storage class
Automatic storage class:
The keyword used for Automatic storage class is ‘auto’.The variable declared as auto is stored in
the memory.
Default value of that variable is garbage value.Scope of that variable is local to the block in
which the variable is defined. Variable is alive till the control remains within the block in which
the variable id defined.

#include<conio.h>
#include<stdio.h>
void main(){
auto int a;
printf(“%d”,a)
}
Output:
1285
As seen above, the output is garbage value.

Register storage class:


The keyword used for Register storage class is ‘register’. The variable declared as register is
stored in the CPU register. Default value of that variable is garbage value. Scope of that variable
is local to the block in which the variable is defined.Variable is alive till the control remains
within the block in which the variable id defined.
Main difference between auto and register is that variable declared as auto is stored in memory
whereas variable declared as register is stored in CPU register.

#include<conio.h>
#include<stdio.h>
void main(){
register int a;
printf(“%d”,a)
}
Output:
4587
As seen above, the output is garbage value.

Static storage class:


The keyword used for Static storage class is ‘static’. The variable declared as static is stored in
the memory.
Default value of that variable is zero. Scope of that variable is local to the block in which the
variable is defined.
Life of variable persists between different function calls.

External storage class:


The keyword used for External storage class is ‘extern’.
The variable declared as static is stored in the memory.
Default value of that variable is zero.
Scope of that variable is global.
Variable is alive as long as the program’s execution doesn’t come to an end.

External variable can be declared outside all the functions or inside function using ‘extern’
keyword.
Example:

1 #include<conio.h>
2 #include<stdio.h>
3 int a;
4 void main(){
5 extern int b;
6 printf(“%d %d”,a,b)
7}
8
9 int b=10;
Output:
0 10

What is Linked List and what are the operations that can be performed on Linked List?
Linked List
a linked list is a list of elements in which the elements of the list can be placed anywhere
in memory, and these elements are linked with each other using an explicit link field, that
is, by storing the address of the next element in the link field of the previous element We
can perform the following basic operations on the linked lists:
1. Creating the list
2. Traversing the list
3. Printing the list
4. Deleting a node
5. Concatenating two lists

4. Explain :
a. Concept of structure.
Ans:
A structure is a collection of variables referenced under one name providing a
convenient means of keeping related information together. The structure definition
creates a format that may be used to declare structure variables in a program later on.
The general format of structure definition is as follows:
struct tag_name
{
data_type member1;
data_type member2;
-------
-------
};
A keyword struct declares a structure to hold the details of fields of different
datatypes. At this time, no variable has actually been created. Only a format of a new
data type has been defined.
Consider the following example:
struct addr
{
char name [30];
char street [20];
char city [15];
char state [15];
int pincode;
};
b. Various Control statements.
c. Concept of pointer.
Short Ques:
1. List the different types of constants used in C.
Ans:
There are 4 types of constants in C.
 Integer constants
 Character constants
 Real/Floating point constants
 String constants

What is the difference between while and do-while loop.


Ans:
The main difference between for loop, while loop, and do while loop is
1. While loop checks for the condition first. so it may not even enter into the loop, if the condition
is false.
2. do while loop, execute the statements in the loop first before checks for the condition. At least
one iteration takes places, even if the condition is false.
3. for loop is similar to while loop except that
 initialization statement, usually the counter variable initialization
 a statement that will be executed after each and every iteration in the loop, usually counter
variable increment or decrement.

Distinguish between variables and keywords with example.


Ans:
Variable can be defined as a memory location declared to store any kind of data (which may
change many times during program execution). It can also be defined as any quantity/entity
which may vary during program execution. To identify a variable (the declared memory
location), it can be assigned a name – known as variable name. The name given to a variable
is known as an identifier. An identifier can be a combination of alphabets,digits and
underscore.
syntax: <storage_class> <datatype> variable_name = <value>;
e.g. int A=10;
where A is variable and 10 is value which stored in A location.

 Keywords are reserved words in C which has a predefined meaning. The compiler already
knows the meaning of these words and it will do a particular operation according to the
meaning of the keyword. here are 32 keywords in C language. A keyword name can not be
used as a variable name.
Keywords must be written in lower case.

What is the use of printf() and scanf() in C language?


Ans:
The printf and scanf are two of the many functions found in the C standard library (stdio.h).
The printf function is used to write information from a program to the standard output
device(Monitor). The scanf function is used to read information into a program from the
standard input device(Keyboard).
e.g.
printf(“\nEnter any number”);
scanf(“%d”,&no);
printf(“\n Number =%d”,no);

Name any four in-built functions of strings


Ans:

1) strlen() :

This function is used to determine the length of a given string.

int len= strlen(“Hello”);

2) strcpy() :

This function copies the string from one variable to another variable.

strcpy(name1,name);

3)strncpy() :

This function also copies the string from one variable to another variable, but only upto the
specified length.

strncpy(name1,name,3);

4) strcmp() in C :

This function is used to compare two strings. They are case sensitive.

int ch= strcmp(“Hello”,”hello”);

If both the strings are equal return value will be 0, else non_zero value will be returned.
What is the main purpose of pointers?
Ans:
Pointers are variables that store memory address, and you can use it to pass reference of
variable to functions .pointers are for many purposes
- without pointers you can not access memory address.
- you can create dynamic array with pointer.
- many data structures need pointer to solve.
- function can't return char[] but it can return char*

What is a conditional operator?


Ans:
The (?:) conditional operator in C is also known as ternary operator. It is called ternary
operator because it takes three arguments.
(expr1 ? expr2 : expr3);
if expr1 is true then expr2 is evaluate otherwise expr3 is evaluate.

What are pre-processor directives?


Ans:
preprocessor is a program that processes the C program before the compiler. All the lines in the
C program beginning with a hash (#) sign are processed by the preprocessor. ‘stdio.h’ refers to a
file supplied along with the C compiler. It contains ordinary C statements. These statements give
information about many other functions that perform input-output roles.
#include<stdio.h>
The #include directive tells the preprocessor to grab the text of a file and place it directly into
the current file.
#include, #define,#ifndef are the example of preprocessor directive.
What is an Identifier?
Ans:
 Each program elements in a C program are given a name called identifiers.
 Names given to identify Variables, functions and arrays are examples for identifiers. eg. x
is a name given to integer variable in above program.
Rules for constructing identifier name in C:

1. First character should be an alphabet or underscore.


2. Succeeding characters might be digits or letter.
3. Punctuation and special characters aren’t allowed except underscore.
4. Identifiers should not be keywords.
Define function. Why there is a need for functions?
Ans:
A function is a block of code that performs a particular task. there are times when we need to
write a particular block of code for more than once in our program. c language provides an
approach in which you need to decalre and define a group of statements once and that can be
called and used whenever required. This saves both times and space. function can be classified
into two categories (i) Library Function (ii) User Defined function

In order to make use of a user-defined function, we need to establish three elements that are
related to functions.
1. Function definition.
2. Function call
3. Function declaration.
The function definition is an independent program, module that is specially written to
implement
the requirements if the function. In order to use this function we need to invoke it is a required
place in the program. This is known as the function call. The program that calls the function is
referred to as calling program or calling function.

int sum(int ,int ); // function definition


void main()
{
int s= sum(100,200); //function calling
}

int sum(int x,int y) //function declaration


{
return(x+y);
}

You might also like