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

1. Explain Features and Applications of c?

C Programming is widely used in Computer Technology, We can say that C is inspiration for development
of other languages. We can use C for different purposes. Below are some of the Features of C
Programming
Features of C Programming Language:
Features of C
Low Level Language Support
Powerful and Feature Rich
High Level Features
Efficient Use of Pointers

Program Portability
Bit Manipulation
Modular Programming

1 . Low Level Features :

1. C Programming provides low level features that are generally provided by the Lower level
languages. C is Closely Related to Lower level Language such as Assembly Language.

2. It is easier to write assembly language codes in C programming.


2 . Portability :

1. C Programs are portable i.e they can be run on any Compiler with Little or no Modification

2. Compiler and Preprocessor make it Possible for C Program to run it on Different PC


3 . Powerful

1. Provides Wide verity of Data Types

2. Provides Wide verity of Functions

3. Provides useful Control & Loop Control Statements


4 . Bit Manipulation

1. C Programs can be manipulated using bits. We can perform different operations at bit level. We
can manage memory representation at bit level. [Eg. We can use Structure to manage Memory at
Bit Level]

2. It provides wide verity of bit manipulation Operators. We have bitwise operators to manage Data
at bit level.
5 . High Level Features :

1. It is more User friendly as compare to Previous languages. Previous languages such as BCPL,
Pascal and other programming languages never provide such great features to manage data.

2. Previous languages have their pros and cons but C Programming collected all useful features of
previous languages thus C become more effective language.
6 . Modular Programming

1. Modular programming is a software design technique that increases the extent to which
software is composed of separate parts, called modules

2. C Program Consist of Different Modules that are integrated together to form complete program
7 . Efficient Use of Pointers

1. A pointer has direct access to memory.

2. C Supports efficient use of pointer.


Application Of C Programming
C Programming is best known programming language. C Programming is near to machine as well as
human so it is called as Middle level Programming Language. C Programming can be used to do verity of
tasks such as networking related,OS related.
Application of C Programming

C language is used for creating computer applications

1. Used in writing Embedded software

2. Firmware for various electronics, industrial and communications products which use microcontrollers.

3. It is also used in developing verification software, test code, simulators etc. for various
applications and hardware products.

4. For Creating Compiles of different Languages which can take input from other language and
convert it into lower level machine dependent language.

5. C is used to implement different Operating System Operations.

6. UNIX kernel is completely developed in C Language.


List of Applications of C Programming
Operating Systems
Language Compilers
Modern Programs
Simulators

Network Drivers
Assemblers
Data Bases
Utilities

Print Spoolers
Text Editors
Language Interpreters
Embedded System

2. Explain the structure or various sections of c-program?


Ans: Here, the program structure refers the way to write a c-program .
C- Program Structure or Various sections in C-Program
A C program may contain one or more sections. They are illustrated below.
Documentation Section
Link Section
Definition Section
Global Declaration Section

main ()
{
Declaration part
Executable part

Subprogram section
Function 1
Function 2
.
.
Function n

Explanation:
Sections
1.Documentation section

2.Link Section

3.Definition Section

4.Global declaration section


and
Function prototype declaration
section
5.main( ) function

6.User-defined function
section or sub-program section

Description
We can give comments about the program, creation or
modified date, author name etc in this section.
The characters or words or anything which are given
between /* and */, wont be considered by C compiler for
compilation process.
These will be ignored by C compiler during compilation.
Example : /* comment line1 comment line2 comment 3 */
Header files that are required to execute a C program are
written in this section.
Example #include<stdio.h>
In this section, variables, symbolic constants are defined and
values are set to these variables. Ex #define X 123
#define is a pre-processor directive not a statement so it not
end with ;
Global variables are defined in this section.
Global variable is a variable which is to be used throughout
the program, can be defined in this section.
Function prototype gives much information about a function
like return type, parameter names used inside the function.
All user defined functions are declared inside in this section
Every C program is started from main function and this
function contains two major parts called declaration part and
executable part.
Declaration part is used to declare all variables.
Executable part contains at least one executable statements
User can define their own functions in this section which
perform particular task as per the user requirement.

A SIMPLE C PROGRAM:
#include <stdio.h>
int main()
{
/* Our first simple C basic program */
printf("Hello World! ");

getch();
return 0;
}
Program Explanation:
Program code/line
#include <stdio.h>

Explanation

This is a preprocessor command that includes,links standard input


output header file(stdio.h) from the C library before compiling a C
program

int main()

This is the main function from where execution of any C program


begins.

This indicates the beginning of the main function.

/*Our first simple c basic


program*/

printf(Hello_World! );

Thisi is a comment in c.
Whatever is given inside the command /* */ or // is called a
comment.
In any C program, comments are wont be considered for
compilation and execution.
printf command prints the output onto the screen.

getch();

This command waits for any character input from keyboard.

return 0;

This command terminates C program (main function) and returns


0.

This indicates the end of the main function.

3. Explan various data-types of c-language?

Data types specifies size and type of data.


C language has some predefined set of data types to handle various kinds of data that we use in
our program.
each data types have different storage capacities.
C language supports 2 different type of data types,
Data types in C
1. Fundamental Data Types or predefined
o Integer types
o Floating type
o Character type
2. Derived Data Types or user-defined
o Arrays
o Pointers
o Structures
o Enumeration
Integer type
Integers are used to store whole numbers (example 55,78,786,99).
Size and range of Integer type on 16-bit machine
Type
Size(bytes)
Range
int or signed int
2
-32,768 to 32767
unsigned int
2
0 to 65535
short int or signed short int
1
-128 to 127
long int or signed long int
4
-2,147,483,648 to 2,147,483,647
unsigned long int
4
0 to 4,294,967,295
Floating type
Floating types are used to store real numbers.(55.45,99.95,1.26)
Size and range of Integer type on 16-bit machine

Type
Float
double
long double

Size(bytes)
4
8
10

Range
3.4E-38 to 3.4E+38
1.7E-308 to 1.7E+308
3.4E-4932 to 1.1E+4932

Character type
Character types are used to store characters value.
Size and range of Integer type on 16-bit machine
Type
Size(bytes)
char or signed char
1
unsigned char
1

Range
-128 to 127
0 to 255

void type
Void type means no value. (nothing or null)
This is usually used to specify the type of functions.
Secondary Data Types:
Array: an array is collection of homogeneous(similer) elements which share same name and memory.
Example int a[3]={55,88,123};
Int a[2][2]={45,32,45,78};
Pointer: A pointer is a variable which holds the address of another variable.
Pointers are memory related variables.
Ex int *p,a;
P=&a;
Structure: A structure is a collection of heterogeneous elements. i.e we can store different types of
elements inside a structure.
struct student
{
int no,
char sname,
float fees
};
Size of a structure is sum of its data elements size,
In the above structure size is (2+1+4 bytes)=7 bytes
Union: the union is similar to structures but in which union elements are stored in same memory location.
The size of union is it largest data-element size.
union emp
{
int eno;
char name;
float sal;
};
The size of union is it largest data-element size.
Here, float element-sal has 4 bytes size which is largest among all other union elements. so it will be
the size of the union emp.
4. What is an Operator Explain various operators in c?
Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and
+ is called operator. C language supports following type of operators.

Arithmetic Operators

Logical (or Relational) Operators

Bitwise Operators

Assignment Operators

Misc Operators

Lets have a look on all operators one by one.


Arithmetic Operators:
There are following arithmetic operators supported by C language:
Assume variable A holds 10 and variable B holds 20 then:
Operator
+
*
/
%
++
--

Description
Adds two operands
Subtracts second operand from the first
Multiply both operands
Divide numerator by denumerator
Modulus Operator and remainder of after an integer division
Increment operator, increases integer value by one
Decrement operator, decreases integer value by one

Example
A + B will give 30
A - B will give -10
A * B will give 200
B / A will give 2
B % A will give 0
A++ will give 11
A-- will give 9

Logical (or Relational) Operators:


There are following logical operators supported by C language
Assume variable A holds 10 and variable B holds 20 then:
Operato
r
==
!=
>
<
>=
<=
&&
||
!

Description

Example

Checks if the value of two operands is equal or not, if yes then condition
becomes true.
Checks if the value of two operands is equal or not, if values are not equal
then condition becomes true.
Checks if the value of left operand is greater than the value of right
operand, if yes then condition becomes true.
Checks if the value of left operand is less than the value of right operand, if
yes then condition becomes true.
Checks if the value of left operand is greater than or equal to the value of
right operand, if yes then condition becomes true.
Checks if the value of left operand is less than or equal to the value of right
operand, if yes then condition becomes true.
Called Logical AND operator. If both the operands are non zero then then
condition becomes true.
Called Logical OR Operator. If any of the two operands is non zero then
then condition becomes true.
Called Logical NOT Operator. Use to reverses the logical state of its
operand. If a condition is true then Logical NOT operator will make false.

(A == B) is
not true.
(A != B) is
true.
(A > B) is not
true.
(A < B) is
true.
(A >= B) is
not true.
(A <= B) is
true.
(A && B) is
true.
(A || B) is
true.
!(A && B) is
false.

Bitwise Operators:
Bitwise operator works on bits and perform bit by bit operation.
Assume if A = 60; and B = 13; Now in binary format they will be as follows:
A = 0011 1100

B = 0000 1101
----------------A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
There are following Bitwise operators supported by C language
Operato
r
&
|
^
~
<<
>>

Description

Example

Binary AND Operator copies a bit to the result if it exists in both


operands.
Binary OR Operator copies a bit if it exists in eather operand.
Binary XOR Operator copies the bit if it is set in one operand but
not both.
Binary Ones Complement Operator is unary and has the efect of
'flipping' bits.
Binary Left Shift Operator. The left operands value is moved left
by the number of bits specified by the right operand.
Binary Right Shift Operator. The left operands value is moved
right by the number of bits specified by the right operand.

(A & B) will give 12


which is 0000 1100
(A | B) will give 61
which is 0011 1101
(A ^ B) will give 49
which is 0011 0001
(~A ) will give -60 which
is 1100 0011
A << 2 will give 240
which is 1111 0000
A >> 2 will give 15
which is 0000 1111

Assignment Operators:
There are following assignment operators supported by C language:
Operato
r
=

Description

Example

<<=

Simple assignment operator, Assigns values from right side


operands to left side operand
Add AND assignment operator, It adds right operand to the left
operand and assign the result to left operand
Subtract AND assignment operator, It subtracts right operand
from the left operand and assign the result to left operand
Multiply AND assignment operator, It multiplies right operand
with the left operand and assign the result to left operand
Divide AND assignment operator, It divides left operand with
the right operand and assign the result to left operand
Modulus AND assignment operator, It takes modulus using two
operands and assign the result to left operand
Left shift AND assignment operator

>>=

Right shift AND assignment operator

&=

Bitwise AND assignment operator

^=

bitwise exclusive OR and assignment operator

|=

bitwise inclusive OR and assignment operator

C = A + B will assigne
value of A + B into C
C += A is equivalent to C
=C+A
C -= A is equivalent to C
=C-A
C *= A is equivalent to C
=C*A
C /= A is equivalent to C
=C/A
C %= A is equivalent to C
=C%A
C <<= 2 is same as C =
C << 2
C >>= 2 is same as C =
C >> 2
C &= 2 is same as C = C
&2
C ^= 2 is same as C = C
^2
C |= 2 is same as C = C |
2

+=
-=
*=
/=
%=

Misc Operators

There are few other operators supported by C Language.


Operato
r
sizeof()
&
*
?:

Description
Returns the size of an variable.
Returns the address of an
variable.
Pointer to a variable.
Conditional Expression

Example
sizeof(a), where a is interger, will return 4.
&a; will give actaul address of the variable.
*a; will pointer to a variable.
If Condition is true ? Then value X : Otherwise value
Y

Operators Categories:
All the operators we have discussed above can be categorized into following categories:

Postfix operators, which follow a single operand.


Unary prefix operators, which precede a single operand.

Binary operators, which take two operands and perform a variety of arithmetic and logical
operations.

The conditional operator (a ternary operator), which takes three operands and evaluates either
the second or third expression, depending on the evaluation of the first expression.

Assignment operators, which assign a value to a variable.

The comma operator, which guarantees left-to-right evaluation of comma-separated expressions.

Precedence of C Operators:

For example x = 7 + 3 * 2;
Here x is assigned 13, not 20 because operator * has higher precedence than + so it first get
multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom.

Category
Postfix (highest-priority)
Unary
Multiplicative
Additive
Shift
Relational
Equality
Bitwise AND
Bitwise XOR
Bitwise OR
Logical AND
Logical OR
Conditional
Assignment

Operator
() [] -> . ++ - + - ! ~ ++ - - (type) * & sizeof
*/%
+<< >>
< <= > >=
== !=
&
^
|
&&
||
?:
= += -= *= /= %= >>= <<= &= ^= |=

5. Explain various control statements in c?


C provides two styles of flow control:
Branching
Looping
Branching is deciding what actions to takes

Associativity
Left to right
Right to left
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Right to left
Right to left


o
o

and looping is deciding how many times to take a certain action.


Branching:
o Branching is so called because the program chooses to follow one branch or another.
if statement
o This is the most simple form of the branching statements.
o 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.
o NOTE: Expression will be assumed to be true if its evaulated values is non-zero.
if statements take the following form:

if (expression)
{
Block of statements;
}
else if(expression)
{
Block of statements;
}
else
{
Block of statements;
}
? : Operator
o The ? : operator is just like an if ... else statement except that because it is an operator you can
use it within expressions.
o ? : is a ternary operator in that it takes three values, this is the only ternary operator C has.
o ? : takes the following form:
if condition is true ? then X return value : otherwise Y value;
o switch statement:
o The switch statement is much like a nested if .. else statement. Its mostly a matter of preference
which you use, switch statement can be slightly more efficient and easier to read.
switch( expression )
{
case constant-expression1:statements1;
[case constant-expression2:
statements2;]
[case constant-expression3:
statements3;]
[default : statements4;]
}
Using break keyword:
If a condition is met in switch case then execution continues on into the next case clause also if it
is not explicitly specified that the execution should exit the switch statement. This is achieved by
using break keyword.
What is default condition:
If none of the listed conditions is met then default condition executed.
Looping
Loops provide a way to repeat commands and control how many times they are repeated. C
provides a number of looping way.
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 statements 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:
while ( expression )
{
Single statement
or
Block of statements;
}
for loop

10

for loop is similar to while, it's just written differently. for statements are often used to process lists
such a range of numbers:
Basic syntax of for loop is as follows:
for( expression1; expression2; expression3)
{
Single statement
or
Block of statements;
}

In the above syntax:


expression1 - Initialisese variables.
expression2 - Condtional expression, as long as this condition is true, loop will keep executing.
expression3 - expression3 is the modifier which may be simple increment of a variable.
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:
do
{
Single statement
or
Block of statements;
}while(expression);
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.
You already have seen example of using break statement. Here is an example showing usage
of continue statement.
#include
main()
{
int i;
int j = 10;
for( i = 0; i <= j; i ++ )
{
if( i == 5 )
{
continue;
}
printf("Hello %d\n", i );
}

}
This will produce following output:
Hello 0
Hello 1
Hello 2
Hello 3
Hello 4
Hello 6
Hello 7
Hello 8
Hello 9
Hello 10
6.Explain pointers in c

A pointer is a special kind of variable.


Pointers are designed for storing memory address i.e. the address of another variable.
Declaring a pointer is the same as declaring a normal variable except you stick an asterisk '*' in
front of the variables identifier.

11

There are two new operators you will need to know to work with pointers.
o The "address of" operator '&'
o and the "dereferencing" operator '*'.
Both are prefix unary operators.
When you place an ampersand(&) in front of a variable you will get it's address, this can be stored
in a pointer variable.
When you place an asterisk(*) in front of a pointer you will get the value at the memory address
pointed to.

Pointers and Arrays


The most frequent use of pointers in C is for walking efficiently along arrays.
In fact, in the implementation of an array, the array name represents the address of the zeroth
element of the array, so you can't use it on the left side of an expression. For example:
char *y;
char x[100];
y is of type pointer to character (although it doesn't yet point anywhere). We can make y point to an
element of x by either of
y = &x[0];
y = x;
Since x is the address of x[0] this is legal and consistent. Now `*y' gives x[0]. More importantly notice the
following:
*(y+1) gives x[1]
*(y+i) gives x[i]
and the sequence
y = &x[0];
y++;
leaves y pointing at x[1].

Pointer Arithmetic:
C is one of the few languages that allows pointer
arithmetic. In other words, you actually move the pointer reference by an arithmetic operation. For
example:
int x = 5, *ip = &x;
ip++;
On a typical 32-bit machine, *ip would be pointing to 5 after initialization. But ip++; increments the
pointer 32-bits or 4-bytes. So whatever was in the next 4-bytes, *ip would be pointing at it.
Pointer arithmetic is very useful when dealing with arrays, because arrays and pointers share a
special relationship in C.
Using Pointer Arithmetic With Arrays:
Arrays occupy consecutive memory slots in the computer's memory.
This is where pointer arithmetic comes in handy - if you create a pointer to the first element,
incrementing it one step will make it point to the next element.
#include <stdio.h>
int main() {
int *ptr;
int arrayInts[10] = {1,2,3,4,5,6,7,8,9,10};
ptr = arrayInts; /* ptr = &arrayInts[0]; is also fine */
printf("The pointer is pointing to the first ");
printf("array element, which is %d.\n", *ptr);
printf("Let's increment it.....\n");
ptr++;
printf("Now it should point to the next element,");
printf(" which is %d.\n", *ptr);
printf("But suppose we point to the 3rd and 4th: %d %d.\n",
*(ptr+1),*(ptr+2));
ptr+=2;

12

printf("Now skip the next 4 to point to the 8th: %d.\n",


*(ptr+=4));
ptr--;
printf("Did I miss out my lucky number %d?!\n", *(ptr++));
printf("Back to the 8th it is then..... %d.\n", *ptr);
return 0;
}
This will produce following result:
The pointer is pointing to the first array element, which is 1.
Let's increment it.....
Now it should point to the next element, which is 2.
But suppose we point to the 3rd and 4th: 3 4.
Now skip the next 4 to point to the 8th: 8.
Did I miss out my lucky number 7?!
Back to the 8th it is then..... 8.
Pointers and const Type Qualifier:
The const type qualifier can make things a little confusing when it is used with pointer
declarations.
The below example:
const int * const ip; /* The pointer *ip is const
and it points at is also cont */
int * const ip; /* The pointer *ip is const
*/
const int *
ip; /* What *ip is pointing at is const
*/
int *
ip; /* Nothing is const
*/
As you can see, you must be careful when specifying the const qualifier when using pointers.
Modifying Variables Using Pointers:
You know how to access the value pointed to using the dereference operator, but you can also modify the
content of variables. To achieve this, put the dereferenced pointer on the left of the assignment operator,
as shown in this example, which uses an array:
#include <stdio.h>
int main() {
char *ptr;
char arrayChars[8] = {'F','r','i','e','n','d','s','\0'};
ptr = arrayChars;
printf("The array reads %s.\n", arrayChars);
printf("Let's change it..... ");
*ptr = 'f'; /* ptr points to the first element */
printf(" now it reads %s.\n", arrayChars);
printf("The 3rd character of the array is %c.\n",
*(ptr+=2));
printf("Let's change it again..... ");
*(ptr - 1) = ' ';
printf("Now it reads %s.\n", arrayChars);
return 0;

}
This will produce following result:
The array reads Friends.
Let's change it..... now it reads friends.
The 3rd character of the array is i.
Let's change it again..... Now it reads f iends.
Generic Pointers: ( void Pointer )
When a variable is declared as being a pointer to type void it is known as a generic pointer. Since you
cannot have a variable of type void, the pointer will not point to any data and therefore cannot be
dereferenced. It is still a pointer though, to use it you just have to cast it to another kind of pointer first.

13

Hence the term Generic pointer. This is very useful when you want a pointer to point to data of different
types at different times.
Try the following code to understand Generic Pointers.
#include <stdio.h>
int main()
{
int i;
char c;
void *the_data;
i = 6;
c = 'a';
the_data = &i;
printf("the_data points to the integer value %d\n",
*(int*) the_data);
the_data = &c;
printf("the_data now points to the character %c\n",
*(char*) the_data);
return 0;
}
NOTE-1 : Here in first print statement, the_data is prefixed by *(int*). This is called type casting in C
language.Type is used to caste a variable from one data type to another datatype to make it compatible to
the lvalue.
NOTE-2 : lvalue is something which is used to left side of a statement and in which we can assign some
value. A constant can't be an lvalue because we can not assign any value in contact. For example x = y,
here x is lvalue and y is rvalue.
However, above example will produce following result:
the_data points to the integer value 6
the_data now points to the character a
7. Explain about storage classes in C?
In C storage class which decides scope, visibility and lifetime of that variable.
The following storage classes are most often used in C programming,
1. Automatic variables
2. External variables
3. Static variables
4. Register variables

Storage Specifier
auto

extern

static

Description
Storage place: CPUMemory
Initial/default value:
Garbage value
Scope:
Local
Life:
Within the function only.
Storage place:
CPU memory
Initial/default value:
Zero
Scope:
Global
Life:
Till the end of the main program.
o Variable definition might be anywhere in the C
program.
Storage place:
CPU memory
Initial/default value: Zero
Scope:
Local
Life: Retains the value of the variable between different
function calls.

14

register

Storage place:
Register memory
Initial/default value: Garbage value
Scope:
Local
Life: Within the function only.

Automatic variables
void main()
{
int detail;
or
auto int detail; //Both are same
}
External or Global variable
int number;
void main()
{
number=10;
}
fun1()
{
number=20;
}
fun2()
{
number=30;
}
Here the global variable number is available to all three functions.
extern keyword
The extern keyword is used before a variable to inform the compiler that this variable is declared
somewhere else. The extern declaration does not allocate storage for variables.
Example Using extern in same file
main()
{
extern int x; //Tells compiler that it is defined somewhere else
x = 10;
printf("%d",x);
}
int x;

//Global variable x

Static variables
main()
{
test();
test();
test();
}
void test()
{
static int a = 0;
a = a+1;
printf("%d\t",a);
}
output :
1
2
3

//Static variable

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

15

register int number;


8. Explain functions in c?

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. This may lead to bugs and irritation for the programmer.
C language provides an approach in which you need to declare and define a group of statements
once and that can be called and used whenever required.
This saves both time and space.
C functions can be classified into two categories,
o Library functions
o User-defined functions
Library functions are those functions which are defined by C library,
example printf(), scanf(), strcat() etc. You just need to include appropriate header files to use
these functions.
These are already declared and defined in C libraries.
User-defined functions are those functions which are defined by the user at the time of writing
program. Functions are made for code reusability and for saving time and space.

Benefits of Using Functions


1. It provides modularity to the program.
2. Easy code Reusability. You just have to call the function by its name to use it.
3. In case of large programs with thousands of code lines, debugging and editing becomes easier if
you use functions.
Function declaration
General syntax of function declaration is,
return-type function-name (parameter-list) ;
Like variable and an array, a function must also be declared before its called.
A function declaration tells the compiler about a function name and how to call the function.
The actual body of the function can be defined separately.
A function declaration consist of 4 parts.
return-type
function name
parameter list
terminating semicolon
Function definition Syntax

General syntax of function definition is,

return-type function-name (parameter-list)


{
function-body ;
}
The first line return-type function-name(parameter) is known as function header and the
statement within curly braces is called function body.
Return-type
return type specifies the type of value(int,float,char,double) that function is expected to return to
the program calling the function.
Function-name
function name specifies the name of the function.
The function name is any valid C identifier and therefore must follow the same rule of formation
as other variables in C.
Parameter-list
The parameter list declares the variables that will receive the data sent by calling program.
They often referred to as formal parameters.
These parameters are also used to send values to calling program.
function-body
The function body contains the declarations and the statements necessary for performing the
required task.
The body is enclosed within curly braces { } and consists of three parts.
local variable declaration.
function statement that performs the tasks of the function.
a return statement that return the value evaluated by the function.

16

Functions and Arguments


Arguments are the values specified during the function call, for which the formal parameters are
declared in the function.
Example : Function that return some value
#include<stdio.h>
#include<conio.h>
int larger(int a,int b); // function declaration
void main()
{
int i,j,k;
clrscr();
i=99;
j=112;
k=larger(i,j);
printf("%d",k);
getch();
}

// function call

int larger(int a,int b)


{
if(a>b)
return a;
else
return b;
}

// function declaration

Nesting of Functions
C language also allows nesting of functions, one function using another function inside its body. We must
be careful while using nested functions, because it may lead to infinte nesting.
function1()
{
function2() ;
//statements
}
If function2 calls function1 inside it, then in this case it will lead to infinite nesting, they will keep calling
each other. Hence we must be careful.
Recursion
Recursion is a special of nesting functions, where a function calls itself inside it. We must have certain
condition to break out of the recursion, otherwise recursion is infinite.
function1()
{
function1() ;
//statements
}
Example : Factorial of a number using Recursion
#include<stdio.h>
#include<conio.h>
int factorial(int x);
void main()
{
int a,b;
clrscr();
printf("Enter no.");
scanf("%d",&a);
b=factorial(a);
printf("%d",b);
getch();
}
int factorial(int x)
{

17

int r=1;
if(x==1) return 1;
else r=x*factorial(x-1);
return r;
}
Types of Function calls in C
Functions are called by their names.
If the function is without argument, it can be called directly using its name.
But for functions with arguments, we have two ways to call them,
1. Call by Value
2. Call by Reference
Call by Value
In this calling technique we pass the values of arguments which are stored or copied into the
formal parameters of functions.
Hence, the original values are unchanged only the parameters inside function changes.
void calc(int x);
int main()
{
int x = 10;
calc(x);
printf("%d", x);
}
void calc(int x)
{
x = x + 10 ;
}
Output : 10
In this case the actual variable x is not changed, because we pass argument by value, hence a
copy of x is passed, which is changed, and that copied value is destroyed as the function
ends(goes out of scope). So the variable x inside main() still has a value 10.
But we can change this program to modify the original x, by making the function calc() return a
value, and storing that value in x.
int calc(int x);
int main()
{
int x = 10;
x = calc(x);
printf("%d", x);
}
int calc(int x)
{
x = x + 10 ;
return x;
}
Output : 20
Call by Reference
In this we pass the address of the variable as arguments.
In this case the formal parameter can be taken as a reference or a pointer, in both the case they
will change the values of the original variable.
void calc(int *p);
int main()
{
int x = 10;
calc(&x); // passing address of x as argument
printf("%d", x);
}
void calc(int *p)
{
*p = *p + 10;
}

18

Output : 20
9.Explain about command files in c
A file represents a sequence of bytes on the disk where a group of related data is stored.
File is created for permanent storage of data. It is a ready made structure.
In C language, we use a structure pointer of file type to declare a file.
FILE *fp;
C provides a number of functions that helps to perform basic file operations. Following are the
functions,
Function
description
fopen()
create a new file or open a existing file
fclose()
closes a file
getc()
reads a character from a file
putc()
writes a character to a file
fscanf()
reads a set of data from a file
fprintf()
writes a set of data to a file
getw()
reads a integer from a file
putw()
writes a integer to a file
fseek()
set the position to desire point
ftell()
gives current position in the file
rewind()
set the position to the begining point
Opening a File or Creating a File
The fopen() function is used to create a new file or to open an existing file.
General Syntax :
*fp = FILE *fopen(const char *filename, const char *mode);
Here filename is the name of the file to be opened and mode specifies the purpose of opening
the file. Mode can be of following types,
*fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or created) file.
mode
description
r
opens a text file in reading mode
w
opens or create a text file in writing mode.
a
opens a text file in append mode
r+
opens a text file in both reading and writing mode
w+
opens a text file in both reading and writing mode
a+
opens a text file in both reading and writing mode
rb
opens a binary file in reading mode
wb
opens or create a binary file in writing mode
ab
opens a binary file in append mode
rb+
opens a binary file in both reading and writing mode
wb+
opens a binary file in both reading and writing mode
ab+
opens a binary file in both reading and writing mode
Closing a File
The fclose() function is used to close an already opened file.
General Syntax :
int fclose( FILE *fp );
Here fclose() function closes the file and returns zero on success, or EOF if there is an error in
closing the file. This EOF is a constant defined in the header file stdio.h.
Input/Output operation on File
In the above table we have discussed about various file I/O functions to perform reading and
writing on file.
getc() and putc() are simplest functions used to read and write individual characters to a file.
#include<stdio.h>
#include<conio.h>
main()
{
FILE *fp;
char ch;
fp = fopen("one.txt", "w");
printf("Enter data");
while( (ch = getchar()) != EOF) {
putc(ch,fp);

19

}
fclose(fp);
fp = fopen("one.txt", "r");
while( (ch = getc(fp)! = EOF)
printf("%c",ch);
fclose(fp);
}
Reading and Writing from File using fprintf() and fscanf()
#include<stdio.h>
#include<conio.h>
struct emp
{
char name[10];
int age;
};
void main()
{
struct emp e;
FILE *p,*q;
p = fopen("one.txt", "a");
q = fopen("one.txt", "r");
printf("Enter Name and Age");
scanf("%s %d", e.name, &e.age);
fprintf(p,"%s %d", e.name, e.age);
fclose(p);
do
{
fscanf(q,"%s %d", e.name, e.age);
printf("%s %d", e.name, e.age);
}
while( !feof(q) );
getch();
}
In this program, we have create two FILE pointers and both are refering to the same file but in
different modes.
fprintf() function directly writes into the file, while fscanf() reads from the file, which can then be
printed on console usinf standard printf() function.
Difference between Append and Write Mode
Write (w) mode and Append (a) mode, while opening a file are almost the same. Both are used to
write in a file. In both the modes, new file is created if it doesn't exists already.
The only difference they have is, when you open a file in the write mode, the file is reset, resulting
in deletion of any data already present in the file.
While in append mode this will not happen. Append mode is used to append or add data to the
existing data of file(if any).
Hence, when you open a file in Append(a) mode, the cursor is positioned at the end of the
present data in the file.
Reading and Writing in a Binary File
A Binary file is similar to the text file, but it contains only large numerical data.
The Opening modes are mentioned in the table for opening modes above.
fread() and fwrite() functions are used to read and write is a binary file.
fwrite(data-element-to-be-written, size_of_elements,
number_of_elements, pointer-to-file);
fread() is also used in the same way, with the same arguments like fwrite() function.
Below mentioned is a simple example of writing into a binary file
const char *mytext = "The quick brown fox jumps over the lazy dog";
FILE *bfp= fopen("test.txt", "wb");
if (bfp) {
fwrite(mytext, sizeof(char), strlen(mytext), bfp) ;
fclose(bfp) ;
}

20

fseek(), ftell() and rewind() functions


fseek() - It is used to move the reading control to different positions using fseek function.
ftell() - It tells the byte location of current position of cursor in file pointer.
rewind() - It moves the control to beginning of the file.

10.Explain about dynamic memory allocation in c?


Dynamic Memory Allocation:The process of allocating memory at runtime is known as dynamic
memory allocation.
Library routines known as "memory management functions" are used for allocating and freeing
memory during execution of a program.
These functions are defined in stdlib.h.
Functio
Description
n
malloc() allocates requested size of bytes and returns a void pointer pointing to the first byte of the allocated
space
calloc()
allocates space for an array of elements, initialize them to zero and then return a void pointer to the
memory
free
releases previously allocated memory
realloc
modify the size of previously allocated space
Memory Allocation Process
Global variables, static variables and program instructions get their memory in permanent storage
area whereas local variables are stored in area called Stack.
The memory space between these two region is known as Heap area.
This region is used for dynamic memory allocation during execution of the program. The size of
heap keep changing.
Allocating block of Memory
malloc() function is used for allocating block of memory at runtime.
This function reserves a block of memory of given size and returns a pointer of type void. This
means that we can assign it to any type of pointer using typecasting. If it fails to locate enough
space it returns a NULL pointer.
Example using malloc() :
int *x;
x = (int*)malloc(50 * sizeof(int)); //memory space allocated to variable x
free(x);
//releases the memory allocated to variable x
calloc() is another memory allocation function that is used for allocating memory at runtime.
calloc function is normally used for allocating memory to derived data types such
as arrays and structures.
If it fails to locate enough space it returns a NULL pointer.
Example using calloc() :
struct employee
{
char *name;
int salary;
};
typedef struct employee emp;
emp *e1;
e1 = (emp*)calloc(30,sizeof(emp));
realloc() changes memory size that is already allocated to a variable.
Example using realloc() :
int *x;
x=(int*)malloc(50 * sizeof(int));
x=(int*)realloc(x,100); //allocated a new memory to variable x
Difference between malloc() and calloc()
calloc()
calloc() initializes the allocated memory with 0
value.
Number of arguments is 2
Syntax :
(cast_type *)calloc(blocks , size_of_block);

malloc()
malloc() initializes the allocated memory with garbage
values.
Number of argument is 1
Syntax :
(cast_type *)malloc(Size_in_bytes);

21

11.Explain command line arguments in C?


Command Line Argument:Command line argument is a parameter supplied to the program
when it is invoked.
Command line argument is an important concept in C programming.
It is mostly used when you need to control your program from outside.
command line arguments are passed to main() method.
Syntax :
int main( int argc, char *argv[])
Here argc counts the number of arguments on the command line and argv[ ] is a pointer array which
holds pointers of type char which points to the arguments passed to the program.
Example for Command Line Argument
#include <stdio.h>
#include <conio.h>
int main( int argc, char *argv[] )
{
int i;
if( argc >= 2 )
{
printf("The arguments supplied are:\n");
for(i=1;i< argc;i++)
{
printf("%s\t",argv[i]);
}
}
else
{
printf("argument list is empty.\n");
}
getch();
return 0;
}
Remember that argv[0] holds the name of the program and argv[1] points to the first command line
argument and argv[n] gives the last argument. If no argument is supplied, argc will be one.

22

You might also like