c Programming
c Programming
c Programming
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.
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.
Hello,World
Pre-processor
Header file
Function
Variables
Statements & expressions
Comments
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.
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.
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.
Example of comments :
// This is a comment
/* This is a comment */
/* This is a long
and valid comment */
// this is not
a valid comment
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.
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.
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:
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;
}
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 */
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;
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
#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();
}
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.
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.
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.
}
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
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.
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).
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*) 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);
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.
#include<conio.h>
#include<stdio.h>
void main(){
register int a;
printf(“%d”,a)
}
Output:
4587
As seen above, the output is garbage value.
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
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.
1) strlen() :
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.
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*
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.