Professional Documents
Culture Documents
C Exam Master
C Exam Master
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. 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.
1. C Programs are portable i.e they can be run on any Compiler with Little or no Modification
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
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.
Network Drivers
Assemblers
Data Bases
Utilities
Print Spoolers
Text Editors
Language Interpreters
Embedded System
main ()
{
Declaration part
Executable part
Subprogram section
Function 1
Function 2
.
.
Function n
Explanation:
Sections
1.Documentation section
2.Link Section
3.Definition Section
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
int main()
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();
return 0;
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
Bitwise Operators
Assignment Operators
Misc Operators
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
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
Assignment Operators:
There are following assignment operators supported by C language:
Operato
r
=
Description
Example
<<=
>>=
&=
^=
|=
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
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:
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.
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
*/%
+<< >>
< <= > >=
== !=
&
^
|
&&
||
?:
= += -= *= /= %= >>= <<= &= ^= |=
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
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;
}
}
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
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.
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
}
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
16
// function call
// 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
malloc()
malloc() initializes the allocated memory with garbage
values.
Number of argument is 1
Syntax :
(cast_type *)malloc(Size_in_bytes);
21
22