Você está na página 1de 184

C Language History

August 9 2016

The C programming language is a structure oriented programming language,

developed at Bell Laboratories in 1972 by Dennis Ritchie.


C programming language features were derived from an earlier language called

B (Basic Combined Programming Language BCPL).


C language was invented for implementing UNIX operating system.
In 1978, Dennis Ritchie and Brian Kernighan published the first edition.The C

Programming Language and commonly known as K&R C.


In 1983, the American National Standards Institute (ANSI) established a
committee to provide a modern, comprehensive definition of C. The resulting
definition, the ANSI standard, or ANSI C, was completed late 1988.

FEATURES OF C PROGRAMMING LANGUAGE:


Reliability
Portability
Flexibility
Interactivity
Modularity
Efficiency and Effectiveness

2
USES OF C PROGRAMMING LANGUAGE:
The C programming language is used for developing system applications that forms a
major portion of operating systems such as Windows, UNIX and Linux. Below are some
examples of C being used.

Database systems
Graphics packages
Word processors
Spreadsheets
Operating system development
Compilers and Assemblers
Network drivers
Interpreters
WHICH LEVEL IS C LANGUAGE BELONGING TO?
1

High Level
High level languages
provide
almost
everything
that
the
programmer might need
to do as already built
into the language.
Examples:
Java, Python
4

Middle Level
Middle level languages dont
provide all the built-in
functions found in high level
languages, but provide all
building blocks that we need
to produce the result we
want.
C, C++

Low Level
Low
level
languages provides
nothing other than
access
to
the
machines
basic
instruction set.
Assembler

THE C LANGUAGE IS A STRUCTURED LANGUAGE


Structure oriented

Object oriented

Non structure

In this type of language, In this type of language, There is no specific


large programs are divided programs are divided into structure

for

into small programs called objects

programming

this

functions

language

Prime focus is on functions Prime focus is in the data

N/A

and procedures that operate that is being operated and


on the data

not on the functions or


procedures

Data moves freely around Data is hidden and cannot


the

systems

from

function to another

N/A

one be accessed by external


functions

Program structure follows Program structure follows

N/A

Top Down Approach

Bottom UP Approach

Examples:

C++, JAVA and C# (C

BASIC, COBOL,

C, Pascal, ALGOL and

sharp)

FORTRAN

Modula-2

C Basic Program
2

We are going to learn a simple Hello World C program in this section. Also, all the
below topics are explained in this section which are the basics of a C program.
1. C basic program with output and explanation
2. Steps to write C programs and get the output
3. Creation, Compilation and Execution of a C program
How to install C compiler and IDE
4. Basic structure of a C program
1

BASIC COMMANDS IN C PROGRAMMING TO WRITE BASIC C


PROGRAM:
Below are few commands and syntax used in C programming to write a simple C
program. Lets see all the sections of a simple C program line by line.
S.no

Command

Explanation

#include <stdio.h>

This is a preprocessor command that includes


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

int main()

This is the main function from where


execution of any C program begins.

This indicates the beginning of the main


function.

/*_some_comments_*/

whatever is given inside the command /*


*/ in any C program, wont 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.

return 0;

This command terminates C program (main


function) and returns 0.

8
2

This indicates the end of the main function.

C BASIC PROGRAM:
#include<stdio.h>
void main()
3

{
/* our first simple C basic program */
printf(Hello World);
getch();
return 0;
}
OUTPUT:
Hello World
3

STEPS TO WRITE C PROGRAMS AND GET THE OUTPUT:

Below are the steps to be followed for any C program to create and get the output.
This is common to all C program and there is no exception whether its a very small C
program or very large C program.
Create
Compile
Execute or Run
Get the Output

4
4.1

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 in your machine. Then, you can start to execute your own C

programs in your machine.


You can refer below link for how to install C compiler and compile and execute C

programs in your machine.


Once C compiler is installed in your machine, you can create, compile and
execute C programs.

BASIC STRUCTURE OF C PROGRAM:


4

Structure of C program is defined by set of rules called protocol, to be followed


by programmer while writing C program. All C programs are having
sections/parts which are mentioned below.
1. Documentation section
2. Link Section
3. Definition Section
4. Global declaration section
5. Function prototype declaration section
6. Main function
7. User defined function definition section

DESCRIPTION FOR EACH SECTION OF A C PROGRAM:

Let us see about each section of a C basic program in detail below.

Please note that a C program maynt have all below mentioned sections

except main function and link sections.


Also, a C program structure maynt be in below mentioned order.

S.No
1

Sections

Description

Documentation

We can give comments about the program, creation

section

or modified date, author name etc in this


section. The characters or words or anything which
are given between /* and */, wont be
considered

by

compiler

for

compilation

process.These will be ignored by C compiler


during

compilation.

Example: /* comment line1 comment line2


comment 3 */
2

Link Section

Header files that are required to execute a C


program are included in this section

Definition Section In this section, variables are defined and values are
5

set to these variables.


4

Global

Global variables are defined in this section. When a

declaration

variable is to be used throughout the program, can

section

be defined in this section.

Function

Function prototype gives many information about a

prototype

function like return type, parameter names used

declaration

inside the function.

section
6

Main function

Every C program is started from main function and


this function contains two major sections called
declaration section and executable section.

User defined

User can define their own functions in this section

function section

which perform particular task as per the user


requirement.

C Printf and Scanf

Printf () and scanf() functions are inbuilt library functions in C which are
available in C library by default. These functions are declared and related macros

are defined in stdio.h which is a header file.


We have to include stdio.h file as shown in below C program to make use of
these printf() and scanf() library functions.

C PRINTF () FUNCTION:
printf() function is used to print the character, string, float, integer, octal and

hexadecimal values onto the output screen.


We use printf() function with %d format specified to display the value of an

integer variable.
Similarly %c is used to display character, %f for float variable, %s for string

variable, %lf for double and %x for hexadecimal variable.


To generate a newline, we use \n in C printf() statement.

Note:
6

C language is case sensitive. For example, printf() and scanf() are different from
Printf() and Scanf(). All characters in printf() and scanf() functions must be in
lower case.

EXAMPLE PROGRAM FOR C PRINTF() FUNCTION:


#include <stdio.h>
void main()
{
char ch = A;
char str[20] = B.Tech student;
float flt = 10.234;
int no = 150;
double dbl = 20.123456;
printf(Character is %c \n, ch);
printf(String is %s \n , str);
printf(Float value is %f \n, flt);
printf(Integer value is %d\n , no);
printf(Double value is %lf \n, dbl);
printf(Octal value is %o \n, no);
printf(Hexadecimal value is %x \n, no);
return 0;
}
Output:
Character is A
String is B.Tech students
Float value is 10.234000
Integer value is 150
Double value is 20.123456
Octal value is 226
Hexadecimal value is 96
You can see the output with the same data which are placed within the double quotes of
printf statement in the program except
%d got replaced by value of an integer variable (no),

%c got replaced by value of a character variable (ch),

%f got replaced by value of a float variable (flt),

%lf got replaced by value of a double variable (dbl),

%s got replaced by value of a string variable (str),


7

%o got replaced by a octal value corresponding to integer variable (no),

%x got replaced by a hexadecimal value corresponding to integer variable

\n got replaced by a newline.

C SCANF () FUNCTION:
Scanf() function is used to read character, string, numeric data from keyboard

Consider below example program where user enters a character. This value is

assigned to the variable ch and then displayed.


Then, user enters a string and this value is assigned to the variable str and then

displayed.
EXAMPLE PROGRAM FOR PRINTF() AND SCANF() FUNCTIONS IN C:
#include <stdio.h>
void main()
{
char ch;
char str[100];
printf(Enter any character \n);
scanf(%c, &ch);
printf(Entered character is %c \n, ch);
printf(Enter any string ( upto 100 character ) \n);
scanf(%s, &str);
printf(Entered string is %s \n, str);
}
Output:
Enter any character
a
Entered character is a
Enter any string ( upto 100 character )
hai
Entered string is hai

The format specifier %d is used in scanf() statement. So that, the value entered is

received as an integer and %s for string.


Ampersand (&) is used before variable name ch in scanf() statement as &ch.
It is just like in a pointer which is used to point to the variable

ALGORITHM
8

A step by step procedure for solving a particular problem is an Algorithm. To be an


algorithm, a set of rules must be unambiguous and have a clear stopping point.
Algorithms can be expressed in any language, from natural languages like English or
French to programming languages like FORTRAN, C.
Example:
Program for to calculate quadratic equation ax2+bx+c
Hint: d = sqrt (), and the roots are: x1 = (b + d)/2a and x2 = (b d)/2a
Algorithm:
Step 1:

Input the coefficients (a, b, c) of the quadratic equation

Step 2:

Calculate d using d sqrt ( )

Step 3:

Calculate x1 using x1 (b + d) / (2 x a)

Step 4:

Calculate x2 using x2 (b d) / (2 x a)

Step 5:

Print x1 and x2

FLOW CHART
A graphical representation of the sequence of operations in an information system
or program is called.
Information system flowcharts show how data flows from source documents
through the computer to final distribution to users. Program flowcharts show the
sequence of instructions in a single program or subroutine. Different symbols are
used to draw each type of flowchart.
A Flowchart

Shows logic of an algorithm


Emphasizes individual steps and their interconnections
e.g. control flow from one action to the next

Flow Chart Symbols:


Name

Symbol

Use in Flowchart

Oval
Denotes the beginning or end
of the program
Parallelogram

Denotes an input operation


9

Rectangle

Denotes a process to be
carried out e.g. addition,
subtraction, division etc.
Denotes a decision (or
branch) to be made. The
program should continue
along one of two routes. (e.g.
IF/THEN/ELSE)

Diamond

Hybrid
Denotes an output operation
Flow line

Denotes the direction of logic


flow in the program

VIVA QUESTION AND ANSWERS


1. Who is the father of C language?
Answer: Dennis Ritchie
2. Who invented B language?
Answer: Martin Richards
10

3. What is meant by Program?


Answer: program is a set of instructions.
4. What is a Pseudocode
Answer: It is a tool used for planning a computer program logic or method.
pseudo means imitation, and code refers to the instructions.
5. What is meant by Algorithm?
Answer: The step by step procedure can be called as algorithm.
6. What is meant by Flowchart?
Answer: Flowchart is diagrammatic representation of an algorithm. It is
constructed using different types of boxes and symbols.

How to Write and Run C Programs in Ubuntu (Linux)


1. First of all open terminal window, for this go to Applications> Accessories>
Terminal, as shown in below image.

11

2.

Now its time to write and run the program. Below i have explained simple steps
for both c and c++.
For C Program

1. Enter the command given below in terminal window to open text editor.
gedit prog.c
Here prog.c is the name of the program. After entering above code it will ask for
password.
2. Now write your program, for your convenience i have given an sample program
below, you can copy and paste it in gedit text editor.
#include<stdio.h>
int main()
{
printf(\n This is C Programming in Ubuntu);
return 0;
}
3. Now save and close the editor.
4. To compile the program enter the command given below in terminal window.
gcc prog.c -o prog

12

5.

If there will be no error in the program then nothing will be shown. And if error
occurs, it will be shown. In case you get an error you have to open the text editor
again by repeating step 1 and remove it and again save and close the editor.

6. Enter the command given below to run the program.


./prog
7. Now you will see the output in the terminal window as shown in below image.

Exercise -1 Basics
a) What is an OS Command, Familiarize of Editors vi, Emacs
13

Vi:

The vi editor is available in almost all systems.


vi can used for any type of terminal because it doesnt depend on arrow key &

function key. It uses like standard alphabetic key of commands.


vi (pronounced vee-eye) is short for visual editor.
It display window into a file being edited that shows 24 lines of text
vi is a text editor
vi lets you add, change and delete text, but doesnt provide such formality
capabilities an creating a line (or) identity programs.

This help note explains the basic of vi:

Opening and closing a file


Moving around in a file
Elementary editing
.Starting vi ..
You may use vi to open an already existing file by typing vi file name Where;
File name is the name of existing file
If the file is not in your current directory, you must use the full path name
(or)
You may create a new file name by typing
vi new name
where;
New name is the name you wish to give the new file. One-screen, you
will see blank line, each a tilde(~) at the left, and a line at the bottom given the
name and status of the file name
~
~
Vi [new file]
-------------------Vi modes---------------Vi has 2 modes
1. Command mode
2. Insert mode

1.

Command mode:
The letters of the key word perform editing functions.
To enter command mode, press the escape & <ESC> key.
14

2.

Insert mode:
The letters you type form words and sentences.
Unlike, many word processors, vi start up in command mode.

1.

Getting Out of vi:

The command to quit out of vi is :q. Once in command mode, type colon, and 'q',
followed by return. If your file has been modified in any way, the editor will warn you
of this, and not let you quit. To ignore this message, the command to quit out of vi
without saving is :q!. This lets you exit vi without saving any of the changes.
The command to save the contents of the editor is :w. You can combine the above
command with the quit command, or :wq and return.
The easiest way to save your changes and exit out of vi is the ZZ command. When you
are in command mode, type ZZ and it will do the equivalent of :wq.
You can specify a different file name to save to by specifying the name after the :w. For
example, if you wanted to save the file you were working as another filename called
filename2, you would type :w filename2 and return.

Emacs:
Emacs is another editor available in UNIX.
Like vi, emacs is a screen editor.
Unlike vi, emacs is not an insertion mode editor, meaning that any character typed
in emacs is automatically inserted into the file, unlessit includes a command
prefix.
Commands in emacs are either control characters (hold down the <Ctrl> key
while typing another character) or are prefixed by one of a set of reserved
characters: <Esc> or <Ctrl>-X.
The <Esc> key can be typed by itself (because it really is a character) and then
followed by another character; the <Ctrl> key must be held down while the next
character is being typed.

15

The conventions for describing these characters (since it takes too long to type out
the whole thing) are ESC means <Esc> and C- means <Ctrl>.
One other distinction between emacs and vi is that emacs allows you to edit
several files at once.
The window for emacs can be divided into several windows, each of which
contains a view into a buffer.
Each buffer typically corresponds to a different file.
Many of the commands listed below are for reading files into new buffers and
moving between buffers.
To use emacs on a
file, type
emacs filename

If the file named filename exists, then the first screen's worth of the file is
displayed; if it doesn't exist, a help message is displayed.
The easiest way to learn emacs is to start it up and go through the on-line tutorial.
To access the on-line tutorial, type ESC help-with-tutorial immediately after you
have started emacs.
The tutorial directs you further in learning the basic commands. One notational
point you should know is that the tutorial uses M- to mean ESC.
To give you a head start, the following table lists the basic commands you need to
know to use emacs to edit a file.
An asterisk (* or star) to the left of a command indicate it is one to learn
immediately.

b) Using commands like mkdir, ls, cp, mv, cat, pwd, and man.
MKDIR COMMAND:
MKDIR file name will create a new directory i.e. here file name directory is
created.
aiet@ubuntu:~$ mkdir file name
LS COMMAND:
LS command is most widely used command and it displays the context of
directory.
aiet@ubuntu:~$ ls
CP COMMAND:
CP command copies a file. if I want to copy a file named old file in a current
directory to a file named new file in a current directory.
16

aiet@ubuntu:~$ cp old file new file


MV COMMAND:
MV command is used to move a file from one directory to another directory
aiet@ubuntu:~$ cp old file new file
CAT COMMAND:
CAT command To displays contents of a file.
aiet@ubuntu:~$ cat >rat
PWD COMMAND:
PWD command will print a home directory on screen.
pwd means print working directory
aiet@ubuntu:~$ pwd
/home/aiet
MAN COMMAND:
This is help command, and will explain you about online manual pages you can
also use man in conjugation with any commands to learn more about the
command.
aiet@ubuntu:~$ man ls

c) C Program To Perform Adding, Subtraction, Multiplication and Division Of


Two Numbers From Command Line
DESCRIPTION:
An arithmetic operator in C Programming language includes operators like Addition,
Subtraction, Multiplication, Division and Modulus. All these operators are binary
operators which means they operate on two operands. Below table shows all the
Arithmetic Operators in C language with examples.
ARITHMETIC OPERATORS IN C
+
*
/
%

OPERATION
Addition
Subtraction
Multiplication
Division
Modulus It
returns the
remainder after
17

EXAMPLE
10 + 2 = 12
10 2 = 8
10 * 2 = 20
10 / 2 = 5
10 % 2 = 0 (Here
remainder is zero). If it
is 10 % 3 then it will

the division
ALGORITHM:
Step: 1 Read the numbers first, second;
Step: 2 Calculate

add = first+second

subtract = first-second

multiply = first*second

divide = first/second

Step: 3 Print add, subtract, multiply and the divide.


Step: 4 Stop

FLOWCHART:

18

be 1.

PROGRAM: aiet@ubuntu:~$ gedit add.c

19

#include <stdio.h>
void main()
{
int first, second, add, subtract, multiply;
float divide;
printf("\n Enter two integers:");
scanf("%d%d", &first, &second);
add = first + second;
subtract = first - second;
multiply = first * second;
divide = first / second;
printf("Sum = %d\n",add);
printf("Difference = %d\n",subtract);
printf("Multiplication = %d\n",multiply);
printf("Division = %f\n",divide);
return 0;
}
OUTPUT:
aiet@ubuntu:~$ gcc add.c
aiet@ubuntu:~$ ./a.out
Enter two integers: 4

Sum = 9
Difference = -1
Multiplication = 20
Division = 0.00000

VIVA QUESTION AND ANSWERS


1. What is C Tokens
20

Answer: Keywords, Identifier, Constant, Variable, Operator, etc.,

2. What is meant by Computer


Answer: Computer is a fastest electronic device. that accepts information and
manipulates it for some result based on a program.

3. What is Syntax Error


Answer: These errors are due to wrongly typed statements, which are not
according to the syntax or grammatical rules of a language.

4. What is an Operator
Answer: An operator is a symbol that tells the compiler to perform specific
mathematical or logical functions.

5. What is a Assignment Operators


Answer: =, +=, <<=, >>=, !=

6. What is Unary Operator


Answer: !, +, &, *, ++, --.

Exercise - 2 Basic Math


a) Write a C program to simulate 3 laws at Motion.
DESCRIPTION:
21

The total distance travelled by vehicle int seconds is given by s = ut+1/2at2 where 'u'
and 'a' are the initial velocity (m/sec.) and acceleration (m/sec2).
ALGORITHM:
Step1: [declaring variables]
declaration of variables u, a, s, t
Step2: [reading variables]
read a, u, t
Step3: [calculating value of s]
s= (u*t)+(a*t*t)/2
Step4: [print the value of s]
print the distance is equal to: s
Step5: [end of program]
stop
FLOWCHART:

PROGRAM: aiet@ubuntu:~$ gedit motion.c


#include<conio.h>
#include<stdio.h>
void main()
22

{
float u,a,s;
int t;
clrscr();
printf(" Enter the value of a: ");
scanf("%f",&a);
printf(" Enter the year of u: ");
scanf("%f",&u);
printf(" Enter the value of t: ");
scanf("%d",&t);
s = (u * t) + (a * t * t)/2;
printf("\n The distance equal to: %f",s);
getch();
}
OUTPUT:
aiet@ubuntu:~$ gcc motion.c
aiet@ubuntu:~$ ./a.out
Enter the value of a: 4
Enter the year of u: 5
Enter the value of t: 6
The distance equal to: 102.000000

b) Write a c program to convert Celsius to Fahrenheit and vice versa.


ALGORITHM:
Step: 1 Read the temperature in degree Centigrade.
Step: 2 Convert the Centigrade to Fahrenheit using the formula
23

F=9/5*c+32
Step: 3 Print the Celsius and Fahrenheit value.
Step: 4 Read the temperature in degree Fahrenheit.
Step: 5 Convert the Fahrenheit to Centigrade using the formula
C=5/9*(F-32)
Step: 5 Print the Fahrenheit and Celsius value.
Step: 6 Stop
FLOWCHART:

PROGRAM: aiet@ubuntu:~$ gedit temperature.c


#include<stdio.h>
#include<conio.h>
void main()
{
float

c,f;
24

clrscr();
printf("\n Enter the temperature in centigrade:");
scanf("%f",&c);
f=1.8*c+32;
printf("\n\t%f Centigrade=%f Fahrenheit",c,f);
printf("\n\n Enter the temperature in Fahrenheit:");
scanf("%f",&f);
c=(f-32)/1.8;
printf("\n\t%f Fahrenheit=%f Centigrade",f,c);
getch();
}
OUTPUT:
aiet@ubuntu:~$ gcc temperature.c
aiet@ubuntu:~$ ./a.out
Enter the temperature in centigrade: 45
45.00 Centigrade=113.00 Fahrenheit
Enter the temperature in Fahrenheit: 114
114.0

Fahrenheit=45.56 Centigrade

VIVA QUESTION AND ANSWERS

1. What are the different Arithmetic Operators?


Answer: addition, subtract, multiplication, division.

2. What is an Arithmetic Expression?


25

Answer: Integer mode, Real mode, Mixed mode.

3. What are the various Logical Operator?


Answer: AND, OR, NOT,

4. Explain the C data types ?


Answer: Built in, Derived, Used defined, Void

5. What are the various Relational Operators?


Answer: <, >, <=, >=, = =, !=

6. Difference between the void main() and int main()?


Answer: int main: means you will end your program with return 0;
Void main: will allow you to skip that line, and have some other
effects.

Exercise -3 Control Flow I


a) Write a c program to find whether the given year is a leap year or not.
DESCRIPTION:
A leap year has 366 days instead of the usual 365, by extending February to 29
days rather than the common 28 days.
Definition of leap year:
26

Rule 1: A year is called leap year if it is divisible by 400.


For example: 1600, 2000 etc leap year while 1500, 1700 are not leap year.
Rule 2: If year is not divisible by 400 as well as 100 but it is divisible by 4 then that year
are also leap year.
For example: 2004, 2008, 1012 are leap year.
ALGORITHM:
Step: 1 Start
Step: 2 Read year
Step: 3 If year%4=0 and year%100!=0 or if year%4=0 and year%400=0 then go to step 4
else go to step 5
Step: 4 Print a leap year
Step: 5 Print not a leap year
Step: 6 Stop

FLOWCHART:

27

PROGRAM: aiet@ubuntu:~$ gedit leap.c


#include<stdio.h>
#include<conio.h>
28

void main()
{
int year;
clrscr();
printf("\n Enter any year: ");
scanf("%d",&year);
if(((year%4==0)&&(year%100!=0))||(year%400==0))
printf("%d is a leap year",year);
else
printf("%d is not a leap year",year);
getch();
}
OUTPUT:
aiet@ubuntu:~$ gcc leap.c
aiet@ubuntu:~$ ./a.out
Enter any year: 2015
Is not a leap year

Enter any year: 2016


Is a leap year

b) Write a c program to add digits of a number


ALGORITHM:
Step1: [declaration of integer variables]
declare num, sum=0, r
29

Step2: [read numbers]


read num
Step3: [repitition loop]
while (num) then follow the steps otherwise go to step 6
Step4: [calculate r, num, sum]
r=num%10
num=num/10
sum=sum+r
Step5: [print sum]
print sum of digits of numbers; sum
Step6: [end of program]
stop

FLOWCHART:

30

PROGRAM: aiet@ubuntu:~$ gedit digit.c


#include<stdio.h>
31

#include<conio.h>
void main()
{
int num,sum=0,r;
clrscr();
printf("\n Enter a number: ");
scanf("%d",&num);
while (num)
{
r=num%10;
num=num/10;
sum=sum+r;
}
printf("Sum of digits of number: %d",sum);
getch();
}
OUTPUT:
aiet@ubuntu:~$ gcc digit.c
aiet@ubuntu:~$ ./a.out
Enter a number: 123
Sum of digits of number: 6

Write a c program to multiplication of a number


ALGORITHM:
32

Step1: [declare variables]


declare num, mul=1,r
Step2: [read number]
read num
Step3: [repitition loop]
while (num) then follow the steps otherwise go to step6
Step4: [calculate r, num, mul]
r=num%10
num=num/10
mul=mul*r
Step5: [print mul]
print multiplication of digits of number: mul
Step6: [end of program]
stop

FLOWCHART:

33

PROGRAM: aiet@ubuntu:~$ gedit multiplication.c


#include<stdio.h>
34

#include<conio.h>
void main()
{
int num,mul=1,r;
clrscr();
printf("\n Enter a number:");
scanf("%d",&num);
while (num)
{
r=num%10;
num=num/10;
mul=mul*r;
}
printf("multiplication of digits of number: %d",mul);
getch();
}
OUTPUT:
aiet@ubuntu:~$ gcc multiplication.c
aiet@ubuntu:~$ ./a.out
Enter a number:124
multiplication of digits of number: 8

VIVA QUESTION AND ANSWERS

1. What is getch() function


35

Answer: getch() is used to hold the console window on the screen after the whole
program run is compileted.

2. What is the use of %d


Answer: To display the value of an integer variable.
3. What is the use of \n
Answer: To create the new line
4. Write the Syntax for IF Statement?
Answer: if(conditional-expression)
{
Statement block;
}
5. Define Conditional Statements
Answer: If statement, if-else statement, nested if-else statement, switch
statement.
6. Write Syntax for WHILE Statement?
Answer: while(conditional expression)
{
Statement- block;
}

Exercise 4 Control Flow II


a) Write a C program to Find Whether the Given Number is
i. Prime Number

36

DESCRIPTION:
This is a C code tutorial to check the input number is prime number or not by using
conditional if-else statement and display on the output screen.
PRIME NUMBER:
A prime number is a natural number greater than 1 that has no positive divisor other
than 1 and itself (or) we can say that prime number is divided without a reminder only
by itself and by 1. (i.e: 2, 3, 5, 7, 11, 13, 17.....etc.)
ALGORITHM:
Step1: [declaration of variables]
Declare variables n, i, c=0
Step2: [read n value]
read n
Step3: [repitition using loop]
for i=1 to n
Step4: [decision making loop]
if (n%i==0) then follow the steps otherwise go to step6
Step5: [increment c]
c++
Step6: [decision making loop]
if (c==2) then follow the steps otherwise go to step 8
Step7: [print about the number]
print n is a prime number
Step8: [decision making loop]
else
Step9: [print about the number]
print n is not a prime number
Step10: [end of program]
stop
FLOWCHART:
37

PROGRAM: aiet@ubuntu:~$ gedit prime.c


#include <stdio.h>
#include<conio.h>
void main()
38

{
int n, i, c = 0;
clrscr();
printf("\n Enter any number n:");
scanf("%d", &n);
/*logic*/
for (i = 1; i <= n; i++)
{
if (n % i == 0)
{
c++;
}
}
if (c == 2)
{
printf("n is a Prime number");
}
else
{
printf("n is not a Prime number");
}
getch();
}
OUTPUT:
aiet@ubuntu:~$ gcc prime.c
aiet@ubuntu:~$ ./a.out
Enter any number n: 7
39

n is a Prime number

b) Write a C program to Find Whether the Given Number is


ii. Armstrong Number
DESCRIPTION:
This is a C code tutorial to check the input number is a armstrong number or not.

40

ARMSTRONG NUMBER:
Armstrong number is a special number whose sum of cube of its digits is equal to the
original number.
For example: 371 is an Armstrong number because 33 + 73 + 13 = 371 .
Example:
Input Numbers

Cube sum of the Individual Digits

Armstrong Number

34

32 + 42 = 25 34

No

153

13 + 53 + 33 = 153 = 153

Yes

1634

14 + 64 + 34 +44 = 1643 = 1634

Yes

54748

55 + 45 + 75 + 45 + 85 = 54748 = 54748

Yes

ALGORITHM:
Step1: [declaration of variables]
declare number, original number, remainder,result=0
Step2: [read number]
read number
Step3: [storing the value of number in original number]
41

original number= number


Step4: [repitition using loop]
while (original number! =0) if yes the follow the steps otherwise go to step6
Step5: [calculate remainder,result,original number]
remainder=original number%10
result+=remainder*remainder*remainder
original number/=10
Step6: [decision making loop]
if (result==number) then follow the steps otherwise go to step 8
Step7: [print about armstrong number]
print number is an armstrong number
Step8: [decision making loop]
else
Step9: [print about armstrong number]
print number is not an arstrong number
Step10: [end of program]
stop

FLOWCHART:

42

PROGRAM: aiet@ubuntu:~$ gedit armstrong.c


#include <stdio.h>
#include<conio.h>
43

void main()
{
int number, originalNumber, remainder, result = 0;
clrscr();
printf("\n Enter a three digit integer:");
scanf("%d", &number);
originalNumber = number;
while (originalNumber != 0)
{
remainder = originalNumber%10;
result += remainder*remainder*remainder;
originalNumber /= 10;
}
if(result == number)
printf("%d is an Armstrong number.",number);
else
printf("%d is not an Armstrong number.",number);
getch();
}
OUTPUT:
aiet@ubuntu:~$ gcc armstrong.c
aiet@ubuntu:~$ ./a.out
Enter a three digit integer: 371
371 is an Armstrong number.
b).Write a c program to print Floyd's triangle
DESCRIPTION:
Number of rows of Floyd's triangle to print is entered by the user.
44

First four rows of Floyd's triangle are as follows:


1
23
456
7 8 9 10
It's clear that in Floyd's triangle nth row contains n numbers.
ALGORITHM:
Step1: [declare variables]
declare variables r, i, j, c=1
Step2: [read no. of rows]
read r
Step3: [repetition using loop]
for i=0 to r
Step4: [repetition using loop]
for j=0 to i
Step5: [print the value of c]
print c
Step6: [increment c]
c++
Step7: [end of a program]
stop

FLOWCHART:

45

PROGRAM:
aiet@ubuntu:~$ gedit
floyd.c
#include <stdio.h>
void main()
{
int n, i, c, a = 1;
printf("Enter the
number of rows of
Floyd's triangle to print:
\n");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
for (c = 1; c <= i; c+
+)
{
printf("%d ",a);
a++;
}
printf("\n");
}
return 0;
}
OUTPUT:
aiet@ubuntu:~$ gcc floyd.c
aiet@ubuntu:~$ ./a.out
Enter the number of rows of Floyds triangle to print: 4
1
46

2 3
4 5
7 8

6
9

10

c). Write a c program to print Pascal triangle


DESCRIPTION:
C program to print Pascal triangle which you might have studied in Binomial Theorem in
Mathematics. Number of rows of Pascal triangle to print is entered by the user.
First four rows of Pascal triangle are shown below:
1
11
121
1331
PROGRAM: aiet@ubuntu:~$ gedit pascal.c
#include <stdio.h>
long factorial(int);
int main()
{
int i, n, c;
printf("Enter the number of rows you wish to see in pascal triangle: \n");
scanf("%d",&n);
for (i = 0; i < n; i++)
{
for (c = 0; c <= (n - i - 2); c++)
printf(" ");
47

for (c = 0 ; c <= i; c++)


printf("%ld ",factorial(i)/(factorial(c)*factorial(i-c)));
printf("\n");
}
return 0;
}
long factorial(int n)
{
int c;
long result = 1;
for (c = 1; c <= n; c++)
result = result*c;
return result;
}
OUTPUT:
aiet@ubuntu:~$ gcc pascal.c
aiet@ubuntu:~$ ./a.out
Enter the number of rows wish to see in Pascal triangle: 5
1
1
1
1
1

1
2

3
4

1
3

1
4

48

VIVA QUESTION AND ANSWERS


1. Write Syntax for For Statement?
Answer: for(initialization; conditional-expression; increment)
{
Statement-block;
}
2. Difference between the Increment and Decrement Operator
Answer: Increment operator: are used to increase the value of the variable by
one.
Decrement operator: are used to decrease the value of the variable by
one
3. What is the Difference between for loop and while loop?
Answer: This question is already repeated in previous question
4. What is the difference between #include< > and #include ?
Answer: #include<file> searches the file in the specified list of directories.
#include"file" searches the file in the current working directory as wel as in the
specified list of directories.
5. What are Unconditional Statements?
Answer: Break and continue
6. Write Syntax for DO- WHILE Statement?
Answer: do
{
Statement-block;
}
49

While(conditional-expression);

Exercise 5 Functions
1. Write a C program demonstrating of parameter passing in function and
return values.
DESCRIPTION:
Parameter Passing is a technique for communication of data (or) information between the
calling function and the called function. It can be achieved either by passing the value or
address of the variable.
There are two types of parameter passing techniques:
1. Call by value: It does not change the argument variable in the calling function,
even if they are changed in the called function.
2. Call by Address: C provides another means of passing values to a function
known as call by address.
PROGRAM: aiet@ubuntu:~$ gedit parameter.c
#include<stdio.h>
#include<conio.h>
#include<math.h>
int sum(int a,int b);
int main()
{
int a,b,c;
printf("\n enter the two numbers:");
scanf("%d%d",&a,&b);
c=sum(a,b);
printf("\n total=%d",c);
50

}
int sum(int a,int b)
{
int result;
result=a+b;
return result;
}
OUTPUT:

aiet@ubuntu:~$ gcc parameter.c


aiet@ubuntu:~$ ./a.out
Enter the two numbers: 20

30

Total=50

51

2. Write a C program to find factorial of a given number using recursion


without recursion.
DESCRIPTION:
Factorial of a number is nothing but the multiplication of numbers from a given number
to 1.
The operation of recursive factorial function is as follows:
Start out with some natural number N.
The definition is:
n=0, 0!=1 ---------- Base case
n>0, n!=n*(n-1)! ----------- Recursive case.
Example:
5! = 5*(5-1)! = 5*4! = 5*24 = 120
4! = 4*(4-1)! = 4*3! = 4*6 = 24
3! = 3*(3-1)! = 3*2! = 3*2 = 6
2! = 2* (2-1)! = 2*1! = 2*1 = 2
1! = 1*(1-1)1 = 1*0! = 1*1 = 1
0! = 1
PROGRAM: aiet@ubuntu:~$ gedit factorial.c
#include<stdio.h>
#include<conio.h>
void main()
{
int n,a,b;
clrscr();
printf("\n Enter the numbers:");
scanf("%d",&n);
a=recfactorial(n);
printf("\n The factorial of given number using recursion is:%d",a);
52

b=nonrecfactorial(n);
printf("\n The factorial of given number using nonrecursion is:%d",b);
getch();
}
int recfactorial(int x)
{
int f;
if(x==0)
return 1;
else
{
f=x*recfactorial(x-1);
return f;
}
}
int nonrecfactorial(int x)
{
int i,f=1;
for(i=1;i<=x;i++)
{
f=f*i;
}
return f;
}
OUTPUT:
aiet@ubuntu:~$ gcc factorial.c
aiet@ubuntu:~$ ./a.out
Enter the number:6
The factorial of given number using recursion is:720
The factorial of given number using nonrecursion is:720
53

3. Write a C program to find Fibonacci sequence using Recursion without


Recursion.
DESCRIPTION:
A Fibonacci sequence starts with the integers 0 and 1. Successive elements in this
sequence are obtained by summing the preceding two elements in the sequence.
Example:
Third number in the sequence is: First number + Second number
: 0+1=1
Fourth number in the sequence is: Second number + Third number
: 1+1=2
Fifth number in the sequence is: Third number + Fourth number
: 1+2=3
and so on..
The sequence of Fibonacci integers is given below:
0

13

21

..

The recursive definition for the Fibonacci sequence of integers may be defined as
follows:
fib(n)=n; if n=0 or n=1
fib(n)=fib(n-1)+fib(n-2); for n>=2

PROGRAM: aiet@ubuntu:~$ gedit fibonacci.c


54

#include<stdio.h>
#include<conio.h>
void main()
{
int i,n;
int recfib(int);
void nonrecfib(int);
clrscr();
printf("\n Enter the numbers:");
scanf("%d",&n);
printf("\n The Fibonacci series using recursion is:");
for(i=0;i<n;i++)
printf("%d\t",recfib(i));
printf("\n The Fibonacci series without using recursion is:");
nonrecfib(n);
}
int recfib(int x)
{
if(x==0)
return 0;
else if(x==1)
return 1;
else
return recfib(x-1)+recfib(x-2);
}
void nonrecfib(int c)
{
int a=0,b=1,d,i;
printf("\n%d\t%d",a,b);
55

for(i=3;i<=c;i++)
{
d=a+b;
printf("\t%d",d);
a=b;
b=d;
}
}
OUTPUT:
aiet@ubuntu:~$ gcc fibonacci.c
aiet@ubuntu:~$ ./a.out
Enter the numbers: 8
The Fibonacci series using recursion is: 0
13

The Fibonacci series without using recursion is: 0


8
13

VIVA QUESTION AND ANSWERS

56

1. What is Recursion?
Answer: Recursion function is a function that calls itself directly or indirectly.
2. What is a Function?
Answer: It contains the block of code to perform a specific task i.e. in this case,
adding two numbers and returning it.
3. Define Call by Value?
Answer: Call by value mechanism does not change the contents of the argument
variable in the calling function.
4. Define Call by Reference?
Answer: The address of the argument is copied into a memory location instead of
the values.
5. Write Syntax for DO- WHILE Statement?
Answer: do
{
Statement-block;
}
While (conditional-expression);
6. What is Loop Control Statements?
Answer: for, while, do while

Exercise 6 Functions
1. Write a C Program to make a simple Calculator to Add, Subtract, Multiply
or Divide Using switchcase.
DESCRIPTION:
57

Switch Statement:
We want to check more possible condition for a single variable, a number of statements
are necessary.
Example: To check the category of Employee.
if (category = = 1)
printf (\n principal);
if (category = = 2)
printf (\n professor);
.
.
.
if (category = = 7)
printf (\n non-teaching staff);
Is there any chance to reduce the repeated usage of if statement? Yes, we have the switch
case statement to check multiple conditions at a time, which reduces the number of
repetitions of the statement.
Syntax of the switch statement:
Switch (expression)
{
case value -1: Statement-1;
case value -2: Statement-2;
case value -3: Statement-3;
[default: statement n;]
}

PROGRAM: aiet@ubuntu:~$ gedit calculator.c


#include<stdio.h>
#include<conio.h>
void main()
58

{
int n1, n2, ch;
clrscr();
printf("\n Enter the first number:");
scanf("%d", &n1);
printf("\n Enter the second number:");
scanf("%d", &n2);
printf("\n [1] -> Addition ");
printf("\n [2] -> Subtraction ");
printf("\n [3] -> Multiplication ");
printf("\n [4] -> Division ");
printf("\n\n Enter your choice <1...4>:");
scanf("%d", &ch);
switch(ch)
{
case 1 :
printf("\n %d + %d = %d", n1, n2, n1 + n2) ;
break ;
case 2 :
printf("\n %d - %d = %d", n1, n2, n1 - n2) ;
break ;
case 3 :
printf("\n %d * %d = %d", n1, n2, n1 * n2);
break ;
case 4 :
printf("\n %d / %d = %.2f", n1, n2, (float)n1 / n2);
break ;
default :
printf("\n Invalid choice");
break ;
}
getch();
59

}
OUTPUT:
aiet@ubuntu:~$ gcc calculator.c
aiet@ubuntu:~$ ./a.out
Enter the first number: 3
Enter the second number: 6
[1] Addition
[2] Subtraction
[3] Multiplication
[4] Division
Enter your choice <14> : 1
3+6 = 9

2. (a).Write a C program to convert Decimal to Binary using switch call


function
DESCRIPTION:
Binary number system: It is base 2 number system which uses the digits from 0 and 1.
Decimal number system: It is base 10 number system which uses the digits from 0 to 9.
60

Decimal to binary conversion with Example:


For example we want to convert decimal number 25 in the binary.
Step 1: 25 / 2 Remainder: 1, Quotient: 12
Step 2: 12 / 2 Remainder: 0, Quotient: 6
Step 3: 6 / 2 Remainder: 0, Quotient: 3
Step 4: 3 / 2 Remainder: 1, Quotient: 1
Step 5: 1 / 2 Remainder: 1, Quotient: 0
So equivalent binary number is: 11001
That is (25)10 = (11001)2
ALGORITHM:
Step: 1 [Defining a function]
void dec_bin(long int num)
Step: 2 [Declaring variables]
long int rem[50], i=0, length=0
Step: 3 [Decision making loop]
while(num>0) then follow the steps
otherwise go to Step 6
Step: 4 [Calculate the values rem/num]
rem[i]=num%2
num=num/2
Step: 5 [Increment i, length]
i++
length++
Step: 6 [print about binary number]
printBinary number is:
61

Step: 7 [Repitition using loop]


for i=length-1 to 0
Step: 8 [print the number]
print rem[i]
Step: 9 [main function and declaration of variables]
main
long int num
Step: 10 [Read decimal number]
read num
Step: 11 [function call]
dec_bin(num)
Step: 12 [End of program]
Stop

FLOWCHART:

62

PROGRAM: aiet@ubuntu:~$ gedit binary.c


63

#include<stdio.h>
#include<conio.h>
#include<math.h>
void dec_bin(long int num) // Function Definition
{
long int rem[50],i=0,length=0;
while(num>0)
{
rem[i]=num%2;
num=num/2;
i++;
length++;
}
printf("\n Binary number:");
for(i=length-1;i>=0;i--)
printf("%ld",rem[i]);
}
//=============================
void main()
{
long int num;
clrscr();
printf("\n Enter the decimal number:");
scanf("%ld",&num);
dec_bin(num); // Calling function
getch();
}

OUTPUT:
aiet@ubuntu:~$ gcc binary.c
64

aiet@ubuntu:~$ ./a.out
Enter the decimal number: 7
Binary number: 111

2. (b) Write a C program to convert Decimal to Hexadecimal using switch call


function.
DESCRIPTION:

65

Hexadecimal Number System: It is base 16 number system which uses the digits from 0
to 9 and A, B, C, D, E, F.
Decimal Number System: It is base 10 number system which uses the digits from 0 to 9
Decimal to Hexadecimal conversion Example:
For example we want to convert decimal number 900 in the hexadecimal.
Step 1: 900 / 16 Remainder: 4, Quotient: 56
Step 2: 56 / 16 Remainder: 8, Quotient: 3
Step 3:

3 / 16 Remainder: 3, Quotient: 0

So equivalent hexadecimal number is: 384


That is (900)10 = (384)16
ALGORITHM:
Step: 1 [Defining a function]
void dec_hex(long int num)
Step: 2 [Declaring variables]
long int rem[50], i=0, length=0
Step: 3 [Decision making loop]
while(num>0) then follow the steps
otherwise go to Step 6
Step: 4 [Calculate the values rem[i],num]
rem[i]=num%16
num=num/16
Step: 5 [Increment I and length]
i++
length++
Step: 6 [print about hexadecimal number]
print hexadecimal number is:
Step: 7 [Repetition using loop]
for i=length-1 ;i>=0;i++)
66

Step: 8 [multiway decision making]


Switch (rem[i])
Step: 9 [case statements]
Case1:- print(A) break;
Case2:- print(B) break;
Case3:- print(C) break;
Case4:- print(D) break;
Case5:- print(E) break;
Case6:- print(F) break;
Step: 10 [Default]
print rem[i]
Step: 11 [Declaring main function and variables]
Main
long int num
Step: 12 [Read decimal number]
read num
Step: 13 [calling function]
dec_hex(num)
Step: 14 [End of program]
Stop

FLOWCHART:

67

PROGRAM: aiet@ubuntu:~$ gedit hexadecimal.c


68

#include<stdio.h>
#include<conio.h>
#include<math.h>
void dec_hex(long int num) // Function Definition
{
long int rem[50],i=0,length=0;
while(num>0)
{
rem[i]=num%16;
num=num/16;
i++;
length++;
}
printf("\n Hexadecimal number:");
for(i=length-1;i>=0;i--)
{
switch(rem[i])
{
case 1:
printf("A");
break;
case 2:
printf("B");
break;
case 3:
printf("C");
break;
case 4:
printf("D");
break;
69

case 5:
printf("E");
break;
case 6:
printf("F");
break;
default :
printf("%ld",rem[i]);
}
}
}
//========================
void main()
{
long int num;
clrscr();
printf("\n Enter the decimal number:");
scanf("%ld",&num);
dec_hex(num); // Calling function
getch();
}
OUTPUT:
aiet@ubuntu:~$ gcc hexadecimal.c
aiet@ubuntu:~$ ./a.out
Enter the decimal number: 7894
Hexadecimal number: A1413F
VIVA QUESTION AND ANSWERS
1. Write the Syntax for Switch Case Statement?
70

Answer: switch (expression)


{
case label1: statements;
break;
case label2: statements;
break;
default:
statements;
break;
}
2. Write the Syntax for IF- ELSE Statement?
Answer: if (condition)
{
Statement1; Statement2;
}
else
{
Statement3; Statement4;
}
3. Differentiate Built-In Functions and UserDefined Functions
Answer: Built-In Functions: printf(), scanf(), main(), gets(), puts()
UserDefined Functions: user defined functions are the function which are
created by user as per his own requirements.
4. Which of the following is the Symbol for Preprocessor.
(a) < >
(b) $
(c ) *
(d) #

[ d ]

5. Write the Different Library Functions?


Answer: <stdio.h>, <math.h>, <string.h>, <stdlib.h>, <signal.h>
6. What are the String Handling Functions in a C?
Answer: strcat(), strsmp(), strcpy(), strlen()

Exercise 7 Functions
1. Write a C program to compute the values of sin x and cos x and e^x values
using series expansion (use factorial function).
PROGRAM: aiet@ubuntu:~$ gedit series.c
71

#include<stdio.h>
#include<math.h>
#define PI 3.1415
float exp_x( int, int );
double sin_x( int, int );
double cos_x( int, int );
int fact( int );
int main()
{
int choice, x, n;
do
{
printf( "\n Menu\n[1] e^x)\n[2] Sin(x)\n[3] Cos(x)\n[4] Exit\n" );
scanf( "%d", &choice );
switch ( choice )
{
case 1: // to find exponential value
printf( "e^x\nEnter x and n:\t" );
scanf( "%d %d", &x, &n );
printf( "e^%d(%d) = %f\n", x, n, exp_x( x, n ) );
break;
case 2: // to find sinx
printf( "sin(x)\nEnter x and n:\t" );
scanf( "%d %d", &x, &n );
printf( "\n sin(%d)(%d) = %f\n", x, n, sin_x( x, n ) );
break;
case 3: // to find cosx
printf( "cos(x)\nEnter x and n:\t" );
scanf( "%d %d", &x, &n );
printf( "\n cos(%d)(%d) = %f\n", x, n, cos_x( x, n ) );
72

break;
case 4: // exit
break;
default: // wrong choice
printf( "Wrong choice" );
break;
}
}
while ( choice != 4 );
}
float exp_x( int x, int n )
{
int i = 1;
float ex = 1;
while ( i < n )
{
ex += ( float ) pow( x, i ) / fact( i );
++i;
}
return ex;
}
double sin_x( int ang_deg, int no_of_terms )
{
int term, j;
double value = 0.0, ang_rad = 0.0;
ang_rad = ( double ) ang_deg * PI / 180;
for ( term = 1, j = 2;term < no_of_terms*2;term += 2, j++ )
{
value += ( double ) pow( -1.0, j ) * pow( ang_rad, term ) / fact( term );
}
return value;
73

}
double cos_x( int ang_deg, int no_of_terms )
{
int term, j;
double value = 1.0, ang_rad = 0.0;
ang_rad = ( double ) ang_deg * PI / 180;
for ( term = 2, j = 1;term <= no_of_terms;term += 2, j++ )
{
value += ( double ) pow( -1.0, j ) * pow( ang_rad, term ) / fact( term );
}
return value;
}
int fact( int num )
{
int f = 0;
if ( num == 1 )
return 1;
else
f = num * fact( num - 1 );
return f;
}

OUTPUT:
aiet@ubuntu:~$ gcc series.c
aiet@ubuntu:~$ ./a.out
Menu
[1] e^x)
[2] Sin(x)
[3] Cos(x)
74

[4] Exit
1
e^x
Enter x and n: 2 3
e^2(3) = 5.000000
Menu
[1] e^x)
[2] Sin(x)
[3] Cos(x)
[4] Exit
2
Sin(x)
Enter x and n: 90
2
Sin(90)(2) = 0.924843
Menu
[1] e^x)
[2] Sin(x)
[3] Cos(x)
[4] Exit
3
Cos(x)
Enter x and n: 90
1
Cos(90)(1) = 1.000000
Menu
[1] e^x)
[2] Sin(x)
[3] Cos(x)
[4] Exit
4

VIVA QUESTION AND ANSWERS


a) What is the Function Syntax?
Answer: return_type function_name(parameter list)
{
/* declaration */
return (expression);
}

75

b) What is the Local Variable?


Answer: Local variables are declared with in a function

c) What is the Global Variable?


Answer: Global variables in c have their declaration outside the function

d) What is a compiler?
Answer: A compiler is system software which converts programming language
code into binary format in single steps.

e) What is meant by Dynamic Memory Allocation?


Answer: It is a process of allocating or de-allocating the memory at run time it is
called as dynamically memory allocation.

Exercise 8 Arrays
Demonstration of arrays:
C Array is a collection of variables belongings to the same data type. You can store group
of data of same data type in an array.

Array might be belonging to any of the data types


Array size must be a constant value.
76

Always, Contiguous (adjacent) memory locations are used to store array elements
in memory.
It is a best practice to initialize an array to zero or null while declaring, if we dont
assign any values to array.

EXAMPLE FOR C ARRAYS:

int a[10];
// integer array
char b[10]; // character array i.e. string
Here 10 means size of the array.

TYPES OF C ARRAYS:
There are 2 types of C arrays. They are,
1. One dimensional array
2. Multi dimensional array

Two dimensional array


Three dimensional array
Four dimensional array etc

1. ONE DIMENSIONAL ARRAY IN C:


Syntax : data-type arr_name[array_size];

Array declaration, initialization and


accessing
Array declaration syntax:
data_type arr_name [arr_size];
Array initialization syntax:
data_type arr_name [arr_size]=(value1,
value2, value3,.);
Array accessing syntax:
arr_name[index];

77

Example
Integer array example:
int age [5];
int age[5]={0, 1, 2, 3, 4};
age[0]; /*0 is accessed*/
age[1]; /*1 is accessed*/
age[2]; /*2 is accessed*/

EXAMPLE PROGRAM FOR ONE DIMENSIONAL ARRAY IN C:


#include<stdio.h>
int main()
{
int i;
int arr[5] = {10,20,30,40,50};
// declaring and Initializing array in C
//To initialize all array elements to 0, use int arr[5]={0};
/* Above array can be initialized as below also
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50; */
for (i=0;i<5;i++)
{
// Accessing each variable
printf("value of arr[%d] is %d \n", i, arr[i]);
}
}
OUTPUT:
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50

2. TWO DIMENSIONAL ARRAY IN C:

Two dimensional array is nothing but array of array.

Syntax : data_type array_name[num_of_rows][num_of_column];


Array declaration, initialization and accessing

Array declaration syntax:


data_type arr_name [num_of_rows][num_of_column];
Array initialization syntax:
78

Example
Integer array example:
int arr[2][2];

data_type arr_name[2][2] = {{0,0},{0,1},{1,0},{1,1}};


Array accessing syntax:
arr_name[index];

int arr[2][2] = {1,2, 3, 4};


arr [0] [0] = 1;
arr [0] ]1] = 2;
arr [1][0] = 3;
arr [1] [1] = 4;

EXAMPLE PROGRAM FOR TWO DIMENSIONAL ARRAY IN C:


#include<stdio.h>
int main()
{
int i,j;
// declaring and Initializing array
int arr[2][2] = {10,20,30,40};
/* Above array can be initialized as below also
arr[0][0] = 10; // Initializing array
arr[0][1] = 20;
arr[1][0] = 30;
arr[1][1] = 40; */
for (i=0;i<2;i++)
{
for (j=0;j<2;j++)
{
// Accessing variables
printf("value of arr[%d] [%d] : %d\n",i,j,arr[i][j]);
}
}
}
OUTPUT:
value of arr[0] [0] is 10
value of arr[0] [1] is 20
79

value of arr[1] [0] is 30


value of arr[1] [1] is 40

INTRODUCTION TO SORTING:
Sorting is nothing but storage of data in sorted order, it can be in ascending or descending
order. The term Sorting comes into picture with the term Searching. There are so many
things in our real life that we need to search, like a particular record in database, roll
numbers in merit list, a particular telephone number, any particular page in a book etc.
Sorting arranges data in a sequence which makes searching easier. Every record which is
going to be sorted will contain one key. Based on the key the record will be sorted. For
example, suppose we have a record of students, every such record will have the following
data:
80

Roll No.

Name

Age

Class

Here Student roll no. can be taken as key for sorting the records in ascending or
descending order. Now suppose we have to search a Student with roll no. 15, we don't
need to search the complete record we will simply search between the Students with roll
no. 10 to 20.
Sorting Efficiency:
There are many techniques for sorting. Implementation of particular sorting technique
depends upon situation. Sorting techniques mainly depends on two parameters. First
parameter is the execution time of program, which means time taken for execution of
program. Second is the space, which means space taken by the program.

Types of Sorting Techniques:


There are many types of Sorting techniques, differentiated by their efficiency and space
requirements. Following are some sorting techniques which we will be covering in next
sections.
1. Bubble Sort
2. Insertion Sort
3. Selection Sort
81

4. Quick Sort
5. Merge Sort
6. Heap Sort

a) Write a C program to implement LINEAR SEARCH using arrays.


DESCRIPTION:
LINEAR SEARCH:
A linear search is the basic and simple search algorithm. A linear search searches an
element or value from an array till the desired element or value is not found and it
searches in a sequence order. It compares the element with all the other elements given in
the list and if the element is matched it returns the value index else it return -1. Linear
Search is applied on the unsorted or unordered list when there are fewer elements in a
list.
82

Example with Implementation:


To search the element 5 it will go step by step in a sequence order.

PROGRAM: aiet@ubuntu:~$ gedit linear.c


#include<stdio.h>
int main()
{
int a[30], ele, num, i;
printf("\n Enter no.of elements:");
scanf("%d", &num);
printf("\n Enter the values:");
for (i = 0; i < num; i++)
{
scanf("%d", &a[i]);
}
83

//Read the element to be searched


printf("\n Enter the elements to be searched:");
scanf("%d", &ele);
//Search starts from the zeroth location
i = 0;
while (i < num && ele != a[i])
{
i++;
}
//If i < num then Match found
if (i < num)
{
printf("Number found at the location = %d", i + 1);
}
else
{
printf("Number not found");
}
}

return (0);

OUTPUT :
aiet@ubuntu:~$ gcc linear.c
aiet@ubuntu:~$ ./a.out
Enter no.of elements: 5
Enter the values: 9
5
3
4
7
Enter the elements to be searched: 4
Number found at the location = 4

84

b) Write a C program to implement BUBBLE SORT using arrays


DESCRIPTION:
BUBBLE SORTING:
Bubble Sort is an algorithm which is used to sort N elements that are given in a memory
for eg: an Array with N number of elements. Bubble Sort compares all the element one
by one and sort them based on their values.
It is called Bubble sort, because with each iteration the smaller element in the list bubbles
up towards the first place, just like a water bubble rises up to the water surface.
Sorting takes place by stepping through all the data items one-by-one in pairs and
comparing adjacent data items and swapping each pair that is out of order.

85

PROGRAM: aiet@ubuntu:~$ gedit bubble.c


#include<stdio.h>
#include<conio.h>
void bubble_sort(int[], int);
void main()
{
int arr[30], num, i;
printf("\n Enter no of elements:");
scanf("%d", &num);
printf("\n Enter array elements:");
for (i = 0; i < num; i++)
scanf("%d", &arr[i]);
86

bubble_sort(arr, num);
getch();
}
void bubble_sort(int iarr[], int num)
{
int i, j, k, temp;
printf("\n Unsorted Data:");
for (k = 0; k < num; k++)
{
printf("%5d", iarr[k]);
}
for (i = 1; i < num; i++)
{
for (j = 0; j < num - 1; j++)
{
if (iarr[j] > iarr[j + 1])
{
temp = iarr[j];
iarr[j] = iarr[j + 1];
iarr[j + 1] = temp;
}
}
printf("\nAfter pass %d : ", i);
for (k = 0; k < num; k++)
{
printf("%5d", iarr[k]);
}
}
}
OUTPUT:
aiet@ubuntu:~$ gcc bubble.c
aiet@ubuntu:~$ ./a.out
Enter no of elements: 5
Enter array elements: 10

55

21

Unsorted Data:

10

55

21

After pass 1:

10

21

55

87

After pass 2:

10

21

55

After pass 3:

10

21

55

After pass 4:

10

21

55

Write a C program to implement SELECTION SORT using arrays


DESCRIPTION:
SELECTION SORTING:
Selection sort is conceptually the most simplest sorting algorithm. This algorithm first
finds the smallest element in the array and exchanges it with the element in the first
position, then find the second smallest element and exchange it with the element in the
second position, and continues in this way until the entire array is sorted.
How Selection Sorting Works:

88

In the first pass, the smallest element found is 1, so it is placed at the first position, then
leaving first element, smallest element is searched from the rest of the elements, 3 is the
smallest, so it is then placed at the second position. Then we leave 1 nad 3, from the rest
of the elements, we search for the smallest and put it at third position and keep doing this,
until array is sorted.

PROGRAM: aiet@ubuntu:~$ gedit selection.c


#include <stdio.h>
//Selection Sort function to Sort Integer array list
int *selectionSort(int array[],int n)
{
int j,temp,i;
//Iterate start from first element
for (i = 0; i < n; i++)
{
//Iterate and compare till it satisfies condition
89

for(j = i+1; j < n; j++)


{
if(array[i] > array[j])
{//Swaping operation
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
//return Sorted array
return array;
}
int main()
{
//declaring variables
int array[1000],n,i;
//Number of elements in array form user input
printf("\n Enter the number of element you want to Sort:");
scanf("%d",&n);
//code to ask to enter elements from user equal to n
printf("\n Enter Elements in the list:");
for(i = 0; i < n; i++)
90

{
scanf("%d",&array[i]);
}
//calling selectionSort function defined above and gettting
//sorted array in sortArray variable
int *sortArray = selectionSort(array,n);
//print sorted array
printf("Sorted list:");
for(i = 0; i < n; i++ )
{
printf("%d\t",sortArray[i]);
}
}

OUTPUT:
aiet@ubuntu:~$ gcc selection.c
aiet@ubuntu:~$ ./a.out
How many elements you want to sort: 6
Enter the values one by one:
Enter element 1: 6
Enter element 2: 8
Enter element 3: 9
Enter element 4: 1
Enter element 5: 5
Array before sorting:
91

[4] [6] [8] [9] [1] [5]


Array after sorting:
[1] [4] [5] [6] [8] [9]

c) Write a C program to implement OPERATIONS ON MATRIX using arrays


PROGRAM: aiet@ubuntu:~$ gedit matric.c
#include<stdio.h>
int main()
{
int i, j, mat1[10][10], mat2[10][10], mat3[10][10];
int row1, col1, row2, col2;
printf("\n Enter the number of Rows of Mat1:");
scanf("%d", &row1);
printf("\n Enter the number of Columns of Mat1:");
scanf("%d", &col1);
printf("\n Enter the number of Rows of Mat2:");
92

scanf("%d", &row2);
printf("\n Enter the number of Columns of Mat2:");
scanf("%d", &col2);
/* Before accepting the Elements Check if no of
rows and columns of both matrices is equal */
if (row1 != row2 || col1 != col2)
{
printf("\n Order of two matrices is not same");
exit(0);
}
//Accept the Elements in Matrix 1
for (i = 0; i < row1; i++)
{
for (j = 0; j < col1; j++)
{
printf("Enter the Element a[%d][%d] : ", i, j);
scanf("%d", &mat1[i][j]);
}
}
//Accept the Elements in Matrix 2
for (i = 0; i < row2; i++)
for (j = 0; j < col2; j++)
{
printf("Enter the Element b[%d][%d] : ", i, j);
scanf("%d", &mat2[i][j]);
}
//Addition of two matrices
93

for (i = 0; i < row1; i++)


for (j = 0; j < col1; j++)
{
mat3[i][j] = mat1[i][j] + mat2[i][j];
}
//Print out the Resultant Matrix
printf("\n The Addition of two Matrices is: \n");
for (i = 0; i < row1; i++)
{
for (j = 0; j < col1; j++)
{
printf("%d\t", mat3[i][j]);
}
printf("\n");
}
return (0);
}
OUTPUT:
aiet@ubuntu:~$ gcc matrix.c
aiet@ubuntu:~$ ./a.out
Enter the number of Rows of Mat1: 3
Enter the number of Columns of Mat1: 3
Enter the number of Rows of Mat2: 3
Enter the number of Columns of Mat2: 3
Enter the element a[0][0]: 1
Enter the element a[0][1]: 4
Enter the element a[0][2]: 3
94

Enter the element a[1][0]: 2


Enter the element a[1][1]: 5
Enter the element a[1][2]: 4
Enter the element a[2][0]: 3
Enter the element a[2][1]: 6
Enter the element a[2][2]: 1
Enter the element b[0][0]: 6
Enter the element b[0][1]: 4
Enter the element b[0][2]: 6
Enter the element b[1][0]: 7
Enter the element b[1][1]: 5
Enter the element b[1][2]: 5
Enter the element b[2][0]: 8
Enter the element b[2][1]: 2
Enter the element b[2][2]: 7
The Addition of two Matrices is:
7

10

11

95

VIVA QUESTION AND ANSWERS


1. The function sqrt() is part of header file
(a). math.h

(b). iostream.h

(c). stdio.h

[a]
(d). conio.h

2. # include is a directive
(a). compiler (b). processor

[d]
(c). Pre-compiler (d). Pre-processor

3. What is meant by Array?


Answer: It is a collection of logically related data items of same type.

4. What is the Syntax of One Dimensional Array?


Answer: Data-type array-name[size];
96

Ex:- int a[10];

5. What is the Syntax of Two Dimensional Array?


Answer: Data-type array-name[ rowsize] [colsize];
Ex:- int a[10] [10];

6. What is the Syntax of Three Dimensional Array?


Answer: Data-type array-name[size1] [size2] [size3];
Ex:- int a[2] [3] [4];

Exercise 9 Structures
1. Write a C Program to Store Information of a Movie Using Structure
PROGRAM: aiet@ubuntu:~$ gedit movie.c
#include<stdio.h>
#include<conio.h>
struct movie
{
char title[100];
int year;
char directorname[100];
char actor[500];
};
void main()
97

{
struct movie movie;
clrscr();
printf("\n Enter title:");
gets(movie.title);
printf("\n Enter year:");
scanf("%d",&movie.year);
printf("\n Enter directorname:");
scanf("%s",&movie.directorname);
printf("\n Enter actor:");
scanf("%s",&movie.actor);
printf(\n\n\n);
printf("Name of the movie: %s \n",movie.title);
printf("year of the movie: %d \n",movie.year);
printf("directorname of the movie: %s \n",movie.directorname);
printf("actor of the movie: %s \n",movie.actor);
getch();
}

OUTPUT:
aiet@ubuntu:~$ gcc movie.c
aiet@ubuntu:~$ ./a.out
Enter title: A Aa
Enter year: 2016
Enter director name: trivikram
Enter actor: Samantha
Name of the movie: A Aa
Year of the movie: 2016
Directorname of the movie: trivikram
Actor of the movie: samantha
98

2. Write a C Program to Store Information Using Structures with Dynamically


Memory Allocation.
PROGRAM: aiet@ubuntu:~$ gedit memory.c
#include <stdio.h>
#include<stdlib.h>
struct course
{
int marks;
char subject[30];
};
int main()
{
struct course *ptr;
int i, noofRecords;
printf("Enter number of records: ");
scanf("%d", &noofRecords);
// Allocates the memory for noofRecords structures with pointer ptr pointing to the base
address.
ptr = (struct course*) malloc (noofRecords * sizeof(struct course));
99

for(i = 0; i < noofRecords; ++i)


{
printf("Enter name of the subject and marks respectively:\n");
scanf("%s %d", &(ptr+i)->subject, &(ptr+i)->marks);
}
printf("Displaying Information:\n");
for(i = 0; i < noofRecords ; ++i)
printf("%s\t%d\n", (ptr+i)->subject, (ptr+i)->marks);
return 0;
}

OUTPUT:
aiet@ubuntu:~$ gcc memory.c
aiet@ubuntu:~$ ./a.out
Enter number of records: 2
Enter name of the subject and marks respectively:
Programming
22
Enter name of the subject and marks respectively:
Structure
33

Displaying Information:
Programming
Structure

22
33

100

3. Write a C Program to Add Two Complex Numbers by Passing Structure to a


Function.
PROGRAM: aiet@ubuntu:~$ gedit complex.c
#include <stdio.h>
typedef struct complex
{
float real;
float imag;
} complex;
complex add(complex n1,complex n2);
int main()
{
complex n1, n2, temp;
printf("For 1st complex number \n");
printf("Enter real and imaginary part respectively:\n");
scanf("%f %f", &n1.real, &n1.imag);
printf("\n For 2nd complex number \n");
printf("Enter real and imaginary part respectively:\n");
scanf("%f %f", &n2.real, &n2.imag);
temp = add(n1, n2);
101

printf("Sum = %.1f + %.1f", temp.real, temp.imag);


return 0;
}
complex add(complex n1, complex n2)
{
complex temp;
temp.real = n1.real + n2.real;
temp.imag = n1.imag + n2.imag;
return(temp);
}
OUTPUT:
aiet@ubuntu:~$ gcc complex.c
aiet@ubuntu:~$ ./a.out
For 1st complex number
Enter real and imaginary part respectively:
2.3
4.5
For 2nd complex number
Enter real and imaginary part respectively:
3.4
5
Sum = 5.7 + 9.5

102

VIVA QUESTION AND ANSWERS


1. Define Structure?
Answer: Structure can be defined to be a group of logically related data items.

2. What is the syntax of Structure?


Answer: Struct structurename
{
Datatype member-1
.
.
Datatype member-n
};
3. Define Union?
Answer: It also store different data types in the same memory location.

4. Which of the following operator is used to open the contents of all structure
elements of different data type to another structure variable of its type [ c ]
(a). ->

(b). &

(c). =

(d). *

5. What is Run time error?


Answer: Errors detected at the time of program execution are called run time
103

error.

Exercise 10 Arrays and Pointers


1. Write a C Program to Access Elements of an Array Using Pointer.
PROGRAM: aiet@ubuntu:~$ gedit elements.c
#include <stdio.h>
int main()
{
int data[5], i;
printf("\n Enter elements:");
for(i = 0; i < 5; ++i)
scanf("%d", data + i);
printf("You entered: \n");
for(i = 0; i < 5; ++i)
printf("%d\n", *(data + i));
return 0;
}
OUTPUT:
aiet@ubuntu:~$ gcc elements.c
aiet@ubuntu:~$ ./a.out
Enter elements: 1
2
104

3
5
4
You entered:
1
2
3
5

2. Write a C Program to find the sum of numbers with arrays and pointers.
PROGRAM: aiet@ubuntu:~$ gedit pointer.c
#include<stdio.h>
#include<conio.h>
void main()
{
int numArray[10];
int i, sum=0;
int *ptr;
printf("\n Enter 10 elements:");
for(i=0;i<10;i++)
scanf("%d",&numArray[i]);
ptr=numArray;
for(i=0;i<10;i++)
{
sum=sum+*ptr;
ptr++;
}
printf("\n The sum of array elements:%d",sum);
}
OUTPUT:
105

aiet@ubuntu:~$ gcc pointer.c


aiet@ubuntu:~$ ./a.out
Enter 10 elements: 11 12

13

14

15

16

17

18

19

20

The sum of array element is: 155

Exercise 11 Dynamic Memory Allocations


1. Write a C program to find sum of n elements entered by user. To perform
this program, allocate memory dynamically using malloc () function.
PROGRAM: aiet@ubuntu:~$ gedit dynamic.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("\n Enter number of elements:");
scanf("%d", &num);
ptr = (int*) malloc(num * sizeof(int)); //memory allocated using malloc
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array:");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
106

OUTPUT:
aiet@ubuntu:~$ gcc dynamic.c
aiet@ubuntu:~$ ./a.out
Enter number of elements:5
Enter elements of array:3
7
9
2
4
Sum= 25

107

2. Write a C program to find sum of n elements entered by user. To perform


this program, allocate memory dynamically using calloc () function.
Understand the difference between the above two programs.
PROGRAM: aiet@ubuntu:~$ gedit allocate.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("\n Enter number of elements:");
scanf("%d", &num);
ptr = (int*) calloc(num, sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("\n Enter elements of array:");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}

108

OUTPUT:
aiet@ubuntu:~$ gcc allocate.c
aiet@ubuntu:~$ ./a.out

Enter number of elements:5


Enter elements of array:3
6
7
9
2
Sum=27

109

VIVA QUESTION AND ANSWERS


1. What is meant by pointer?
Answer: A variable which can store the address of another variable is called a
pointer.

2. What is symbol of pointer


(a). [ ]

(b). *

(c). #

[b]
(d). &

3. Define String?
Answer: A string is a collection of characters that are enclosed within double
quotes ( ).
4. Malloc( ) allocates bytes of memory.

5. Calloc( ) allocates block of memory

6. What is meant by getchar() and putchar()?


Answer: getchar(): is used to read a character from the terminal.
Putchar(): it is used to display a character on the monitor.
Putchar() can be used repeatedly to display a line of characters.

110

Exercise 12 Strings
1. Implementation of string manipulation operations with library function.
i. Copy
ii. Concatenate
iii.
Length
iv. Compare
PROGRAM: aiet@ubuntu:~$ gedit with.c
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char str[20],str1[20];
int ch,i,j;
clrscr();
do
{
printf("\n****MENU****");
printf("\n1:Find Length");
printf("\n2:Copy the Strings");
printf("\n3:Compare the Strings");
printf("\n4:Concatenate the Strings");
printf("\n5:Exit");
printf("\n Enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\n Enter the string: ");
scanf("%s",&str);
i=strlen(str);
printf("\n The Length of given string is: %d",i);
break;
case 2:
111

printf("\n Enter the first string: ");


scanf("%s",&str);
printf("\n Enter the second string: ");
scanf("%s",&str1);
strcpy(str,str1);
printf("\n The Copied string is: %s",str);
break;
case 3:
printf("\n Enter the first string: ");
scanf("%s",&str);
printf("\n Enter the second string: ");
scanf("%s",&str1);
j=strcmp(str,str1);
if(j==0)
{
printf("\n The string is same");
}
else
{
printf("\n The string is not same");
}
break;
case 4:
printf("\n Enter the first string: ");
scanf("%s",&str);
printf("\n Enter the second string: ");
scanf("%s",&str1);
strcat(str,str1);
printf("\n The Concatenated string is: %s",str);
break;
case 5:
exit(0);
break;
}
}
while(ch!=5);
getch();
}

112

OUTPUT:
aiet@ubuntu:~$ gcc with.c
aiet@ubuntu:~$ ./a.out

****MENU****
1:Find Length
2:Copy the Strings
3:Compare the Strings
4:Concatenate the Strings
5:Exit
Enter your choice: 1
Enter the string: VINIT
The Length of given string is: 5
****MENU****
1:Find Length
2:Copy the Strings
3:Compare the Strings
4:Concatenate the Strings
5:Exit
Enter your choice: 2
Enter the first string: VINIT
Enter the second string: JAIN
The Copied string is: JAIN
****MENU****
1:Find Length
2:Copy the Strings
3:Compare the Strings
4:Concatenate the Strings
5:Exit
Enter your choice: 3
Enter the first string: VINIT
113

Enter the second string: VINIT


The string is same
****MENU****
1:Find Length
2:Copy the Strings
3:Compare the Strings
4:Concatenate the Strings
5:Exit
Enter your choice: 4
Enter the first string: VINIT
Enter the second string: JAIN
The Concatenated string is: VINIT JAIN
****MENU****
1:Find Length
2:Copy the Strings
3:Compare the Strings
4:Concatenate the Strings
5:Exit
Enter your choice: 5

114

2. Implementation of string manipulation operations without library function.


i. Copy
ii. Concatenate
iii.
Length
iv. Compare
PROGRAM: aiet@ubuntu:~$ gedit without.c
#include<stdio.h>
#include<stdlib.h>
int find_length(char string[])
{
int len = 0,i;
for(i = 0; string[i]!='\0'; i++)
{
len++;
}
return len;
}
void join_strings(char string1[], char string2[])
{
int i, len1, len2;
len1 = find_length(string1);
len2 = find_length(string2);
for(i = len1; i < len1+len2; i++)
{
string1[i] = string2[i-len1];
}
string1[i] = '\0'; //adding null character at the end of input
}
/*returns 0 if thery are same otherwise returns 1*/
int compare_strings(char string1[], char string2[])
{
int len1, len2, i, count = 0;
len1 = find_length(string1);
len2 = find_length(string2);
115

if(len1!=len2)
return 1;
for(i = 0; i < len1; i++)
{
if(string1[i] == string2[i])
count++;
}
if(count == len1)
return 0;
return 1;
}
void copy_string(char destination[], char source[])
{
int len,i;
len = find_length(source);
for(i = 0; i < len; i++)
{
destination[i] = source[i];
}
destination[i] = '\0';
}
int main()
{
char string1[20], string2[20]; //string variables declaration with size 20
int choice;
while(1)
{
printf("\n1. Find Length \n2. Concatenate \n3. Compare \n4. Copy \n5. Exit\n");
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter the string: ");
scanf("%s",string1);
printf("The length of string is %d", find_length(string1));
break;
116

case 2:
printf("Enter two strings: ");
scanf("%s%s",string1,string2);
join_strings(string1,string2);
printf("The concatenated string is %s", string1);
break;
case 3:
printf("Enter two strings: ");
scanf("%s%s",string1,string2);
if(compare_strings(string1,string2)==0)
{
printf("They are equal");
}
else
{
printf("They are not equal");
}
break;
case 4:
printf("Enter a string: ");
scanf("%s",string1);
printf("String1 = %s\n");
printf("After copying string1 to string 2\n");
copy_string(string2,string1);
printf("String2 = %s",string2);
break;
case 5:
exit(0);
}
}
return 0;
}

117

OUTPUT:
aiet@ubuntu:~$ gcc without.c
aiet@ubuntu:~$ ./a.out
1. Find Length
2. Concatenate
3. Compare
4. Copy
5. Exit
Enter your choice: 1
Enter the string: siddhu
The length of string is 6
1. Find Length
2. Concatenate
3. Compare
4. Copy
5. Exit
Enter your choice: 2
Enter two strings: venkata bhavani
The concatenated string is venkatabhavani
1. Find Length
2. Concatenate
3. Compare
4. Copy
5. Exit
Enter your choice: 3
Enter two strings: venkata prasad
They are not equal
1. Find Length
2. Concatenate
3. Compare
4. Copy
5. Exit
Enter your choice: 3
Enter two strings: venkata venkata
They are equal
1. Find Length
2. Concatenate
3. Compare
4. Copy
118

5. Exit
Enter your choice: 4
Enter a string: prasad
String1 = prasad
After copying string1 to string 2
String2 = Prasad
1. Find Length
2. Concatenate
3. Compare
4. Copy
5. Exit
Enter your choice:5

VIVA QUESTION AND ANSWERS


119

1. What is Compile time error?


Answer: If any error is generated at the time of compilation is known as compile
time error.
Ex:- Missing semicolon, writing keyword in upper case, writing variable
declaration, initialization after calling clrscr() function.

2. What are the dynamic memory allocation I/O functions?


Answer: <alloc.h>, <malloc.h>, <mem.h> ,<stdlib.h>

3. A string is an array of
(a). integers

[c]

(b). floating point number

(c). characters

4. What is the control string for representing string


(a). %d

(b). %s

(c). %c

(b). strrsa( )

[c]

(c). strrev( )

(d). strcmp( )

6. The strcat( ) function is used for


(a). multiplication

[b]

(d). %f

5. The function is used to reverse a string


(a). strcat( )

(d). Boolean values

[b]

(b). Concatenation

(c). Joining

(d). Addition

Exercise -13 Files


1. Write a C programming code to open a file and to print it contents on screen.
120

PROGRAM: aiet@ubuntu:~$ gedit open.c


#include <stdio.h>
#include <conio.h>
void main()
{
FILE *fp;
char s;
clrscr();
fp=fopen("text.txt","r");
if(fp==NULL)
{
printf("\n CAN NOT OPEN FILE");
getch();
exit();
}
do
{
s=getc(fp);
printf("%c",s);
}
while(s!=EOF);
fclose(fp);
getch();
}
OUTPUT:
aiet@ubuntu:~$ gcc open.c
aiet@ubuntu:~$ ./a.out
CAN NOT OPEN FILE
2. Write a C program to copy files.
PROGRAM: aiet@ubuntu:~$ gedit copy.c
#include<stdio.h>
121

#include<conio.h>
#include<stdlib.h>
void main()
{
FILE *fp1, *fp2;
char ch;
clrscr();
fp1 = fopen("Sample.txt", "r");
fp2 = fopen("Output1.txt", "w");
while (1)
{
ch = fgetc(fp1);
if (ch == EOF)
break;
else
putc(ch, fp2);
}
printf("File copied Successfully!");
fclose(fp1);
fclose(fp2);
}
OUTPUT:
aiet@ubuntu:~$ gcc copy.c
aiet@ubuntu:~$ ./a.out
File copied successfully.

Exercise - 14 Files
1. Write a C program merges two files and stores their contents in another file.
PROGRAM: aiet@ubuntu:~$ gedit merge.c
122

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
main()
{
FILE *fs1, *fs2, *ft;
char ch, file1[20], file2[20], file3[20];
printf("\n Enter name of first file: ");
gets(file1);
printf("\n Enter name of second file: ");
gets(file2);
printf("\n Enter name of file which will store contents of two files: ");
gets(file3);
fs1 = fopen(file1,"r");
fs2 = fopen(file2,"r");
if( fs1 == NULL || fs2 == NULL )
{
perror("Error ");
printf("Press any key to exit...\n");
getch();
exit(EXIT_FAILURE);
}
ft = fopen(file3,"w");
if( ft == NULL )
{
perror("Error ");
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
while( ( ch = fgetc(fs1) ) != EOF )
fputc(ch,ft);
123

while( ( ch = fgetc(fs2) ) != EOF )


fputc(ch,ft);
printf("Two files were merged into %s file successfully.\n",file3);
fclose(fs1);
fclose(fs2);
fclose(ft);
getch();
return 0;
}

OUTPUT:
aiet@ubuntu:~$ gcc merge.c
aiet@ubuntu:~$ ./a.out
Enter name of first file: 222.c
Enter name of second file: copy1.c
Enter name of file which will store contents of two files: output.txt
Two files were merged into output.txt file successfully.

2. Write a C program to delete a file.


PROGRAM: aiet@ubuntu:~$ gedit delete.c
#include<stdio.h>
main()
{
124

int status;
char file_name[25];
printf("Enter the name of file you wish to delete\n");
gets(file_name);
status = remove(file_name);
if( status == 0 )
printf("%s file deleted successfully.\n",file_name);
else
{
printf("Unable to delete the file\n");
perror("Error");
}
return 0;
}
OUTPUT:
aiet@ubuntu:~$ gcc delete.c
aiet@ubuntu:~$ ./a.out
Enter the name of file you wish to delete:
111.c
111.c file deleted successfully.

VIVA QUESTION AND ANSWERS


1. What is a File?
Answer: A file is a collection of records. Each record provides an information to
the user.

2. What is the File I/O functions?


125

Answer: fputc(), fgetc(), fprintf(), fscanf(), fcolse()

3. Which of the following function is used for storing information in a disk file [ d ]
(a). scanf( )

(b). fscanf( )

(c). printf( )

(d). fprintf( )

4. The C library that contains the prototype statement for the file operation is
(a). proto.h

(b). file.h

(c). stdio.h

[b]

(d). stdlib.h

5. EOF means: End of File


6. What is meant by Calloc() function?
Answer: Calloc() allocates multiple blocks of memory, all of which are of same
size and return a pointer.

Exercise 15
1) System Assembling, Disassembling and identification of Parts / Peripherals.
Steps for Assembling:

Fix the SMPS on the cabinet of PC using the screws provided.

Fix the motherboard on the cabinet of PC using the screws provided.

Connect the power cables from SMPS to motherboard.


126

Insert the preprocessor into the slot provided such that the corner with no pin
coincide with corner without pinhole on motherboard.

Apply the appropriate adhesive on the processor for fixing the processor fan.

Fix the processor fan on the processor and use clips on it to keep it firm.

Connect the power cable to the processor fan

Insert the RAM card into the slots provided on the motherboard.

Set the jumpers setting on the hard disc drive.

Fix the hard disc drive in the space provided in the PC cabinet using screws
provided.

Fix the FDD in the space provided in the PC cabinet using screws provided.

Fix the CD-ROM in the space provided in the PC cabinet using screws provided.

Connect the FDD,HDD, CD-ROM drive to motherboard using flat ribbon.

Connect power supply to the HDD, FDD, CD-ROM drive using the cables from
the SMPS.

Connect wires of speakers and lights of cabinet to the motherboard.

Connect the network interface and other cards to motherboard by inserting in right
slots and fix them in cabinet using the screws provided.

Place the cabinet in right position.

Fix the doors of the cabinet.

Connect the data cable of monitor to the CPU.

Connect the keyboard cable to the CPU.

Connect the mouse cable to the CPU.

Connect other devices to CPU.

Connect the LAN cable to NIC in CPU.

Connect the power supply to CPU.

Connect the power supply to Monitor.

Switch on the computer after giving the power supply.

127

Getting the Cabinet ready:


1. Check how to open the cabinet and determine where to fix the components.
2. Determine if the case has the appropriate risers installed.
Preparing to fit the Components:
1. Network adapter drive.
2. Floppy disk drive.
3. Ribbon cables.
4. Hard disk.
5. CD-ROM Drive.
6. RAM
7. CPU
8. Heat sink / cooler / fan.
9. Mother board.
10. Screws.
Fitting the Mother board:
1. Line up the patch on the motherboard ( ps/l, USB, etc ) with the appropriate holes
in the block panel I/O shield of the case.
2. Check the points where you and to install
3. Install them and make the mother board sit on them and fix screws if required.

Mother board parts:


1. PCI Slot.
2. AGP Slot.
3. ATX Connectors.
4. CPU Fan.
5. Chipset North Bridge.
128

6.

CPU socket.

7. Floppy.
8. System memory.
9. Chipset south bridge.
10. Panel connector.
11. Power supply.
12. IDE connectors.
ATX Connectors:
1. PS, Mouse.
2. Key board.
3. USB.
4. Parallel ( Prints )
5. Serial COM1.
6. Serial COM 2.
7. Joystick.
8. Sound.
Fitting the processor:
1. Raise the small lever at the side of the socket.
2. Notice that there is a pin missing at one corner, determine the direction to fit in
the processor.
3. You should not force the CPU. When inserting it. All pins should slide smoothly
into the socket.

Lock the lever back down.

Install the heat sink over it (Different type for each processor). Heat sink /
CPU fan.

Fitting the RAM:


1. The RAM must be suitable for motherboard.
2. There are currently 3 types of RAM available.
129

SD RAM.

DDR SD RAM.

RD RAM.

3. The mother boards chipset determines which type of RAM may be used.
Installing the PCI Cards:
1. Most of the cards are inbuilt these days.
2. NIL, Sound Cards etc. are fitted into PCI slots.
Fitting the hard disk and Floppy disk:
1. Place the floppy and hard disks in their slots.
2. Leave some space above HDD to prevent heat building.
3. Check the jumper configuration.
4. Fix the screws.
Installing the CD-ROM Drives:
1. CD-ROM drive is similar to installing a hard disk.
2. 1st check that the jumper configuration is correct.
3. Fix the screw.
Connecting the ribbon Cables:
1. Attach the long end of the cable to the IDEU connector on the motherboard first.
2. The red stripe on the IDE cable should be facing the CD Power.

Powering the driver and motherboard:


Connecting the cables for the case front pane
1. SD, SPK or SPEAK: The loud speakers o/p. it has 4 pins.
2. RS, RE, RS or RESET: Connect the two pin Reset cable here.
130

3. PWR, PW, PWSW, PS or power SW: Power switch, the pcs on (switch, the
plug is two pin ).
4. PWLED, PWRLED or Power LED: The light emitting diode on the front
panel of the case illuminates when the computer is switched on. Its a 2-pin
cable.
5. HD, HDD, and LED: These two pins connect to the cable for the hard disk
activity LED.
Final Check:
1. Mother board jumper configurations are the settings for the processor operator.
2. Drive jumper settings, master/ slave correct?
3. Are the processor, RAM modules and plug in cards finally seated in there
sockets?
4. Did you plug all the cables in? Do they all fit really?
5. Have you frightened all the screws in plug- in cards or fitted the clips?
6. Are the drive secure?
7. Have u connected the power cables to all driver?

Powering up for the first time:


1. Ensure that no wires are touching the CPU heat sink fan.
2. Plug your monitor, mouse and keyboard.
3. Plug in power card and switch the power supply.
4. If everything is connected as it should be

All system, fans should start spinning.

U should hear a single beep and after about 5-10 sec.

Amber light on monitor should go green.

You will see computer start to boot with a memory check.

Now check front LEDS to see if u plugged them in correctly.


131

Check all other buttons.

Power afford change any wrong settings.

Steps for Dissembling:

Switch of the power supply

Disconnect the power supply cable from monitor.

Disconnect the power supply cable from CPU.

Disconnect the LAN cable to NIC in CPU.

Disconnect the other devices in CPU such as printers.

Disconnect the mouse cable from CPU.

Disconnect the keyboard cable from CPU.

Disconnect data cable of monitor from CPU.

Remove the doors of cabinet.

Place the cabinet such that motherboard faces the ceiling.

Disconnect the NIC and other cards from mother board by removing from slots
and unscrewing from cabinet.

Disconnect the wires of speakers from mother board.

Remove power supply cables from HDD, FDD, CD-ROM drive etc.

Disconnect the HDD, FDD, CD-ROM drive from mother board by removing flat
ribbon cable.

Remove CR-ROM from cabinet.

Remove the FDD from cabinet by unscrewing it.

Remove the HDD from cabinet by unscrewing it.

Removing RAM cards from slots on mother board.

Disconnect the power cables from processor fan.

Remove the processor fan by unlocking clips on it.

Disconnect the power cables from SMPS on power cabinet.


132

Remove mother board from cabinet by unscrewing it.

Remove the SMPS from cabinet of PC by unscrewing it.

VIVA QUESTION AND ANSWERS


1) Define a Computer?
Answer: Computer is a fastest electronic device. It used to input data, output data,
processing of information and store the result.
133

2) Define Hardware and Software?


Answer: Hardware:- the collection of physical parts of a computer system.
Software:- Software is a set of instructions and applications used to
manage various function.
3) What are the functional units of a computer?
Answer: Input unit, output unit, storage unit, control unit, arithmetic logic unit.

4) COMPUTER stands for: common operation machine particular used for trade
education research.

5) What are the Classification of Computers?


Answer: Main frame computer, mini frame computer, micro frame computer,
super computer.

Identification of Parts / Peripherals.


Major Components of a Computer:
1. Case
2. Motherboard
134

3. CPU
4. Memory (RAM), (ROM)
5. Power supply
6. Hard drive
7. CD or DVD drive
8. I/O Slots
9. Network Ports
10. Floppy drive
11. Monitor
12. Keyboard
13. Mouse
PC Overview
Personal Computer (PC) - A small, single-user computer based on a microprocessor as it's
central "brain". In addition to the microprocessor,

a personal computer has a keyboard for entering data,

a monitor for displaying information,

a mouse for selecting items that show up on the monitor, and a storage device for
saving data.

BLOCK DIAGRAM OF COMPUTER:

135

INPUT UNIT:
The process of sending the data and instructions for the processing through some suitable
devices such as Keyboard, Mouse, Scanner, Barcode reader and Digital Camera etc. is
called input. The devices translate the data from human understandable from into
electronic impulses which are understood by the computer.

CENTRAL PROCESSING UNIT (CPU):


Once the data accepted it fed in to central Processing Unit before the output is generated
as data has to be processed, which is done by CPU. This unit of the computer is the brain
of computer system, which does all the processing, calculations, problem solving and
controls all other functions of all other elements of the computer. The CPU consists of the
following three (3) distinct units namely.
1. Memory Unit
2. Control Unit
3. Arithmetic and Logic Unit

1. Memory Unit:
136

This holds the data in terms of program and files. The data stored can be accessed
and used whenever required by the CPU for necessary processing. This memory
unit is usually refereed as primary storage section. The units in which memory
unit is measured are known as BYTES.
BYTE is the space required to store 8 characters or alphabet or digits to any other
special character.
2. Control Unit:
This unit which coordinates all the activities of each and every element of
computer. It decodes the instructions given by various users and it seeds
commands and signals that determine the sequence of various instructions.
Through this unit does not process data but it acts as the central system for data
manipulation, as it controls the flow of data to and from the main storage.
3. Arithmetic and Logic Unit:
This unit performs arithmetic operations such as addition, subtraction,
multiplication and division. It also does Logical Operations such as comparison of
numbers etc. Thus this unit helps by processing data and taking logical decisions.
OUTPUT UNIT:
The processing of extracting the data from CPU through some suitable devices is
called Output. The common used output devices are Speakers, Monitors, Printers,
and Projectors etc.

CPU BACK PANELS:

137

1. What is CASE or CABIET

Contain the framework to support and enclose internal components of the


computer.
Typically made of plastic, steel, and aluminum.
Available in a variety of styles.
The size and layout of a case is called a form factor.
Designed to keep internal components cool.
Helps to prevent damage from static electricity.

138

2. What is a Motherboard

A motherboard is a printed circuit board that is the foundation of a computer and


allows the CPU, RAM, and all other computer hardware components to function
with each other. It is also known as a main board, baseboard, system
board, and logic board.
A typical motherboard provides attachment points for one or more of the
following:
a) CPU
b) Graphics card
139

c) Sound card
d) Hard disk controller
e) Memory (RAM)
f) External peripheral devices.

Some motherboards support AMD CPUs, while others support Intel processors.
Within the manufacturer's categories.

There are different grades of CPUs. An AMD 64-bit processor requires a different
CPU socket than an AMD 32-bit processor.

A motherboard also comes in one of a few standard footprints or sizes.

Today most motherboards are color-coded with controllers built-in, making it very
easy to build a computer from scratch.

Most motherboard today was designed for IBM compatible computers which hold
over 96% of the computers in the market today.

3. What is CPU

CPU The central processing unit.


CPU is also known as the brain of the computer.
Also referred to as the processor.
Two major CPU architectures related to instruction sets:
a) Reduced Instruction Set Computer (RISC)
b) Complex Instruction Set Computer (CISC)
The processor is fitted on to a Mother Board.
The Mother Board contains various components, which support the
functioning of a PC.

4. What is Memory

It is internal storage area in the computer.


140

The term memory identifies data storage that comes in the form of chips,
and the word storage is used for memory that exists on tapes or disks.

The term memory is usually used as shorthand for physical memory, which
refers to the actual chips capable of holding data.

Some computers also use virtual memory, which expands physical memory
onto a hard disk.

There are two types of memorys


a) Primary Memory
b) Secondary Memory
MEMORY

PRIMARY MEMORY

RAM

SECONDARY MEMORY

ROM

HARD DISK
DRIVE

FLOPPY
DRIVE

CD/DVD
DRIVE

a) PRIMARY MEMORY:
i.

RAM (RANDOM ACCESS MAMORY):

This is the same as main memory. When used by itself, the term
RAM refers to read and write memory.
You can both write data into RAM and read data from RAM.
This is in contrast to ROM which permits you only to read data.
Most RAM is tempary (volatile) storage device.
As soon as the power is turned off, whatever data was in RAM is
lost.
There are three types of RAMs
a) SD-RAM (synchronous dynamic random access memory)
b) RD-RAM (rambus dynamic random access memory)
c) DDR (double data rate (or) dual data rate random access
memory)

141

ii.

ROM (READ ONLY MEMORY):


Computers almost always contain a small amount of read-only
memory that holds instructions for starting up the computer.
Most ROM is permentant (non-volatile) storage device.
There are three types of ROMs
a) PROM (programmable read only memory)
b) EPROM (erasable programmable read only memory)
c) EEPROM (electrically erasable programmable read only
memory)

Differences between ROM & RAM


RAM:

RAM stands for Random Access Memory.


This is the main store and is the place where the programs and software we load
gets stored.
When the Central Processing Unit runs a program, it fetches the program
instructions from the RAM and carries them out.
If the Central Processing Unit needs to store the results of calculations it can store
them in RAM.
Random Access Memory can have instruction READ from it by the CPU and also
it can have numbers or other computer, data WRITTEN to it by the CPU.
The more RAM in your computer, the larger the programs you can run.
When we switch a computer off, whatever is stored in the RAM gets erased.

ROM:
ROM stands for Read Only Memory.
The CPU can only fetch or read instructions
from Read Only Memory (or) ROM.
142

ROM comes with instructions permanently stored inside and these instructions
cannot be over-written by the computers CPU.
ROM memory is used for storing special sets of instructions which the computer
needs when it starts up.
When we switch the computer off, the contents of the ROM does not become
erased but remains stored permanently.
Therefore it is non-volatile.
The following is a diagram showing the relationship between the Central
Processing Unit and Main Memory (RAM and ROM).
b) SECONDARY MEMORY:
i.

HARD DISK DRIVE: (HDD)

A hard drive (hard disk or hard disk drive) is used to store


operating system, software and data disk size is currently measured
in gigabytes for workstations or terabytes for servers drives tend to
spin at 7,200 RPM for workstations and 10,000 RPM for servers,
through older computers will have 5,400 RPM.
Large amount of data is stored in the computer is called hard disk
drive.
The four main components of a hard disk drive are the platters,
head arm, chassis and the head actuator.

There are three types of hard disk drives


a) IDE (Integrated device electronic)
b) SATA (Serial advanced technology attachment)
c) SCSI (Small computer system interface)
(a). IDE (Integrated Device Electronic):
It as a 39 pins.
We can insert 4 IDE Hard disk in computer depends
upon the capacity.
Speed of this hard disk 7,200Rpm
Speed of data reading 33 Mb\sec
143

Hard disk cable Red wire and power supply cable


Red should be co inside.

(b). SATA (Serial Advanced Technology Attachment):

It as 6 or 8 pins.
We can insert 4 SATA hard disk in computer
depends upon the capacity.
Speed of this hard disk 8,300 Rpm.
Speed of data reading 53Mb/sec.
Hard disk cable Red wire and power supply cable
Red should be co inside.

(c). SCSI (Small Computer System Interface):

It has 25,50, 68 Pins.


Speed of this hard disk 15,000 Rpm
A SCSI port can transmit data at rates in excess of
320 Mbps and can support up to 15 devices.
Three different types of SCSI ports:
I. DB-25 female connector
II. High-density 50-pin female connector
III. High-density 68-pin female connector

144

ii. Floppy Disk Drive: (FDD)


A floppy disk drive (FDD) is storage device that uses removable
3.5 inch floppy disks that can store 1.44 MB of data.
It as a 32 pins.

iii. CD/DVD drives:

CD means compact disc.


DVD means Digital video disc.
CD-ROM (Compact Disc-Read-Only Memory) is an optical disk
use for storing large amount of data, the most common is 650
Megabytes.
CD-ROMs are popularly used to distribute computer software,
including games and multimedia applications, though any data can
be stored (up to the capacity limit of a disc).
DVD-ROM is an optical disc storage that is capable to store atleast
47.7gigabytes.
145

DVD-ROM has data which can only be read but cannot be written
over. It has the same size and form with CD-ROM

CD

DVD

5. What is Power Supply (or) SMPS


SMPS means switch mode power supply.
The power supply converts alternating-current (AC) power coming from a
wall outlet into direct-current (DC) power, which is a lower voltage.
It is two types of Power supply.
a) AT (Advanced Technology):
We have to switch off the system manually by pressing power switch
after OS shut down.
b) ATX (Advanced Extended Technology):
In ATX power supply the system automatically goes to power off
position after OS shut down.
DC power is required for all of the components inside the computer.
Cables, connectors, and components are designed to fit together snugly. Never
force any connector or component.

Voltage:
Red

: +5 volts

Yellow

: +12 volts

Blue

: -12 volts

White

: -5 volts

Black

: 0 volts
146

Orange

: +5volts (feed back)

6. What is I/O SLOTS


I/O slots mean input and output slots.
It is used to extra cards.
Increase the functionality of a computer by adding controllers for specific
devices or by replacing malfunctioning ports.
Examples of adapter cards:
a) Sound adapter and video adapter
b) USB, parallel, and serial ports
c) RAID adapter and SCSI adapter
d) Network Interface Card (NIC), wireless NIC, and modem adapter

There are three types of I/O slots.


1) Industry Standard Architecture (ISA)
2) Peripheral Component Interconnect (PCI)
3) Advanced Graphics Port (AGP)
1) Industry Standard Architecture (ISA):
Black color 8 bit, 16 bit
8-bit ISA: 62 connector; 8-bit data lines.
16-bit ISA: 98 pin connector (62+36); this spots 8-bit ISA
and 16-bit ISA card.
2) Peripheral Component Interconnect (PCI):
White color 32 bit, 64bit this is also local bus.
It supports 64-bit data transferring.
3) Advanced Graphics Port (AGP):
Brown color, it supports high speed graphics and is only
meant for graphic application.
It supports 62 bit data transferring.
147

It is specially designed for insert AGP Graphic Card.

7. What is Network Ports

A network port, also known as an RJ-45 port, (Register Jack) connects a


computer to a network.
Standard Ethernet can transmit up to 10 Mbps.
Fast Ethernet can transmit up to 100 Mbps.
Gigabit Ethernet can transmit up to 1000 Mbps.
The maximum length of network cable is 328 feet (100 m).

Cable Connector types:

8. What is Monitor
Connects to the computer via the video card.
The Computer Monitor is the computer user's window into the workings
of the computer.
It consists of a television picture tube that had been modified to accept the
type of video signal created by the computer's electronics.
Conventional televisions can be used as computer monitors if a translation
device is used to connect them.
The picture quality leaves something to be desired.
There are two types of Monitors:
a) Cathode Ray Tube (CRT):
Cathode-ray tube (CRT) monitor is the most common
monitor type.
Most televisions also use this technology.
148

b) Liquid Crystal Display (LCD) :


Liquid crystal display (LCD) is commonly used in laptops
and some projectors.
LCD comes in two forms, active matrix and passive matrix.
c) Digital Light Processing (DLP) or Projector

9. What is Key Board

A Keyboard is a primary input device that is used mainly for inputting


text.
Its key-arrangement was patterned from and electronic and mechanical
type writer.
There are actually three different PC keyboards:
i. The original PC keyboard, with 84 keys.
ii. The AT keyboard, also with 84 keys.
iii.
The enhanced keyboard, with 101 keys.
The three differ somewhat in the placement of function keys, the Control
key, the Return key, and the Shift keys.
In addition to the following keys: Page Up, Page Down, Home, End,
Insert, Pause, Num Lock, Scroll Lock, Break, Caps Lock, and Print
Screen.
There are three types of keyboard.
I. PS/2 (parallel series)
II. USB (universal serial bus)
III. WIRELESS.

149

KEYBOARD

PS/2

USB

10. What is MOUSE


A mouse is a small device that a computer user pushes across a desk
surface in order to point to a place on a display screen and to select one or
more actions to take from that position.

There are three types of keyboard.


o PS/2 (parallel series)
o USB (universal serial bus)
o WIRELESS.

MOUSE

PS/2

I/O PORTS:

150

USB

USB Ports and Cables:

USB is a standard interface for connecting peripheral devices to


a computer.
USB devices are hot-swappable.
USB ports are found on computers, cameras, printers, scanners,
storage devices, and many other electronic devices.
A single USB port in a computer can support up to 127 separate devices
with the use of multiple USB hubs.
Some devices can also be powered through the USB port, eliminating the
need for an external power source.

POST:
151

POST stands for Power on Self Test.


Done by the BIOS.
Determine which components are connected to the computer and if they are
working.
A series of beeps indicates the status of the system.
Typical post codes:

Short beep Normal POST system is ok


2 short beep POST Error error code shown on screen
No beep Power supply or system board problem
Continuous beep - Power supply, system board or keyboard problem
Repeating short beeps - Power supply or system board problem
1 long, 1 short beep - System board problem
1 long, 2 short beep - Display adapter problem
1 long, 3 short beeps Enhanced Graphics Adapter (EGA)
3 long beeps 3270 keyboard card.

ABBREVATIONS
CPU

: Central Processing Unit

ALU

: Arithmetic Logical Unit

AMD

: Advanced micro devise

ZIF

: Zero Insertion Force

I \ O Slots

: Input Output Slots

ISA
SIS

: Industrial Standard Architecture


: Silicon Integrated System
152

PCI

: Peripheral Component Interconnect

AGP

: Accelerated Graphic Port

MCA

: Micro Channel Architecture

EISA

: Electronic Industrial Standard Architecture

VESA

: Video Equipment Stranded Association

RAM

: Random Access Memory

ROM

: Read Only Memory

S-RAM

: Static Ram

D-RAM

: Dynamic Ram

SIMM

: Single in Line Memory Module

DIMM

: Dual In Line Memory Module

SD-RAM

: Synchronizing Dynamic Ram

DDR-RAM

: Double Data Rate Ram

RD-RAM

: Rambus Dynamic Ram

BIOS

: Basic Input & Output System

CMOS

: Complementary Meted Oxide Semiconductor

IDE

: Integrated Device Electro

SCSI

: Small Computer Interface System

MOSFET

: Metal oxide Semiconductor Field Effective Transistor

RPM

: Rotation Per Minute

SMPS

: Switch Mode Power Supply

AT

: Advanced Technology

ATX

: Advanced Extended Technology


153

POST

: Power On Self-Test

VIVA QUESTION AND ANSWERS


1) Define a Hard disk?
Answer: It is large amount data is stored in the computer.
2) RAM & ROM stands for: Random Access memory & Read Only Memory
3) What is meant by SMPS (or) power supply?
Answer: To convert the AC current to DC current.
4) CD/DVD Capacity: 700mb/ 4.7gb
5) LAN means: local area network
154

6) POST stands for: post on self test


7) BIOS stands for: basic input output system
8) CMOS STANDS for: complementary metal oxide semiconductor
9) Latest processor: Intel-7.

10) CRT stands for: cathode ray tube


11) LCD stands for: liquid crystal display
12) LED stands for: light emitted diode
13) Total no.of keys in keyboard: 101 keys.

OPERATING SYSTEM
Definition: It is interface between user and hard ware is called the operating system.
There are three types of operating system.
Single user single Task ----- MS-Dos
Single user Multi Task ----- Windows
Multi user Multi Task

----- WinNT, Unix, Linux

Characteristics of Operating Systems:

Control hardware access:


OS automatically discovers and configures PnP hardware

File and folder management

User interface:
155

Command line interface (CLI)


Graphical user interface (GUI)

Application management:
Open Graphics Library (OpenGL) DirectX

The Types of Operating Systems:

Command Line Interface (CLI): The user types commands at a prompt.

Graphical User Interface (GUI): The user interacts with menus and icons.

Most operating systems include both a GUI and a CLI.

Compare Operating Systems:


DESKTOP OPERATING SYSTEM

NETWORK OPERATING SYSTEM

Supports a single user.

Supports multiple users.

Runs single-user applications.

Runs multi-user applications.

Shares files and folders.

Is robust and redundant.

Shares peripherals.

Provides increased security.

Used on a small network.

Used on a network.

156

2) Operating System Installation-Install Operating Systems like Windows,


Linux along with necessary Device Drivers.
INSTALLATION OF WINDOWS XP:
AIM: To install Windows XP
Windows XP (codename Whistler, also known as Windows NT 5.1) is the latest desktop
version of the Microsoft Windows operating system. It was made publicly available on
October 25, 2001. Two editions of Windows XP are most commonly available: Windows
XP Home Edition which is targeted at home users and Windows XP Professional which
has additional features such as dual-processor support and the ability to join a domain, a
grouping of centrally managed Windows computers. The letters "XP" originate from the
word "Experience".
Manual Install of Windows XP:
1. Disconnect the network cable from your computer.
157

2. Turn on the computer.


3. Insert the Windows XP CD into the drive.
4. When you receive the prompt to Press any key to boot from CD..., press any
key to boot from the Windows CD.
5. Wait while the Windows setup files are loaded.
6. When presented with the following menu, press Enter to begin the Windows
XP setup.

7. After reading the License Agreement, press F8 to accept it and continue the
installation.

8. You will now see a list of the partitions on your hard drives. Use the cursor keys
to select an item not labeled as un-partitioned space.

158

9. Press the D key to delete the selected partition. If you receive the following
prompt, press Enter to continue. Otherwise, proceed to the next step.

10. Press the L key to confirm the deletion.


159

11. Repeat steps 8-10 until all space is labeled as


unpartitioned.
12. Use the cursor keys to select an unpartitioned space.
Press the C key to create a new partition.

160

13. When prompted for the size of the partition, press


Enter to accept the default recommendation.
1

14. Repeat steps 12 and 13 for each un-partitioned space


with a size greater than 8 MB.
15. Upon returning to the partition list, select the item
labeled as C: Partition1 [New (Raw)] and press
Enter.

161

16. At the following prompt, select the option to Format


the drive using the NTFS file system. Press Enter
to continue.
1

17. The setup program will now proceed to format the


drive. This may take a while
depending on the size of the drive.

162

18. Once the format procedure has completed, files


should begin to be automatically copied from the
installation CD.

19. Once all necessary files have been copied, the system
will be automatically restarted. You may now remove
the CD. If you choose to leave the CD in the drive, do
not press any key when prompted to press any key to
boot from CD.
163

20. The Windows setup program will now complete the


installation. The content and appearance of the
remaining screens may differ based on the exact
version and distribution of Windows XP you are
installing.

164

OR

121. The default settings on this screen should be correct

for the U.S. Click Next.

165

122. Enter your name and, optionally, your organization.

Click Next.

123. Enter the Windows XP product key and click Next.

For help finding your product key, see the note at the
beginning of this document.

166

OR

124. Enter a name for the computer. This may be


anything you like. In Windows XP Professional you
will be prompted to enter an administrator password.
Do not leave any of your system passwords blank!
For security purposes, it is recommended you choose
a password that contains mixed case letters, numbers
and symbols, and is not based on a dictionary word.
Here are some examples:
0

o dR9f?a9e, b7$Pruc? ,tExjf$n4 ,2!hATrat


,s@A3ifus
Click Next.

167

225. Set the date, time, and time zone. Click Next.

26. Setup will scan for a network. If you receive the


following prompt, select Typical Settings and click Next.

168

169

27. If you are prompted for workgroup or domain settings, leave the default entries and click Next.

128. Setup will continue and will eventually reboot. If you have left the CD in the drive, do not press
any key when prompted to press any key to boot from CD.
129. After rebooting, you may see a display settings box. If you do, click OK. The screen may flicker
for a moment and ask you whether you can see the image. If you can, click Yes.

130. When you see the welcome screen, click Next.


170

31. If you are asked to setup a network or Internet connection at this time, click on Skip.
32. You will now be prompted to register your copy of Windows. Since we have not connected to
the network yet, select No and click Next. If prompted to activate Windows, choose the appropriate
option to skip this step as well. Windows will prompt you to do this later if it is required.

33. Click Finish on the Thank You screen. The Windows XP operating system itself should now be
installed.
171

34. Desktop for the XP after installation.

VIVA QUESTION AND ANSWERS


1) Define Operating System?
Answer: It is interface between the system and user.
172

2) XP abbreviation?
Answer: Extreme professional
3) How many characters does a product key contain from windows XP?
Answer: characters (total blocks: 5 and each block contains:5 characters).
4) Describe different kinds of Microsoft Operating systems?
Answer: Windows 95, windows 2000, windows XP, windows 7
5) FAT stands for: file allocation table
6) NTFS stands for: new technology file system.

7) Total no.of keys in keyboard: 101 keys.

Exercise 16
1. Network Configuration & Software Installation-Configuring TCP/IP, Proxy, and

firewall settings. Installing application software, system software & tools.


NETWORK:
173

Network is the communication between two or more devices or systems.


or
Networking is the collection of computers communicating by a common transmission
method.
Networking began in 1960s by the U.S.Department of Defence (DOD).
PURPOSE: It is used for sharing resource.
RESOURCE: It consists of files, services and hardware devices.
SHARING: Sharing of files includes data and applications.
HARDWARE RESOURCE REQUIREMENTS:

Modem
Hub
Brides (switches)
Routers
Servers
Printers ,scanners

TYPES OF NETWORKS:
Networks are divided into three primary categories.

Local area networks (LAN)


Metropolitan area networks (MAN)
Wide area networks (WAN)

1. LOCAL AREA NETWORK (LAN):


Local area network is a small geographical area network.
Eg: single office , building or campus.

Currently Lan size is limited to few kilometers.


The most common Lan topologies are bus , ring ,star.
Lans have data rates in the 4 to 16 mbps range.
Todays speed are increasing and can reach 100mbps with giga bit systems
in the development.
174

TOPOLOGY:
It the is similar properties of the object.

Smaller Lans - 2 to 25 computers.


Larger Lans 10,000 computers.

2. METROPOLITAN AREA NETWORK:


It is a large geographical area network.
Eg: Extend over an entire city.

It may be a single network such as a cable television network.


And number of Lans into a large network.
Resource may be shared Lan-to-Lan as well as device-to-device.

3. WIDE AREA NETWORK:


It is an extremely large geographical area network.
Eg: country, continent (or) whole world.

It is a long distance transmission of data.

TYPES OF ADMINISTRATION NETWORKS:


Administration networks are also divided into two categories.

Peer -to-peer network


Client-server-network

CLASSIFICATION OF THE NETWORKS:


INTEL PROCESSOR
DISTANCE
0.1m

PROCESSORS
LOCATED IN SAME

EXAMPLES

Circuit board

Data flow machine

1m

System

Multi computer

10m

Room

100m

Building

1km

Campus

Lans

175

10km

City

Man

100km

Country

Wan

1000km

Continent

Wan

10,000km

Planet

The internet

INTERNET:

The internet is a global digital infrastructure that connects millions of


computer.
It is a global interwork , with cross platform compatibility using the internet
protocol (IP) to communicate between computers.
It uses existing public telephone and communication (including satellites )
networks to relay data between networks using routers.
The fastest growing part of the internet is the world wide web.
Other parts of the internet include services such as telnet and ftp.

WORLD WIDE WEB:

The www is a uniform method of accessing and retrieving information on


the internet.
This information is almost always retrieved using the Hyper text transfer
protocol (HTTP).
HTTP has been in use by the world wide web since 1990.
Today, there are millions of websites on the world wide web.

HYPERTEXT:

Hypertext is text with links to additional information about that text.


Hypertext fits very well into the hierarchical architecture of the world wide
web.

HYPERMEDIA:

Hypermedia is the ability to display pictures , videos and sound.

PROTOCOL:

A protocol is a method by which two computers agree to communicate.

TCP/IP:

TCP/IP is an abbreviation for transmission control protocol / internet protocol.


176

TCP is a lossless protocol , requiring a handshake to insure that data is not


lost during transmission.
Internet protocol (IP) uses addresses which are a series of four octet (byte)
numbers in a dotted decimal notation.
Eg: 199.246.32.101
Each IP address is divided into 4 octets.
An octet is 8 bits.
Each IP address is 32 bits.
Each octet can range from 0 to 255.

IP ADDRESS ARE THREE CLASSES:

Class A
Class B
Class C
Class D

IP ADDRESS FORMAT:

The 32 bit IP address is grouped eight bits at a time , separated by dots , and
represented in the decimal format (known as decimal notation).
Each bit in the octet has a binary weight (128,64,32,16,8,4,2,1).
The minimum value for an octet is 0.
The maximum value for an octet is 255.

32 bits

NETWORK ID

8 bits

172

HOST ID

8 bits

32

8bits

144

8bits

DIFFERNCE BETWEEN THE NETWORK ID AND HOST ID:


177

202

NETWORK ID

HOST ID

Shared (or) common to all computers on


the same physical segment.

Identification a specific device (host)


with in a physical segment.

Unique on the entire network.

Unique on the physical segment.

Eg: Area code

Eg: Phone number

IP ADDRESS CLASSES:

IP
ADDRES
S CLASS

IP addressing supports five different address classes : A ,B,C,D and E.


Classes A,B and C are available for commercial use.
The left-most (high-order) bits indicates the network class.

HIGH
ORDE
R BITS

NO. BITS
NETWORKIN
G / HOST

MAX.
HOSTS

1.0.0.0 to
126.0.0.0

7/24

224-2

ADDRESS
RANGE

FORMAT

PURPOSE

N.H.H.H

Few large
organization

N.N.H.H

Medium-size
organization

1,0

128.1.0.0 to
191.254.0.0

14/16

216-2

N.N.N.H

Relatively
small
organization

1,1,0

192.0.1.0 to
223.255.254.0

21/8

28-2

Multicast
groups

1,1,1,0
178

224.0.0.0 to
239.255.265.25

N/A (not for


commercial use)

N/A

N/A

(RFC-1112)

N/A

Experimenta
l

240.0.0.0 to
254.255.255.25
5

1,1,1,1

N Network

N/A

H Host

Class A supports LACKS of system IP address.


Class B supports THOUSANDS of system IP address.
Class C supports HUNDREDS of system IP address.
127- is a MAC address (or) physical address.
It is a universal address.
MAC- Media access control (32bit).

SUBNET MASK:
Each physical segment has a unique network ID.
Class A

Class B

Network

Host

1 0 Network

Network

Host

Host

Class C
1 1 0 Network

Host

Network

Network

Host

Host

DOMAIN:

A domain is logical grouping of computers on a network.


It may include multiple networks.
It may also just be s subset of a network of computers.
So domains can have sub domains.

TOP LEVEL DOMAIN:


The top level domains (TLD) of the internet are:

Com - for commercial entities.


179

N/A

Edu - for educational institutions.


Gov - for non-military , united states , government institutions.
Mil - for united state military organizations.
Net - for network operations.
Org - for non-profit organizations.

BROWSER:

A browser is a graphical user interface (GUI) appilication program that


retrieues and displays documents from web sites.
A browser has the ability to render text and graphics in the browser window.

DISPLAY:

Hypertext and hypermedia documents.


Text in different fonts , styles ,colors and sizes.
Foreign language character sets conforming to the ISO 8859 standard.
Forms composed of text fields , text widgets , buttons, checkboxes etc..
Graphics in different formats.

STEPS IN COFIGURING THE LOCAL AREA NETWORK (LAN) :

Verify whether LAN CARD (or) ETHERNET CARD is there in the system.
Right click on
my computer
properties
system properties
hardware device manager
network adapter.
If the LAN CARD is not installed , then install the drivers and restart the
system.
On the desktop right click on the icon MY NETWORK PLACES.
Select the internet protocol (TCP/IP) option and click its properties and give
the IP address with subnet mask and press OK.
In order to connect a small office networks , goto network tasks in my
network places , click setup a home (or) small office network.
Click on next for both the windows.
Select the option This computer does not have internet connection and press
next , give the computer and its work group name which should be unique for
all the systems in that LAN.
After the giving the work group name , select the option turn on file and print
sharing and press next , that will show the network settings.
After the completion of the setup press finish.
Select the option views work group computer and we can view the
computers that are in this LAN and ready to share the data. Click on the icon
of any system seen in the work group we can get that system views.
In order to get our system drives view to others we should give sharing
permission.
180

ETHERNET:
It is widely used network technology.

Ethernet was invented at center in the 1970s.


Ethernet cable is limited to 500 meters in length.
Band width : 10mega bit p/s (mbps).

Later version known as fast Ethernet operates at mbps.


The most recent version, gigabit Ethernet operators at 1000mbps (or) 1Gbps.

TYPES OF ETHERNET CABLES:


Ethernet cables are divided into three categories:

Straight- through cable


Crossover cable
Rolled cable

BOOK MARK:

A stored location for quick retrieval at a later date.


Web browsers provide bookmarks that contain the address (URLs) of
favorite sites.
Most electronic references, large text databases and help systems provide
bookmarks that mark a location users want to revisit in the future.

INTERNET BOOKMARK:

To click on the internet explorerFavoritesOrganize Favorites.

181

Bookmarks are pointers- primarily to URLs- built-in to the various Internet web
browsers.

Bookmarks have been incorporated into almost every browser since the Mosaic
browser and are normally stored on the software client.

A folder metaphor may be used for organization. Various shareware utilities and
server-side web utilities have been developed to better manage bookmark,yet none
has gained widespread acceptance.

The most recent development in internet bookmarks was the introduction of live
bookmarks by Mozilla Firefox in 2004.

Utilizing Web feeds, live bookmarks sit in the bookmarks menu or sidebar like
any other, but contain a regularly updated list to recent articles supplied by a news
site or Weblog.

POP-UP BLOCKER:

Pop-up blocker refers to any software or application that disables any pop-up,
pop-over or pop-under advertisement window that you would see while using a
Web browser.

Some pop-up blockers may try to close all pop-up windows, some may remove all
advertising from a publishers Web site, and still others may help you choose which
pop-up window you want to be closed with block list feature.

Steps To install pop blockers:


1. After downloading the pop blocker.exe file double the icon and press the button to continue.

2. Press the Next to Continue.

182

3. To agree the license press Yes to continue.


4. To finish the setup press finish which install the pop up blocker in C:\PROGRAM
FILES.
Firewall:
A firewall is a special software or hardware designed to protect a private computer network
from unauthorized access. A firewall is a set of related programs located at a network
gateway server which protects the resources of the private network from users from other
networks.

PROCEDURE:
183

Installing Symantec antivirus for Windows:

Insert Symantec antivirus CD into your CD drive

Double click on the Symantec-setup.exe

The installer will open

Click next to proceed

License agreement will open . Click I accept the terms of the license
agreement and then click next.

Follow the instruction on the screen to complete the installation.

Get Computer Updates:

Click start> settings>control panel

Click Automatic Updates icon to open Automatic Updates dialog box

Check the box Keep my computer up to date

Choose a setting

Click OK

Block Pop ups:

In the IE open tools>pop-up blocker

Click on Turn on Pop- up blocker

Windows Firewall:

Go to Start>control panel>Network and Internet Connections>windows firewall

In the general tab check the On(recommended) box


If you dont want any exceptions check on Dont allow exceptions box

184

Você também pode gostar