Complete Merged
Complete Merged
Complete Merged
System Software: System software consists of programs that manage the hardware resources of a
computer and perform required information processing tasks. It is essential for the day today activities
of the computer. Examples of systems software are: Operating system, translators, utilities,
housekeeping routines etc.These programs are divided into three classes: the operating system, system
support, and system development.
The operating system provides services such as a user interface, file and database access, and
interfaces to communication systems such as Internet protocols. The primary purpose of this software
is to keep the system operating in an efficient manner while allowing the users access to the system.
System support software provides system utilities and other operating services. Examples of system
utilities are sort programs and disk format programs. Operating services consists of programs that
provide performance statistics for the operational staff and security monitors to protect the system and
data.
The last system software category, system development software, includes the language translators
that convert programs into machine language for execution, debugging tools to ensure that the
programs are error free and computer –assisted software engineering (CASE) systems.
CONTROL UNIT
Is the centre of operations for the computer system, it directs the activities of the computer
system.This unit controls the operations of all parts of the computer but does not carry out any
actual data processing operations.
Functions of this unit are −
● It is responsible for controlling the transfer of data and instructions among other units of a
computer.
● It manages and coordinates all the units of the computer.
● It obtains the instructions from the memory, interprets them, and directs the operation of
the computer.
● It communicates with Input/Output devices for transfer of data or results from storage.
● It does not process or store data.
ALU (Arithmetic Logic Unit)
This unit consists of two subsections namely,
● Arithmetic Section
● Logic Section
Arithmetic Section
Function of arithmetic section is to perform arithmetic operations like addition, subtraction,
multiplication, and division. All complex operations are done by making repetitive use of the
above operations.
Logic Section
Function of logic section is to perform logic operations such as comparing, selecting, matching,
and merging of data.
OPERATING SYSTEM
The Operating System is a program with the following features −
● An operating system is a program that acts as an interface between the software and the
computer hardware.
● It is an integrated set of specialized programs used to manage overall resources and operations
of the computer.
● It is a specialized software that controls and monitors the execution of all other programs that
reside in the computer, including application programs and other system software.
COMPUTER LANGUAGES
To write a program for a computer, we must use a computer language. Over the years, computer
languages have evolved from machine languages to natural languages.
● 1940’s Machine level Languages
● 1950’s Symbolic Languages
● 1960’s High-Level Languages
Machine Languages:
In the earliest days of computers, the only programming languages available were machine languages.
Each computer has its own machine language, which is made of streams of 0’s and 1’s.
Instructions in machine language must be in streams of 0’s and 1’s because the internal circuits of a
computer are made of switches transistors and other electronic devices that can be in one of two states:
off or on. The off state is represented by 0, the on state is represented by 1.
The only language understood by computer hardware is machine language.
Symbolic Languages:
In early 1950’s Admiral Grace Hopper, A mathematician and naval officer developed the concept of a
special computer program that would convert programs into machine language.
The early programming languages simply mirror to the machine languages using symbols of
mnemonics to represent the various machine language instructions because they used symbols, these
languages were known as symbolic languages.
Computer does not understand symbolic language it must be translated to the machine language. A
special program called assembler translates symbolic code into machine language. Because symbolic
languages had to be assembled into machine language they soon became known as assembly
languages.
Symbolic language uses symbols or mnemonics to represent the various ,machine language
instructions.
High Level Languages:
Symbolic languages greatly improved programming effificiency; they still required programmersto
concentrate on the hardware that they were using. Working with symbolic languages wasalso very
tedious because each machine instruction has to be individually coded. The desire toimprove
programmer efficiency and to change the focus from the computer to the problembeing solved led to
the development of high-level language.
High level languages are portable to many different computers, allowing the programmer
toconcentrate on the application problem at hand rather than the intricacies of the computer.High-level
languages are designed to relieve the programmer from the details of the assemblylanguage. High
level languages share one thing with symbolic languages, They must beconverted into machine
language. The process of converting them is known as compilation.The first widely used high-level
languages, FORTRAN (FORmulaTRANslation)was created byJohn Backus and an IBM team in
1957;it is still widely used today in scientific and engineeringapplications. After FORTRAN was
COBOL(Common Business-Oriented Language). AdmiralHopper was played a key role in the
development of the COBOL Business language.C is a high-level language used for system software
and new application code.
/*_some_comments_* whatever is given inside the command “/* */” in any C program,
/ won’t be considered for compilation and execution.
printf(“Hello_World!
printf command prints the output onto the screen.
“);
getch(); This command waits for any character input from keyboard.
This command terminates C program (main function) and returns
return 0;
0.
A SIMPLE C PROGRAM
Below C program is a very simple and basic program in C programming language. This C program
displays “Hello World!” in the output window. And, all syntax and commands in C programming are
case sensitive. Also, each statement should be ended with semicolon (;) which is a statement
terminator.
#include <stdio.h>
int main()
{
/* Our first simple C basic program */
printf("Hello World! ");
getch();
return 0;
}
OUTPUT:
Hello World!
1. Create
2. Compile
3. Execute or Run
4. Get the Output
CREATION, COMPILATION AND EXECUTION OF A C PROGRAM
Prerequisite:
● If you want to create, compile and execute C programs by your own, you have to install C
compiler (IDE tool and GCC compiler) in your machine. Then, you can start to execute your own
C programs in your machine.
Sections Description
In this section, variables are defined and values are set to these
Definition Section variables.
Global declaration Global variables are defined in this section. When a variable is to be
section used throughout the program, can be defined in this section.
Function prototype Function prototype gives many information about a function like
declaration section return type, parameter names used inside the function.
User defined User can define their own functions in this section which perform
function section particular task as per the user requirement.
C PREPROCESSOR DIRECTIVES:
● Before a C program is compiled in a compiler, source code is processed by a program called
preprocessor. This process is called preprocessing.
● Commands used in preprocessor are called preprocessor directives and they begin with “#”
symbol.
Below is the list of preprocessor directives that C programming language offers.
Preprocessor Syntax/Description
Syntax: #define
This macro defines constant value and can be any of the basic data
Macro types.
#include <stdio.h>
void main()
{
printf("value of height : %d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
printf("value of backslash_char : %c \n", backslash_char);
}
OUTPUT:
value of height : 100
value of number : 3.140000
value of letter : A
value of letter_sequence : ABC
value of backslash_char : ?
EXAMPLE PROGRAM FOR CONDITIONAL COMPILATIONDIRECTIVES:
#include <stdio.h>
#define RAJU 100
int main()
{
#ifdef RAJU
printf("RAJU is defined. So, this line will be added in " \
"this C file\n");
#else
printf("RAJU is not defined\n");
#endif
return 0;
}
OUTPUT:
RAJU is defined. So, this line will be added in this C file
#endif
return 0;
}
OUTPUT:
SELVA is not defined. So, now we are going to define here
EXAMPLE PROGRAM FOR #IF, #ELSE AND #ENDIF IN C:
● “If” clause statement is included in source file if given condition is true.
● Otherwise, else clause statement is included in source file for compilation and execution.
#include <stdio.h>
#define a 100
int main()
{
#if (a==100)
printf("This line will be added in this C file since " \
"a \= 100\n");
#else
printf("This line will be added in this C file since " \
"a is not equal to 100\n");
#endif
return 0;
}
OUTPUT:
This line will be added in this C file since a = 100
Comments
It is useful to place a comment in place to indicate what you are doing. It is added into the program for
making the program easier to understand and these are not compiled by the compiler or interpreter. It
is useful if you want someone else to be able to ever read your code.
Multi Line comment – It is used to apply the comment on multiple lines. To apply multi line use
/*comment */.
e.g.
printf("hello World"); /*It will print the
Character type
Character types are used to store characters value.
Size and range of Integer type on 16-bit machine
Type Size(bytes) Range
void type
“void” type means no value. This is usually used to specify the type of functions which returns nothing.
Unlike other primitive data types in c, void data type does not create any variable but returns an empty
set of values. Thus, we can say that it stores null.
The void type specifies that no value is available. It is used in three kinds of situations –
Sr.No. Types & Description
3 Pointers to void
A pointer of type void * represents the address of an object, but not its type. For
example, a memory allocation function void *malloc(size_t size ); returns a
pointer to void which can be casted to any data type.
Algorithm in Programming
In programming, algorithm is a set of well-defined instructions in sequence to solve the problem.
Qualities of a good algorithm
1. Input and output should be defined precisely.
2. Each steps in algorithm should be clear and unambiguous.
3. Algorithm should be most effective among many different ways to solve a problem.
4. An algorithm shouldn't have computer code. Instead, the algorithm should be written in such a
way that, it can be used in similar programming languages.
Step 1:
Start
Step 2:
Declare variables num1, num2 and sum.
Step 3:
Read values num1 and num2.
Step 4:
Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop
Write an algorithm to find the largest among three different numbers entered by user.
Step 1:
Start
Step 2:
Declare variables a,b and c.
Step 3:
Read variables a,b and c.
Step 4:
If a>b
If a>c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b>c
Display b is the largest number.
Else
Display c is the greatest number.
Step 5: Stop
Introduction to flowcharts
A flowchart is a graphical representation of an algorithm. These flowcharts play a vital role in the
programming of a problem and are quite helpful in understanding the logic of complicated and lengthy
problems. Once the flowchart is drawn, it becomes easy to write the program in any high level
language. Often we see how flowcharts are helpful in explaining the program to others. Hence, it is
correct to say that a flowchart is a must for the better documentation of a complex program.Flowcharts
are usually drawn using some standard symbols;
Basic Symbols used in Flowchart Designs
1. Terminal: The oval symbol indicates Start, Stop and Halt in a program’s logic flow. A
pause/halt is generally used in a program logic under some error conditions. Terminal is the first
and last symbols in the flowchart.
3. Processing: A box represents arithmetic instructions. All arithmetic processes such as adding,
subtracting, multiplication and division are indicated by action or process symbol.
4. Decision Diamond symbol represents a decision point. Decision based operations such as yes/no
question or true/false are indicated by diamond in flowchart.
5. Connectors: Whenever flowchart becomes complex or it spreads over more than one page, it is
useful to use connectors to avoid any confusions. It is represented by a circle.
6. Flow lines: Flow lines indicate the exact sequence in which instructions are executed. Arrows
represent the direction of flow of control and relationship among different symbols of flowchart.
Example of a flowchart:
Problem: Write an algorithm and draw the flowchart for finding the average of two numbers
Algorithm:
Input: two numbers x and y
Output: the average of x and y
Steps:
1. input x
2. input y
3. sum = x + y
4. average = sum /2
5. output average
START
END
Errors in C Programming
Error is an illegal operation performed by the user which results in abnormal working of the
program.Programming errors often remain undetected until the program is compiled or executed.
Some of the errors inhibit the program from getting compiled or executed. Thus errors should be
removed before compiling and executing.
Syntax errors
Syntax: All languages have a set of rules for how words and sentences should be structured. These
rules are collectively known as the language syntax. In computer programming, syntax serves the
same purpose, defining how declarations, functions, commands, and other statements should be
arranged.
A syntax error is an error in the source code of a program. Since computer programs must follow strict
syntax to compile correctly, any aspects of the code that do not conform to the syntax of the
programming language will produce a syntax error. Syntax errors are small grammatical mistakes,
sometimes limited to a single character. For example, a missing semicolon at the end of a line or an
extra bracket at the end of a function may produce a syntax error.
Common syntax errors are:
● Spelling mistakes.
● Missing out quotes.
● Missing out brackets.
● Using upper case characters in key words e.g. IF instead of if.
● Missing out a colon or semicolon at end of a statement.
● Using tokens in the wrong order.
Errors that occur when you violate the rules of writing C syntax are known as syntax errors. This
compiler error indicates something that must be fixed before the code can be compiled. All these
errors are detected by compiler and thus are known as compile-time errors.
Most frequent syntax errors are:
● Missing Parenthesis (})
● Printing the value of variable without declaring it
● Missing semicolon like this:
Example:
// C program to illustrate
// syntax error
#include<stdio.h>
voidmain()
{
intx = 10;
inty = 15;
On compilation and execution of a program, desired output is not obtained when certain input values
are given. These types of errors which provide incorrect output but appears to be error free are called
logical errors. These are one of the most common errors done by beginners of programming.
These errors solely depend on the logical thinking of the programmer and are easy to detect if we
follow the line of execution and determine why the program takes that path of execution.
Example:
// C program to illustrate
// logical error
intmain()
{
inti = 0;
References:
● https://nptel.ac.in/courses/106105171/2
● https://www.tutorialspoint.com/computer_fundamentals/computer_operating_system.htm
● Kernighan 78 – B. W. Kernighan and D. M. Ritchie, The C Programming Language,
Prentice-Hall: Englewood Cliffs, NJ, 1978. Second edition, 1988.
● Thinking 90 – C* Programming Guide, Thinking Machines Corp. Cambridge Mass., 1990
● https://www.geeksforgeeks.org/an-introduction-to-flowcharts/
● https://www.programiz.com/article/flowchart-programming
● https://www.programiz.com/article/algorithm-programming
Unit II
Operators and Operands
C language supports a rich set of built-in operators. An operator is a symbol that tells the compiler to
perform a certain mathematical or logical manipulation. Operators are used in programs to manipulate data
and variables.
An operator is a symbol which operates on a value or a variable. For example: + is an operator to
perform addition. And those variables are termed as operands.
C operators can be classified into following types:
● Arithmetic operators
● Relational operators
● Logical operators
● Bitwise operators
● Assignment operators
● Conditional operators
● Special operators
Arithmetic operators
C supports all the basic arithmetic operators. The following table shows all the basic arithmetic operators.
Operator Description
+ adds two operands
- subtract second operands from first
* multiply two operand
/ divide numerator by denominator
% remainder of division
++ Increment operator - increases integer value by one
-- Decrement operator - decreases integer value by one
Relational operators
The following table shows all relation operators supported by C.
Operator Description
== Check if two operand are equal
!= Check if two operand are not equal.
> Check if operand on the left is greater than operand on the right
< Check operand on the left is smaller than right operand
>= check left operand is greater than or equal to right operand
<= Check if operand on left is smaller than or equal to right operand
Logical operators
C language supports following 3 logical operators. Suppose a = 1 and b = 0,
Operator Description Example
&& Logical AND (a && b) is false
|| Logical OR (a || b) is true
! Logical NOT (!a) is false
Bitwise operators
Bitwise operators perform manipulations of data at bit level. These operators also perform shifting of
bits from right to left. Bitwise operators are not applied to “float” or “double”
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< left shift
>> right shift
Now lets see truth table for bitwise “&”, | and “^”
a b a&b a|b a^b
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
The bitwise shift operator, shifts the bit value. The left operand specifies the value to be shifted and the
right operand specifies the number of positions that the bits in the value have to be shifted. Both operands
have the same precedence.
Example :
a = 0001000
b=2
a << b = 0100000
a >> b = 0000010
Assignment Operators
Assignment operators supported by C language are as follows.
Operato Description Example
r
= assigns values from right side operands to left side operand a=b
+= adds right operand to the left operand and assign the result to left a+=b is same as a=a+b
-= subtracts right operand from the left operand and assign the result to left a-=b is same as a=a-b
operand
*= mutiply left operand with the right operand and assign the result to left a*=b is same as a=a*b
operand
/= divides left operand with the right operand and assign the result to left a/=b is same as a=a/b
operand
%= calculate modulus using two operands and assign the result to left operand a%=b is same as
a=a%b
Conditional operator
The conditional operators in C language are known by two more names
1. Ternary Operator
2. ? : Operator
It is actually the “if” condition that we use in C language decision making, but using conditional operator,
we turn the “if” condition statement into a short and simple operator.
The syntax of a conditional operator is :
expression1 ? expression2: expression 3
Explanation:
Operators Precedencein C
Operator precedence determines the grouping of terms in an expression and decides how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence
than +, so it first gets 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. Within an expression, higher precedence operators will be evaluated first.
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* &sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift <<>> Left to right
Relational <<= >>= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right
Decision Making
In programming, decision making is used to specify the order in which statements are executed.
if statement
The syntax of if statement is:
if (testExpression)
{
// statement(s)
}
if...else statement
The if statement may have an optional else block. The syntax of if..else statement is:
if (testExpression) {
// statement(s) inside the body of if
}
else {
// statement(s) inside the body of else
}
if (testExpression1)
{
// statement(s)
}
else if(testExpression2)
{
// statement(s)
}
else if (testExpression 3)
{
// statement(s)
}
else
{
// statement(s)
}
Nested if...else
It is possible to include if...else statement(s) inside the body of another if...elsestatement.
This program below relates two integers using either <, > and = similar like in if...elseladder
example. However, we will use nested if...else statement to solve this problem.
Switch Statement:The switch case statement is used when we have multiple options and we need
to perform a different task for each option. Switch case statements are a substitute for long if
statements that compare a variable to several integral values
● The switch statement is a multiway branch statement. It provides an easy way to dispatch
execution to different parts of code based on the value of the expression.
● Switch is a control statement that allows a value to change control of execution.
Loops in C Program
In computer programming, a loop is a sequence of instructions that is repeated until a certain condition
is reached.
● An operation is done, such as getting an item of data and changing it, and then some condition is
checked such as whether a counter has reached a prescribed number.
● Counter not reached: If the counter has not reached the desired number, the next instruction in
the sequence returns to the first instruction in the sequence and repeat it.
● Counter reached: If the condition has been reached, the next instruction “falls through” to the
next sequential instruction or branches outside the loop.
There are mainly two types of loops:
1. Entry Controlled loops: In this type of loops the test condition is tested before entering the loop
body. For Loop and While Loop are entry controlled loops.
2. Exit Controlled Loops: In this type of loops the test condition is tested or evaluated at the end
of loop body. Therefore, the loop body will execute at least once, irrespective of whether the test
condition is true or false. do – while loop is exit controlled loop.
for Loop
A for loop is a repetition control structure which allows us to write a loop that is executed a specific
number of times. The loop enables us to perform n number of steps together in one line.
Syntax:
for (initialization expr; test expr; update expr)
{
// body of the loop
// statements we want to execute
}
In for loop, a loop variable is used to control the loop. First initialize this loop variable to some value,
then check whether this variable is less than or greater than counter value. If statement is true, then
loop body is executed and loop variable gets updated . Steps are repeated till exit condition comes.
● Initialization Expression: In this expression we have to initialize the loop counter to some
value. for example: inti=1;
● Test Expression: In this expression we have to test the condition. If the condition evaluates to
true then we will execute the body of loop and go to update expression otherwise we will exit
from the for loop. For example: i<= 10;
● Update Expression: After executing loop body this expression increments/decrements the loop
variable by some value. for example: i++;
#include<stdio.h>
int main()
{
intnum, count, sum =0;
return0;
}
Output
While Loop
While studying for loop we have seen that the number of iterations is known beforehand, i.e. the
number of times the loop body is needed to be executed is known to us. while loops are used in
situations where we do not know the exact number of iterations of loop beforehand. The loop
execution is terminated on the basis of test condition.
Syntax:
We have already stated that a loop is mainly consisted of three statements – initialization expression,
test expression, update expression. The syntax of the three loops – For, while and do while mainly
differs on the placement of these three statements.
initialization expression;
while (test_expression)
{
// statements
update_expression;
}
#include<stdio.h>
int main()
{
int number;
longlong factorial;
factorial=1;
return0;
}
Output
Enter an integer: 5
Factorial = 120
Do while loop
In do while loops also the loop execution is terminated on the basis of test condition. The main
difference between do while loop and while loop is in do while loop the condition is tested at the end
of loop body, i.e do while loop is exit controlled whereas the other two loops are entry controlled
loops.
Note: In do while loop the loop body will execute at least once irrespective of test condition.
Syntax:
initialization expression;
do
{
// statements
update_expression;
} while (test_expression);
Note: Notice the semi – colon(“;”) in the end of loop.
Important Points:
● Use for loop when number of iterations is known beforehand, i.e. the number of times the loop
body is needed to be executed is known.
● Use while loops where exact number of iterations is not known but the loop termination
condition is known.
● Use do while loop if the code needs to be executed at least once like in Menu driven programs
#include<stdio.h>
int main()
{
double number, sum =0;
printf("Sum = %.2lf",sum);
return0;
}
Output
▪ Break
▪ Continue
▪ Goto
▪ Return
BREAK
A break statement is used to terminate the execution of the rest of the block where it is present and
takes the control out of the block to the next statement. It is mostly used in loops and switch-case to
bypass the rest of the statement and take the control to the end of the loop. The use of break in
switch-case has been explained in the previous tutorial Switch – Control Statement.
Another point to be taken into consideration is that break statement when used in nested loops only
terminates the inner loop where it is used and not any of the outer loops. Let’s have a look at this
simple program to better understand how break works:
#include <stdio.h>
intmain()
{
inti;
for(i=1;i<=15;i++)
{
printf("%d\n",i);
if(i==10)
break;
}
return0;
}
Output:-
1
2
3
4
5
6
7
8
9
10
In this program, we see that as soon as the condition if(i==10) becomes true the control flows out of
the loop and the program ends.
CONTINUE
The Continue statement like any other jump statements interrupts or changes the flow of control
during the execution of a program. Continueis mostly used in loops. Rather than terminating the loop
it stops the execution of the statements underneath and takes the control to the next iteration. Similar
to a break statement, in case of nested loop, the continue passes the control to the next iteration of the
inner loop where it is present and not to any of the outer loops.Let’s have a look at the following
example:
#include <stdio.h>
int main()
{
inti,j;
for(i=1;i<3;i++)
{
for(j=1;j<5;j++)
{
if(j==2)
continue;
printf("%d\n",j);
}
}
return0;
}
Output:-
1
3
4
1
3
4
In this program, we see that the printf() instruction for the condition j=2 is skipped each time during
the execution because of continue. We also see that only the condition j=2 gets affected by
the continue. The outer loop runs without any disruption in its iteration.
GOTO
This jump statement is used to transfer the flow of control to any part of the program desired. The
programmer needs to specify a label or identifier with the goto statement in the following manner:
goto label;
This label indicates the location in the program where the control jumps to. Have a look at this simple
program to understand how goto works:
#include <stdio.h>
intmain()
{
inti,j;
for(i=1;i<5;i++)
{
if(i==2)
gotothere;
printf("%d\n",i);
}
there:
printf("Two");
return0;
}
Output:-
1
Two
In this program, we see that when the control goes to the goto there; statement when i becomes equal
to 2 then the control next goes out of the loop to the label(there: ) and prints Two.
RETURN
This jump statement is usually used at the end of a function to end or terminate it with or without a
value. It takes the control from the calling function back to the main function(main function itself can
also have a return).
An important point to be taken into consideration is that return can only be used in functions that is
declared with a return type such as int,float, double, char, etc. The functions declared with void type
does not return any value. Also, the function returns the value that belongs to the same data type as it
is declared. Here is a simple example to show you how return statement works.
#include <stdio.h>
charfunc(intascii)
{
return((char)ascii);
}
intmain()
{
intascii;
charch;
printf("Enter any ascii value in decimal: \n");
scanf("%d",&ascii);
ch=func(ascii);
printf("The character is : %c",ch);
return0;
}
Output:-
Enter any ascii value in decimal:
110
The character is : n
In this program we have two functions that have a return type but only one function is returning a
value[func()] and the other is just used to terminate the function[main()]. The function func() is
returning the character value of the given number(here 110). We also see that return type of func() is
char because it is returning a character value.
The return in main() function returns zero because it is necessary to have a return value here because
main has been given the return type int.
References:
1. https://nptel.ac.in/courses/106104128/18
2. https://www.codingeek.com/tutorials/c-programming/jump-statements-in-c-break-continue-got
o-return/
3. https://www.tutorialcup.com/cprogramming/break-continue-goto.htm
4. https://www.programiz.com/c-programming/c-break-continue-statement
5. https://www.geeksforgeeks.org/loops-in-c-and-cpp/
6. https://www.programiz.com/c-programming/c-for-loop
7. https://nptel.ac.in/courses/106104128/6
8. https://www.studytonight.com/c/switch-statement-in-c.php
9. https://www.programiz.com/c-programming/c-switch-case-statement
10. https://www.geeksforgeeks.org/switch-statement-cc/
11. https://beginnersbook.com/2014/01/switch-case-statements-in-c/
Unit III
ARRAYS
An array is a group of related data items that share a common name.
Ex:- Students
The complete set of students are represented using an array name students. A particular value is
indicated by writing a number called index number or subscript in brackets after array name. The
complete set of value is referred to as an array, the individual values are called elements.
ONE – DIMENSIONAL ARRAYS :
A list of items can be given one variable index is called single subscripted variable or a
one-dimensional array. The subscript value starts from 0.
If we want 5 elements the declaration will be-- intnumber[5];
The elements will be number[0], number[1], number[2], number[3], number[4]
There will not be number[5]
Declaration of One - Dimensional Arrays :
Type variable – name [sizes];
Type – data type of all elements Ex: int, float etc.,
Variable – name – is an identifier
Size – is the maximum no of elements that can be stored.
Ex:- float avg[50]
This array is of type float. Its name is avg. and it can contains 50 elements only. The range starting
from 0 – 49 elements.
Initialization of Arrays :
Initialization of elements of arrays can be done in same way as ordinary variables are done when they
are declared.
Type array name[size] = {List of Value};
Ex:-int number[3]={0,0,0};
If the number of values in the list is less than number of elements then only that elements will be
initialized. The remaining elements will be set to zero automatically.
Ex:- float total[5]= {0.0,15.75,-10};
The size may be omitted
Example:
main()
{
inti;
float x[10],value,total;
printf(“Enter 10 real numbers\n”);
for(i=0;i<10;i++)
{
scanf(“%f”,&value);
x[i]=value;
}
total=0;
for(i=0;i<10;i++)
total=total+x[i]
for(i=0;i<10;i++)
printf(“x*%2d+=%5.2f\n”,I+1,x*I+);
printf(“total=%0.2f”,total);
}
TWO – DIMENSIONAL ARRAYS:
To store tables we need two dimensional arrays. Each table consists of rows and
columns. Two dimensional arrays are declare as
type array name [row-size][col-size];
Example:
/* Write a program Showing 2-DIMENSIONAL ARRAY */
/* SHOWING MULTIPLICATION TABLE */
#include<stdio.h>
#include<math.h>
#define ROWS 5
#define COLS 5
main()
{
introw,cols,prod[ROWS][COLS];
inti,j;
printf(“Multiplication table”);
for(j=1;j< =COLS;j++)
printf(“%d”,j);
for(i=0;i<ROWS;i++)
{
row = i+1;
printf(“%2d|”,row);
for(j=1;j < = COLS;j++)
{
COLS=j;
prod[i][j]= row * cols;
printf(“%4d”,prod*i+*j+);
}
}
}
INITIALIZING TWO DIMENSIONAL ARRAYS:
They can be initialized by following their declaration with a list of initial values enclosed in braces.
Ex:-int table[2][3] = {0,0,0,1,1,1};
Initializes the elements of first row to zero and second row to one. The initialization is done by row by
row. The above statement can be written as
int table[2][3] = {{0,0,0},{1,1,1}};
When all elements are to be initialized to zero, following short-cut method may be used.
int m[3][5] = {{0},{0},{0}};
STRINGS (CHARACTER ARRAYS) :
A String is an array of characters. Any group of characters (except double quote sign)defined between
double quotes is a constant string.
Ex: “C is a great programming language”.
If we want to include double quotes.
Ex: “\”C is great \” is norm of programmers “.
Declaring and initializing strings :-
A string variable is any valid C variable name and is always declared as an array.
char string name [size];
Here, size determines number of characters in the string name. When the compiler assigns a character
string to a character array, it automatically supplies a null character (‘\0’) at end of String. Therefore,
size should be equal to maximum number of character in String plus one. String can be initialized
when declared as
1. char city*10+= “NEW YORK’;
2. char city[10]= ,‘N’,’E’,’W’,’ ‘,’Y’,’O’,’R’,’K’,’/0’-;
3.C also permits us to initializing a String without specifying size.
Ex:- char Strings* += ,‘G’,’O’,’O’,’D’,’\0’-;
READING STRINGS FROM USER:
%s format with scanf can be used for reading String.
char address[15];
scanf(“%s”,address);
The problem with scanf function is that it terminates its input on first white space it finds. Soscanf
works fine as long as there are no spaces in between the text.
Reading a line of text :
If we are required to read a line of text we use getchar(). which reads a single characters. Repeatedly
to read successive single characters from input and place in character array.
Example:
/* Program to read String using scanf&getchar */
#include<stdio.h>
main()
{
char line[80],ano_line[80],character;
int c;
c=0;
printf(“Enter String using scanf to read \n”);
scanf(“%s”, line);
printf(“Using getchar enter new line\n”);
do
{
character = getchar();
ano_line[c] = character;
c++;
- while(character !=’\n’);
c=c-1;
ano_line*c+=’\0’;
}
STRING INPUT/OUTPUT FUNCTIONS:
C provides two basic ways to read and write strings.First we can read and write strings with the
formatted input/output functions,scanf/fscanf and prinf/fprinf.Second we can use a special set of strin
only functions ,get string(gets/fgets)and put string(puts/fputs).
Formatted string Input/Output:
Formatted String Input:scanf/fscanf:
Declarations:
intfscanf(FILE *stream, const char *format, ...);
intscanf(const char *format, ...);
The scanf functions provide a means to input formatted information from a stream fscanf reads
formatted input from a stream scanf reads formatted input from stdin.
These functions take input in a manner that is specified by the format argument and store eachinput
field into the following arguments in a left to right fashion.
Each input field is specified in the format string with a conversion specifier which specifies howthe
input is to be stored in the appropriate variable. Other characters in the format stringspecify characters
that must be matched from the input, but are not stored in any of the following arguments. If the input
does not match then the function stops scanning and returns.
A whitespace character may match with any whitespace character (space, tab, carriage return,new line,
vertical tab, or formfeed) or the next incompatible character.
Formatted String Output:printf/fprintf:
Declarations:
intfprintf(FILE *stream, const char *format, ...);
intprintf(const char *format, ...);
The ..printf functions provide a means to output formatted information to a stream.
fprintf sends formatted output to a stream
printf sends formatted output to stdout
These functions take the format string specified by the format argument and apply each following
argument to the format specifiers in the string in a left to right fashion. Each character in the format
string is copied to the stream except for conversion characters which specify a format specifier.
String Input/Output
In addition to the Formatted string functions,C has two sets of string functions that read and write
strings without reformatting any data.These functions convert text file lines to strings and strings to
text file lines.
gets():
Declaration:
char *gets(char *str);
Reads a line from stdin and stores it into the string pointed to by str. It stops when either the newline
character is read or when the end-of-file is reached, whichever comes first. The newline character is
not copied to the string. A null character is appended to the end of the string.
On success a pointer to the string is returned. On error a null pointer is returned. If the end-of-file
occurs before any characters have been read, the string remains unchanged.
puts:
Declaration:
int puts(const char *str);
Writes a string to stdout up to but not including the null character. A newline character is appended to
the output.
On success a nonnegative value is returned. On error EOF is returned.
STRING HANDLING/MANIPULATION FUNCTIONS:
strcat( ) Concatenates two Strings
strcmp( ) Compares two Strings
strcpy( ) Copies one String Over another
strlen( ) Finds length of String
strcat() function:
This function adds two strings together.
Syntax: char *strcat(const char *string1, char *string2);
strcat(string1,string2);
string1 = VERY
string2 = FOOLISH
strcat(string1,string2);
string1=VERY FOOLISH
string2 = FOOLISH
Strncat: Append n characters from string2 to stringl.
char *strncat(const char *string1, char *string2, size_t n);
strcmp() function :
This function compares two strings identified by arguments and has a value 0 if they are equal. If they
are not, it has the numeric difference between the first non-matching characters in the Strings.
Syntax:intstrcmp (const char *string1,const char *string2);
strcmp(string1,string2);
Ex:-strcmp(name1,name2);
strcmp(name1,”John”);
strcmp(“ROM”,”Ram”);
Strncmp: Compare first n characters of two strings.
intstrncmp(const char *string1, char *string2, size_t n);
strcpy() function :
It works almost as a string assignment operators. It takes the form
Syntax: char *strcpy(const char *string1,const char *string2);
strcpy(string1,string2);
string2 can be array or a constant.
Strncpy: Copy first n characters of string2 to stringl .
char *strncpy(const char *string1,const char *string2, size_t n);
strlen() function :
Counts and returns the number of characters in a string.
Syntax:intstrlen(const char *string);
n= strlen(string);
n🡪integer variable which receives the value of length of string.
EXAMPLE:
/* Illustration of string-handling */
#include<stdio.h>
#include<string.h>
main()
{
char s1[20],s2[20],s3[20];
int X,L1,L2,L3;
printf(“Enter two string constants\n”);
scanf(“%s %s”,s1,s2);
X=strcmp(s1,s2);
if (X!=0)
{
printf(“Strings are not equal\n”);
strcat(s1,s2);
}
else
printf(“Strings are equal \n”);
strcpy(s3,s1);
L1=strlen(s1);
L2=strlen(s2);
L3=strlen(s3);
printf(“s1=%s\t length=%d chars \n”,s1,L1);
printf(“s2=%s\t length=%d chars \n”,s2,L2);
printf(“s3=%s\t length=%d chars \n”,s3,L3);
}
References:
1. https://www.cs.uic.edu/~jbell/CourseNotes/C_Programming/Arrays.html
2. https://www.studytonight.com/c/arrays-in-c.php
3. https://www.studytonight.com/c/arrays-in-c.php
4. https://www.programiz.com/c-programming/c-arrays
5. https://www.tutorialspoint.com/cprogramming/c_arrays.htm
Unit IV
Application of Algorithms
Binary Search
Binary Search is applied on the sorted array or list of large size. It's time complexity
of O(logn) makes it very fast as compared to other sorting algorithms. The only
limitation is that the array or list of elements must be sorted for the binary search
algorithm to work on it.
Algorithm:
BinarySearch(A, x):
where ‘A’ defines the array and ‘x’ is the element to be searched.
1. n = len(A)
2. beg = 0
3. end = n - 1
4. result = 0
5. while (beg <= end)
a. mid = (beg + end) / 2
b. if (A[mid] <= x)
i. beg = mid + 1
ii. result = mid
c. else
i. end = mid - 1
6. return result
Bubble Sorting:
Bubble sort starts with very first two elements, comparing them to check which one is
greater.
In this case, value 33 is greater than 14, so it is already in sorted locations. Next, we
compare 33 with 27.
We find that 27 is smaller than 33 and these two values must be swapped.
The new array should look like this −
Next we compare 33 and 35. We find that both are in already sorted positions.
We know then that 10 is smaller 35. Hence they are not sorted.
We swap these values. We find that we have reached the end of the array. After one
iteration, the array should look like this −
To be precise, we are now showing how an array should look like after each iteration.
After the second iteration, it should look like this −
Notice that after each iteration, at least one value moves at the end.
And when there's no swap required, bubble sorts learns that an array is completely sorted.
Algorithm:
We assume list is an array of n elements. We further assume that swap function swaps
the values of the given array elements.
beginBubbleSort(list)
swap(list[i], list[i+1])
end if
end for
return list
endBubbleSort
Insertion Sort:
This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained
which is always sorted. For example, the lower part of an array is maintained to be
sorted. An element which is to be 'insert'ed in this sorted sub-list, has to find its
appropriate place and then it has to be inserted there. Hence the name, insertion sort.
The array is searched sequentially and unsorted items are moved and inserted into the
sorted sub-list (in the same array). This algorithm is not suitable for large data sets as
2
its average and worst case complexity are of Ο(n ), where n is the number of items.
It finds that both 14 and 33 are already in ascending order. For now, 14 is in sorted
sub-list.
By now we have 14 and 27 in the sorted sub-list. Next, it compares 33 with 10.
So we swap them.
9
We swap them again. By the end of third iteration, we have a sorted sub-list of 4 items.
This process goes on until all the unsorted values are covered in a sorted sub-list.
Algorithm
Now we have a bigger picture of how this sorting technique works, so we can
derive simple steps by which we can achieve insertion sort.
The smallest element is selected from the unsorted array and swapped with the leftmost
element, and that element becomes a part of the sorted array. This process continues
moving unsorted array boundary by one element to the right.
This algorithm is not suitable for large data sets as its average and worst case
2
complexities are of O(n ), where n is the number of items.
For the first position in the sorted list, the whole list is scanned sequentially. The first
position where 14 is stored presently, we search the whole list and find that 10 is the
lowest value.
So we replace 14 with 10. After one iteration 10, which happens to be the minimum
value in the list, appears in the first position of the sorted list.
For the second position, where 33 is residing, we start scanning the rest of the list in a
linear manner.
We find that 14 is the second lowest value in the list and it should appear at the second
place. We swap these values.
14
After two iterations, two least values are positioned at the beginning in a sorted manner.
The same process is applied to the rest of the items in the array.
Following is a pictorial depiction of the entire sorting process −
15
Algorithm
Step 1 −Set MIN to location 0
Step 2 −Search the minimum element in the list
Step 3 −Swap with value at location MIN
Step 4 −Increment MIN to point to next element
Step 5 −Repeat until list is sorted
Algorithmic Complexity
Algorithmic complexity is concerned about how fast or slow particular algorithm
performs. A given algorithm will take different amounts of time on the same inputs
depending on such factors as: processor speed; instruction set, disk speed, brand of
compiler and etc. The way around is to estimate efficiency of each
algorithm asymptotically. We will measure time as the number of elementary "steps"
(defined in any way), provided each such step takes constant time.
Sometimes, there are more than one way to solve a problem. We need to learn how to
compare the performance different algorithms and choose the best one to solve a
particular problem. While analyzing an algorithm, we mostly consider time complexity
and space complexity. Time complexity of an algorithm quantifies the amount of time
taken by an algorithm to run as a function of the length of the input. Similarly, Space
complexity of an algorithm quantifies the amount of space or memory taken by an
algorithm to run as a function of the length of the input.
Example
Constant Time: O(1)
An algorithm is said to run in constant time if it requires the same amount of time
regardless of the input size. Examples:
● array: accessing any element
● fixed-size stack: push and pop methods
● fixed-size queue: enqueue and dequeue methods
Linear Time: O(n)
An algorithm is said to run in linear time if its time execution is directly proportional to
the input size, i.e. time grows linearly as input size increases. Examples:
● array: linear search, traversing, find minimum
● ArrayList: contains method
● queue: contains method
Types of Functions:
1. User-defined Functions
C allow programmers to define functions. Such functions created by the user are
called user-defined functions.
Syntax:
Function-type function-name ( argument list )
{
local variable declarations;
executable statement 1;
executabie statement 2;
----------
----------
----------
return (expression) ;
}
The return statement is the mechanism for returning a value to the calling function.
All functions by default returns int type data. we can force a function to return a
particular type of data by using a type specifier in the header.
A function can be called by simply using the function name in the statement.
Example:
#include <stdio.h>
voidfunctionName()
{
... .. ...
... .. ...
}
int main()
{
... .. ...
... .. ...
functionName();
... .. ...
... .. ...
}
Function Definition :
typefunc_name( parameter list )
{
//declarations;
//statements;
}
Function Header :
Function Calls :
When a function is called, expressions in the parameter list are evaluated (in no particular
order!) and results are transformed to the required type. Parameters are copied to local
variables for the function and function body is executed when return is encountered, the
function is terminated and the result (specified in the return statement) is passed to the calling
function (for example main).
Ex:
int fact (int n)
{
inti, product = 1;
for (i = 2; i<= n; ++i)
product *= i;
return product;
}
int main (void)
{
inti = 12;
printf(“%d”,fact(i));
return 0;
}
Parameter Passing Techniques:
Parameter passing mechanism in „C‟ is of two types.
1. Call by Value
2. Call by Reference.
The process of passing the actual value of variables is known as Call by Value.
The process of calling a function using pointers to pass the addresses of variables is known as
Call by Reference. The function which is called by reference can change the value of the variable
used in the call.
RECURSION:
Recursion is a repetitive process in which a function calls itself (or) a function is called
recursive if it calls itself either directly or indirectly. In C, all functions can be used
recursively.
In programming languages, if a program allows you to call a function inside the same
function, then it is called a recursive call of the function.
Example:
void recursion(){
recursion();/* function calls itself */
}
int main(){
recursion();
}
Examples on Recursion:
FACTORIAL
The following example calculates the factorial of a given number using a recursive function-
#include<stdio.h>
unsignedlonglongint factorial(unsignedinti){
if(i<=1){
return1;
returni* factorial(i-1);
int main(){
inti=12;
return0;
When the above code is compiled and executed, it produces the following result −
Factorial of 12 is 479001600
FIBONACCI SERIES
The following example generates the Fibonacci series for a given number using a recursive
function −
#include<stdio.h>
intfibonacci(inti){
if(i==0){
return0;
if(i==1){
return1;
returnfibonacci(i-1)+fibonacci(i-2);
int main(){
inti;
for(i=0;i<10;i++){
printf("%d\t\n",fibonacci(i));
return0;
When the above code is compiled and executed, it produces the following result −
0
1
1
2
3
5
8
13
21
34
Ackermann Function:
The Ackerman function is a well-known recursive function defined for m>= 0, n >= 0 as
follows:
A(m,n) = n+1, if m==0
A(m,n) = A(m-1,1), if m>0 and n==0
A(m-1,A(m,n-1)), if m>0 and
A(m,n) =
n>0
Find A(m,n) for the given m and n. The Ackerman function should be defined using
recursion only (hence use of arrays is not allowed). Also print the number of recursive calls
made to the function.
Input Format: The input contains the indices m and n separated by space.
Example:
Merge Sort
Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls
itself for the two halves and then merges the two sorted halves. The merge() function is used
for merging two halves. The merge(a[], l, m, h) is key process that assumes that a[l..m]
andarr[m+1..h] are sorted and merges the two sorted sub-arrays into one.Merge sort required
splitting and then merging of a pair of sorted arrays.
Merging steps involves:
1. Take two elements one from each array A and B.
2. Compare them and place smaller of two (say from A) in sorted list.
3. Take next element from A and compare with element in hand (from B).
4. Repeat until one of the array is exhausted.
5. Now place all remaining elements of non-empty array one by one.
C programming code:
Merging:
Merge sort
Main function:
ARRAY OF STRUCTURES :
To store more number of Structures, we can use array of Structures. In array of Structures all
elements of the array are stored in adjacent memory location.
/* Program to illustrate the usage of Array of Structures.
Void main()
{
struct book
{
char name[20];
float price;
int pages;
};
struct book b[10];
inti;
for (i=0;i<10;i++)
{
print(“\n Enter Name, Price and Pages”);
scanf(“%s%f%d”, b[i].name,&b[i].price,&b[i].pages);
}
for (ii=0;i<10;i++)
printf(“ \n%s%f%d”, b[i].name,b[i].price,b[i].pages);
}
POINTERS:
One of the powerful features of C is ability to access the memory variables by their memory
address. This can be done by using Pointers. The real power of C lies in the proper use of
Pointers.
A pointer is a variable that can store an address of a variable (i.e., 112300).We say that a
pointer points to a variable that is stored at that address. A pointer itself usually occupies 4
bytes of memory (then it can address cells from 0 to 232-1).
Advantages of Pointers:
1. A pointer enables us to access a variable that is defined out side the function.
2. Pointers are more efficient in handling the data tables.
3. Pointers reduce the length and complexity of a program.
4. They increase the execution speed.
Definition :
A variable that holds a physical memory address is called a pointer variable or Pointer.
Declaration :
Datatype * Variable-name;
Eg:-
int *ad; /* pointer to int */
char *s; /* pointer to char */
float *fp; /* pointer to float */
char **s; /* pointer to variable that is a pointer to char */
A pointer is a variable that contains an address which is a location of another variable in
memory.
Consider the Statement
p=&i;
Here “&‟ is called address of a variable.
“p‟ contains the address of a variable i.
The operator & returns the memory address of variable on which it is operated, this is called
Referencing.
The * operator is called an indirection operator or dereferencing operator which is used to
display the contents of the Pointer Variable.
Consider the following Statements :
int *p,x;
x =5;
p= &x;
Assume that x is stored at the memory address 2000. Then the output for the following printf
statements is :
Printf() statement Output
Printf(“The Value of x is %d”,x); 5
Printf(“The Address of x is %u”,&x); 2000
Printf(“The Address of x is %u”,p); 2000
Printf(“The Value of x is %d”,*p); 5
Printf(“The Value of x is %d”,*(&x)); 5
Representation:
A linked list is represented by a pointer to the first node of the linked list. The first node is
called head. If the linked list is empty, then value of head is NULL.
Each node in a list consists of at least two parts:
1) Data
2) Pointer (Or Reference) to the next node
In C, we can represent a node using structures. Below is an example of a linked list node with
an integer data.
Example:
UNIT –IX
File Handling in C Language
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 readymade 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 beginning 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,
*fpis 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 :
intfclose( 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.
main()
{
FILE *fp;
charch;
fp = fopen("one.txt", "w");
printf("Enter data");
}
fclose(fp);
fp = fopen("one.txt", "r");
while( (ch = getc()) != EOF)
printf("%c",ch);
fclose(fp);
}
Reading and Writing from File using fprintf() and fscanf()
#include<stdio.h>
#include<conio.h>
structemp
{
char name[10];
int age;
};
void main()
{
structemp 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
{
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.
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() andfwrite() 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.
Belowmentioned is a simple example of writing into a binary file
const char *mytext = "The quick brown fox jumps over the
lazy dog";
fwrite(mytext,sizeof(char),strlen(mytext),bfp)
;fclose(bfp) ;
}
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.