Ge6151 Computer Programming All Five Units
Ge6151 Computer Programming All Five Units
1
Anna University, Chennai Syllabus
GE6151 COMPUTER PROGRAMMING LTPC
3003
UNIT I INTRODUCTION 8
Generation and Classification of Computers- Basic Organization of a
Computer –Number System – Binary – Decimal – Conversion – Problems.
Need for logical analysis and thinking – Algorithm – Pseudo code – Flow
Chart.
UNIT II C PROGRAMMING BASICS 10
Problem formulation – Problem Solving - Introduction to ‘ C’ programming –
fundamentals – structure of a ‘C’ program – compilation and linking processes
– Constants, Variables – Data Types – Expressions using operators in ‘C’ –
Managing Input and Output operations – Decision Making and Branching –
Looping statements – solving simple scientific and statistical problems.
UNIT III ARRAYS AND STRINGS 9
Arrays – Initialization – Declaration – One dimensional and Two dimensional
arrays. String- String operations – String Arrays. Simple programs- sorting-
searching – matrix operations.
UNIT IV FUNCTIONS AND POINTERS 9
Function – definition of function – Declaration of function – Pass by value –
Pass by reference – Recursion – Pointers - Definition – Initialization – Pointers
arithmetic – Pointers and arrays- Example Problems.
UNIT V STRUCTURES AND UNIONS 9
Introduction – need for structure data type – structure definition – Structure
declaration – Structure within a structure - Union - Programs using structures
and Unions – Storage classes, Pre-processor directives.
TOTAL: 45 PERIODS
TEXTBOOKS:
1. Anita Goel and Ajay Mittal, “Computer Fundamentals and Programming
in C”, Dorling Kindersley (India) Pvt. Ltd., Pearson Education in South
Asia, 2011.
2. Pradip Dey, Manas Ghosh, “Fundamentals of Computing and
Programming in C”, First Edition, Oxford University Press, 2009
3. Yashavant P. Kanetkar. “ Let Us C”, BPB Publications, 2011.
REFERENCES:
Byron S Gottfried, “Programming with C”, Schaum’s Outlines, Second
Edition, Tata McGraw-Hill, 2006.
Dromey R.G., “How to Solve it by Computer”, Pearson Education,
Fourth Reprint, 2007.
Kernighan,B.W and Ritchie,D.M, “The C Programming language”,
Second Edition, Pearson Education, 2006.
2
Detailed lesson plan
Wee No of Cummlati
S. No Topics Book No
k No Hrs ve hours
UNIT – I NTRODUCTION
Introduction – Definition of Computer –
1 1 1 T1/ T2/R3
History & Characteristics of Computer
Computer Generations – First, Second,
2 1 2 T1/T2/R3
Third, Fourth and Fifth generation.
Classification of Computers – Micro,
3 1 3 T1/T2/R3
I Mini, Mainframe and Super Computers.
3
Wee No of Cummlati
S. No Topics Book No
k No Hrs ve hours
Functions, Library functions.
Decision Making – Branching – if,
if-else, nested if else – go to - T1/T2/T3/
17 1 17
switch .. case – example R3
programs
Looping – while , for ,do while , T1/T2/T3/
18 1 18
break , continue - R3
Solving simple scientific and
statistical problems –
Temperature conversions, Finding
19 1 19 T2/R3
area of geometrical shapes,
Programs using control
statements
Programs using looping
20 1 20 T2/R3
statements
UNIT III - ARRAYS & STRINGS
Arrays – Initialization – Declaration- 1D T1/T2//T3
21 1 21
Array /R3
2D Array – Initialisation – definition –
T1/T2/T3/
22 Multidimensional Arrays – Matrix – 1 22
R3
Programs.
Strings – String declaration & T1/T2/T3/
23 V 1 23
Initialization, basic sting functions R3
String Library functions –
24 1 24 T1/T2/R3
strcpy(),strlen(),strcmp(),strcat()
String Library functions –
25 tolower(),toupper(),strlwr(),strupr(),strnc 1 25 T1/T2/R3
at()
26 Array of strings 1 26 T1/T2
4
Wee No of Cummlati
S. No Topics Book No
k No Hrs ve hours
Total Hours: 47
5
Unit – I
Introduction
Part – A
6
3. Define pseudo code. Write two characteristics of pseudo code.
Jan 14, Nov / Dec 16, April / May 15
Pseudo code is a short, readable and formally styled English language
used for explaining an algorithm. It is a short hand way of describing a
computer program.
7
6. What are flow charts and list down their advantages?
7. Define flow chart. Why is flow chart required? Nov / Dec 2014
12. Convert the binary number 110 100 111 101 to octal.
May/June 2014
(110100111101)2 = (6475)8
10110111.1101 2
= 1*27+0*26+1*25+1*24+0*23+1*22+1*21+1*20+1*2-1+1*2-2+0*2-3+1*2-4
=183.8125
9
Part – B
Write in detail about the evolution and the various generations of computer. January 14
Discuss various generations of computers. April / May 15,14
Explain in detail about the various generations of computers. June 14
Third Fifth
First Second
Generation Fourth Generation Generation
S.No Features Generation Generation
(1964-Early (early 70's to till date) (present and
(1940-56) (1956-63)
70's) beyond)
Microprocessor,
LSI - 1000's of
SLSI(Super
Hardware Vacuum Tubes Integrated transistors
1 Transistor Large Scale
Technology for circuitry Circuits VLSI - 100's of 100's
Integration)
of transistors , Linking
of computers: Internet
Human
Input - Input - Mouse and behaviour like
Input - Input -
Punched cards Handheld devices. thinking,
Input / Punched Keyboard
2 / Paper tape Output - speaking and
Output cards Output Output -
Output – Monitors/Printers/ reasoning. It
– Printouts Monitors
printouts Plotters uses expert
system
10
Third Fifth
First Second
Generation Fourth Generation Generation
S.No Features Generation Generation
(1964-Early (early 70's to till date) (present and
(1940-56) (1956-63)
70's) beyond)
Primary
memory –
Primary Memory –
Magnetic
Semiconductor
Core
memory with faster
technology
Magnetic RAM. Secondary
3 Memory Secondary
Drums Memory : Hard Disk
memory –
( Smaller, Cheaper
Magnetic
and Bigger in
Disk &
Capacity)
Magnetic
Tapes
Computing Gig seconds,
Microsecond
4 Characteristi Milliseconds Nanoseconds Pico seconds parallel
s
cs processing
Very Large.
Physical
5 More space for Smaller Smaller Smaller Smaller
Appearnce
installation.
6 Software Machine Assembly Operating High level Language, based on
Technology Language. language, system GUI (Graphical User Artificial
Language Difficult to use High Level interfaces Interface) : allows Intelligence
and to program Programming keyboard and users to intearct with which
with 1's & 0's. : COBOL & monitor, High the computer includes
11
Third Fifth
First Second
Generation Fourth Generation Generation
S.No Features Generation Generation
(1964-Early (early 70's to till date) (present and
(1940-56) (1956-63)
70's) beyond)
FORTRAN level Natural
were also Language is language
developed. used for processing,
less difficult profgramming. speech
to program Easier to recognition,
and time program and vision
efficient time efficient recognition
used Commercial Purpose,
used for
Commercial commercially, Computers are used for
7 Application scientific
purpose and by mass availabe for home research
applications
audience users
Generate large
amount of heat Generate
Heat Generate les Negligible amount of
8 with thousands less amount
generation heat heat
of vacuum of heat
tubes
Constant Less frequent
Maintenance, maintenance, Low
9 Maintenance High less maintenance , Minimum maintenance
Maintenance maintenance Minimum cost
cost cost
10 Example ENIAC,EDVAC PDP-8, IBM IBM 370, PDP APPLE II , ALTAIR Robotics
12
Third Fifth
First Second
Generation Fourth Generation Generation
S.No Features Generation Generation
(1964-Early (early 70's to till date) (present and
(1940-56) (1956-63)
70's) beyond)
1401,CDC
& UNIVAC 11 8800,CRAY-I
1604
13
2. Basic computer organization
CPU
CU ALU
The digital computers that are available nowadays vary in their sizes
and types. The computers are broadly classified into four categories based
on the size and type:
a. Micro computers,
b. Mini computers,
c. Super computers and
d. Mainframe computers
Super computers
Mainframe computers
Mini Computers
Slow Cheap Simple Small
Micro Computer
16
Microcomputers are small low cost and single user digital
computer.
They consist of CPU, input unit, output unit, storage unit and the
software.
Although microcomputers are stand alone machines, they can be
connected together to create a network of computers that can serve more
than one user.
Examples : IBM PC and Apple Macintosh
Microcomputers include Desktop, Notebook, Net book, Tablet
computer, Handheld computer and Smart phones
Desktop Computer / Personal Computers (PC) is the most
common type of microcomputer. It is a stand-alone machine that can be
placed on the desk. It consists of three units externally – keyboard, monitor
and system unit containing the CPU, memory, Hard disk drive, etc. It is not
expensive and is suited to the needs of a single user at home, small business
units and organizations.
Notebook computers or Laptops resemble a netbook. They are
portable and have the features of a desktop computer. The advantage of
laptop is that it is small in size, can be carried anywhere, has a battery backup
and hence all the functionality of the desktop. Laptops are costlier than
desktop machines.
Netbook are smaller notebooks optimized for low weight and low
cost, and designed for accessing web based applications.
Tablet Computer has the features of the notebook computer but
it can accept the input from a stylus or pen instead of the keyboard or mouse.
It is a new kind of PC.
Handheld Computer or Personal Digital Assistant (PDA) is a
small computer that can be held on the top of the palm. It is small in size.
Instead of keyboard, PDA uses a pen or stylus for input. PDAs do not have a
disk drive. They have limited memory and are less powerful. PDA can be
connected to the Internet via a wireless connection.
Smart Phones are cellular phones that function both as a phone
and as a small PC. They may use a stylus or a pen or may have a small
keyboard. They can be connected to the Internet wirelessly.
b. Mini computers:
Minicomputers are digit computers, generally used in multi-user
systems.
They have high processing speed and high storage capacity than
microcomputers.
17
Minicomputers can support 4-200 users simultaneously.
The users can access the minicomputer through their PCs or
terminal.
They are used for real time applications in industries, research
centres, etc.
Example PDP 11, IBM (8000 series)
c. Mainframe computers:
Mainframe computers are multi user, multiprogramming and high
performance computers.
They operate at a very high speed, have very high storage
capacity and handle the workloads of many users.
They are large and powerful systems used in centralized
databases.
Users access the mainframe computers via dumb terminal or
intelligent terminal or a PC.
Used in banks and companies.
Example : CDC 6600, IBM ES 9000 series
d. Super computers:
Fastest and most expensive machines which perform trillions of
calculations per second.
The speeds of super computers are measured in FLOPS
(Floating Point Operations per Second).
Super computers are built by interconnecting thousands of
processors that can work in parallel.
It performs highly intensive calculations.
Super computers are used in climate research, molecular
research, nuclear research, military agencies, etc.
Example: IBM Roadrunner, IBM Blue gene and Intel ASCI red.
The terminator symbol represents the start points, end points, and potential
outcomes of a path.
20
Guidelines for preparing flowcharts:
It should be simple.
Standard symbols should be used.
The flow lines should not intersect each others.
In case of complex flowcharts use the connectors symbols.
Only one flow line should enter the process symbol and only one
flow line should come out from a process symbol.
Only one flow line should enter the decision symbol and two or
three flow lines may leave from the decision symbol.
21
4c. Flow chart to find biggest of three numbers
Start
Stop
Yes NO
23
4d. Flowchart to find factorial of a number
Start
READ N
i=1
fact = 1
fact = fact * i
Yes
i=i+1 Is i<=n
No
PRINT fact
Stop
24
4e. Flow chart to find sum of first 100 natural numbers
Draw a flow chart to find sum of first 100 natural numbers. May /
June 14
Start
SUM = 0
N=1
N=N+1
SUM = SUM + N
Yes
IS N<=100
No
PRINT SUM
Stop
25
4f. Flow chart to multiply two matrices
Draw a flow chart to multiply two matrices.
26
4g. Flow chart to generate Fibonacci series
Draw the flow chart to generate Fibonacci series.
27
28
4h.Flow chart to check the given number is positive or negative
29
4i. Flow chart to
solve quadratic equation
30
31
5a. Pseudo code
32
Each set of instructions is written from top to bottom, with only
one entry and one exit.
It should allow easy transition from design to coding in
programming language.
Benefits of Pseudo code
It is easier to develop a program from pseudo code than in flow
chart.
It is easy to translate the pseudo code into a programming
language
Limitations of Pseudo code
Pseudo code is textual representation of an algorithm. It does not
provide graphical representation. Therefore, sometimes, it becomes difficult to
understand the complex logic written in Pseudo code.
When too many nested conditions are used in the Pseudo code,
the level of difficulty to understand the code increases.
Since Pseudo code focus on detailed description, a lot of practice
and concentration is required.
Pseudo code lacks the standards and follows very few rules. Due
to this, some programmers reject the code because they fail to see the logic
behind it.
33
6. Number System
Perform the following:
4872 = 114108
1011.11012 = 1*23+0*22+1*21+1*20+1*2-1+1*2-2+0*2-3+1*2-4
= 11.812510
1011.11012= 11.812510
8 48710
8 6088 -6
8 761 -0
8 95 -1
8 11 -7
8 1 -3
48710= (137106)8
Unit – II
34
C PROGRAMMING BASICS
35
5. List the various input and output statements in C. April / May 15
Input statement:
o scanf(), getchar(),gets(),getch()
Output statement:
o printf(), putchar(),puts()
36
9. What is the importance of keywords in C? April / May 15
Keyword is a reserved word that has a particular meaning in the
programming language. The meaning of a keyword is predefined.
Keyword cannot be used as an identifier name in C language.
Example : while, if, do ....
10. Write a C program to find factorial of a number using iteration.
June 14
#include<stdio.h>
#include<conio.h>
void main()
{
int a,fact,i;
clrscr();
printf("Enter a number: ");
scanf("%d",&a);
fact=1;
i=1;
while(i<=a)
{
fact = fact * i;
i++;
}
printf("Factorial of %d is %d",a,fact);
getch();
}
Output: Enter a number: 3
Factorial of 3 is 6
11. What do you mean by C tokens?
C tokens are the basic buildings blocks in C language which are
constructed together to write a C program. Each and every smallest
individual unit in a C program are known as C tokens. C tokens are of
six types. They are,
1. Keywords (eg: int, while),
2. Identifiers (eg: main, total),
3. Constants (eg: 10, 20),
4. Strings (eg: “total”, “hello”),
5. Special symbols (eg: (), {}),
6. Operators (eg: +, /,-,*)
37
12. Write a C program for the following expression.
a. A=5<=8&&6!=5
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
a =5<=8&&6!=5;
printf("%d",a);
getch();
}
Output:1
b. A=B++ + ++B where b=50
#include<stdio.h>
#include<conio.h>
void main()
{
int b=50, a;
a=b++ + ++b;
printf("A=%d",a);
getch();
}
Output: A=102
13. Write a C program to implement the expression ((m+n)/p-m)*m),
where m=4;n=6;p=8.
#include<stdio.h>
#include<conio.h>
void main()
{
int k,m=4,n=6,p=8;
clrscr();
k=((m+n)/p-m)*m);
printf("%d",k);
getch();
}
Error: statement missing
38
14. What will be the outputs for the following program when the value
of i is 5 and 10.
void main()
{
int i;
scanf(%d”,&i);
if(i=5)
printf(“five”);
}
i=5 five
i=10 five
39
Part – B
Problem formulation:
A computer program is basically a set logical instruction written in
a set computer programming language that tells the computer how it
accomplishes a task.
The process of developing a program starts with identifying the
problem first. Once a problem is well understood and documented a series of
problem solving techniques like algorithm, flowcharts and pseudo codes are
carried out in arriving at the most efficient solution.
Planning the computer program:
o Whenever a user wants to use a computer for solving a
problem, the user has to perform various inter related tasks in a systematic
manner.
o All the activities that have to be performed by a user in
order to solve a problem using a computer is grouped into three phases:
a) Identifying the purpose.
Identifying the parameters and constraints.
Collecting information
b) Developing the program
c) Executing the program
Problem solving:
Problem solving is the process of solving a problem in a
computer system by following a sequence of steps. The major steps that need
to be followed are:
o Preparing hierarchy chart
o Developing algorithm
o Drawing flowchart
o Writing Pseudo code.
40
1. b. Constants
41
1. c. Compilation and execution process in C
43
44
2. Branching statements in C
if (expression)
statement;
45
Output:
Enter the book price of computer programming 360
Purchase book
if..........else statement: The if...... else statement is an extension of the
simple if statement. The general form is:
if (test expression)
{
True-block statement(s)
}
else
{
False-block statement(s)
}
statement-x
If the test expression is true, then the true-block statement(s), immediately
following the if statement are executed; otherwise the false-block statement(s)
are executed. In either case, either true-block or false-block will be executed,
not both.
Program:
#include<stdio.h>
void main()
{
int n;
printf("Enter a number: ");
scanf("%d",&n);
if(n%2==0)
printf("The given number is even");
else
printf("The given number is odd");
getch();
}
Output:
Enter a number: 5
The given number is odd
Nested if ...........else statement: When a series of decisions are involved, the
programmers may have to use more than one if.....else statement in nested
form as follows:
If the condition-1 is false statement-3 will be executed; otherwise it
continues to perform the second test. If the condition-2 is true, the
statement-1 will be evaluated; otherwise the statement-2 will be
evaluated and then the control is transferred to the statement-x.
46
if (test condition1)
{
if (test condition 2)
{statement-1;}
else
{statement-2;}
}
else
{ statement-3;}
Program: statement-x;
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("Enter a number:");
scanf("%d",&n);
if(n>0)
{
if(n%2==0)
printf("The number is positive and even");
else
printf("The number is positive and odd");
}
else
printf("The number is negative");
getch();
}
Output: Enter a number: 6
The number is positive and even
The else if ladder: There is another way of putting ifs together when
multipath decisions are involved. A multipath decision is a chain of ifs in
which the statement associated with each else is an if . It takes the
following general form: This construct is known as the else if ladder. The
conditions are evaluated from the top (of the ladder), downwards. As
soon as a true condition is found, the statement associated with is
executed and the control is transferred to the statement x (skipping the
rest of the ladder).When all the n conditions become false, then the final
else containing the default statement will be executed.
if (condition 1) statement 1 ;
else if (condition 2) statement 2;
else if (condition 3) statement
47 3;
else if (condition n) statement n;
else default statement; statement x;
Program: Consider an example of grading the students in an academic
institution. The grading is done according to the following rules:
Average marks Grade
75-100 Honours 60- 74 First Division 50- 59 Second Division 0- 49 Fail
#include<stdio.h>
#include<conio.h>
void main()
{
int marks;
clrscr();
printf("Enter the mark");
scanf("%d",&marks);
if (marks >=75)
printf("grade = Honours");
else if (marks>=60&&marks<75)
printf("grade = First Division");
else if (marks>=50&&marks<60)
printf("grade = Second Division");
else
printf("grade = Fail");
getch();
}
Output: Enter the mark 61 grade = First Division
Switch statement / Multiway Branching statement: The switch-
case statement is a multi-way decision making statement. Unlike the multiple
decisions statement that can be created using if-else, the switch statement
evaluates the conditional expression and tests it against the numerous
constant values. During execution, the branch corresponding to the value that
the expression matches is taken. The value of the expressions in a switch-
case statement must have to be an ordinal type i.e. integer, char, short, long,
etc. Double and Float are not allowed.
The syntax of switch statement is as follows:
switch( expression )
{case constant-expression1:
statements1; break
case constant-expression2:
statements2; break;
case constant-expression3:
statements3; break;
default : statements4; break;}
48
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int choice,a,b;
clrscr();
printf("1 ADDITION\t2 SUBTRACTION\t3 MULTIPLICATION\t4
DIVISION\n");
printf("Enter your choice:");
scanf("%d",&choice);
printf("Enter the values for a and b:");
scanf("%d%d",&a,&b);
switch(choice)
{
case 1:
printf("%d + %d = %d",a,b,a+b); break;
case 2:
printf("%d - %d = %d",a,b,a-b); break;
case 3:
printf("%d * %d = %d",a,b,a*b); break;
case 4:
printf("%d / %d = %d",a,b,a/b); break;
default:
printf("Wrong choice"); break;
}
getch();
}
Output: 1 ADDITION 2 SUBTRACTION 3
MULTIPLICATION 4 DIVISION
Enter your choice: 1
Enter the values for a and b: 4 5 4+ 5 = 9
3. Looping statements in C
49
Differentiate entry and exit checked looping constructs with
example. May / June
2014
Need for looping statements: A computer is used for performing many
repetitive types of tasks The process of repeatedly performing tasks is known
as looping .The statements in the block may be executed any number of times
from zero to up to the Condition is true. The loop is that in which a task is
repeated until the condition is true or the loop will execute all the statements
until the given condition is not to be false.
Types of looping statements: Depending on the position of the control
statement in the loop, a control structure can be classified into two types;
Entry Controlled: The types of loop where the test condition is
stated before the body of the loop, are known as the entry controlled loop. So
in the case of an entry controlled loop, the condition is tested before the
execution of the loop. If the test condition is true, then the loop gets the
execution, otherwise not.
Exit Controlled: The types of loop where the test condition is
stated at the end of the body of the loop, are know as the exit controlled loops.
So, in the case of the exit controlled loops, the body of the loop gets execution
without testing the given condition for the first time. Then the condition is
tested. If it comes true, then the loop gets another execution and continues till
the result of the test condition is not false.
In The loop generally there are three basic operations are
performed
i) Initialization
ii) Condition check
iii) Increment
Looping Constructs in C:
C provides a number of looping way.
a) for loop
b) while loop
c) do-while loop
a. for loop:
It is an Entry Controlled Loop because it first initializes the loop
variable and then the condition is checked.
If the condition is true then it will execute the statements within
the loop body and then after it increments or decrements the value of the loop
variable.
50
In for loop all the basic operations like initialization, condition
checking and incrementing or decrementing all these are performed in only
one line.
Syntax:
Program
#include <stdio.h>
void main()
{
int i;
for(i=0;i<10;i++)
{
printf("%d\t ",i);
}
}
Output : 0 1 2 3 4 5 6 7 8 9
b. while loop:
while loop is Known as Entry Controlled Loop because in the
while loop first the loop variable is initialized and then the condition is checked
If the condition is true then it will execute the statements within
the loop body and then after it increments or decrements the value of the loop
variable.
Otherwise the loop body will be skipped and the statement next to
loop block will be executed.
51
Syntax:
while ( conditional expression )
{
Single statement
or
Block of statements;
}
Program :
#include <stdio.h>
void main()
{
int i=0;
while(i<10)
{
printf("%d\t",i);
i++;
}
}
Output : 0 1 2 3 4 5 6 7 8 9
c. do ... while loop:
This is also called as exit controlled loop.
It is just like a while loop except that the test condition is checked
at the end of the loop rather than the start. This has the effect that the content
of the loop are always executed at least once.
Syntax:
do
{
Single statement
or
Block of statements;
}while(conditional expression);
Program :
#include <stdio.h>
void main()
{
int i=0;
do
{
printf("%d\t",i);
52
i++;
} while(i<10);
}
Output : 0 1 2 3 4 5 6 7 8 9
Input : In any programming language input means to feed some data
into program. This can be given in the form of file or from command line. C
programming language provides a set of built-in functions to read given input
and feed it to the program as per requirement.
Output : In any programming language output means to display some data on
screen, printer or in any file. C programming language provides a set of built-
in functions to output required data.
There are number of I/O functions in C based on the data types.
The I/O functions are classified into two types:
Formatted I/O functions. Formatted I/O function accepts or
present in a particular format.
printf(): Used to print any combination of data.
Syntax:
printf(“control_string 1, - - , control_string n”,variable1, - - - , variable n);
Control String may be format specifier, escape sequence, string to
be displayed.
Format
Data type
specifier
%d Integer
%f Float
%c Character
%s string
scanf(): reads all types of data values. It is used for runtime assignment
of variables.
Syntax:
scanf(“control_string 1, - - , control_string n”,&variable1, - - - ,variable n);
Program:
#include<stdio.h>
#include<conio.h>
53
void main()
{
int no;
char ch;
char s[20];
Unformatted I/O functions. This function cannot control the format of reading
and writing the data. There are two types of unformatted console Input/Output
functions:-
Character I/O functions: These are the functions that can input/output
of one character at a time. These functions deal with the individual
character value. Some of the character I/O functions are:
o getchar():This is used for reading a character from the keyboard.
Syntax: Character_variable = getchar();
Ex.:- char ch; ch=getchar( );
54
This statement accepts a character and stores it to "ch". In this
function the typed character is echoed to the monitor and waits for carriage
return (Enter) to assign it to variable.
o putchar(): It is used to display a character
Syntax: putchar(character_variable/'character')
Ex: putchar(ch);
o getch():It also accepts a single character. It doesn't display the
character at the time of typing. And also it doesn't require enter to
assign value to variable.
Syntax: Character_variable = getch()
o putch(): It is also used to display a single character on the
screen.
Syntax : putch(variable name);
o getche():It is same as getch( ) but only difference is it it echoes
the character at the time of typing on the monitor.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("Enter a character:");
ch=getchar();
putchar(ch);
getch();
}
Output: Enter a character: a
a
String I/O functions: These are the functions that are used to
input/output of whole string. Following functions are used to input and
output in program:
o gets():reads a whole line of input into a string until a newline or
EOF is encountered. It is critical to ensure that the string is large
enough to hold any expected input lines. When all input is
finished, NULL as defined in stdio.h is returned.
Syntax: gets(str var);
Ex: gets(s);
o puts(): writes a string to the output means it displays the
character on the screen, and ends it with a newline character.
55
Syntax: puts(string);
Ex : puts(hai);
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
char s[20];
clrscr();
puts("Enter a string");
gets(s);
puts("The string is");
puts(s);
getch();
}
Output: Enter a string:
Hai
The string is
Hai
5. Operators available in C
56
Classification of operators
1 Based on no of operands on which an operator operates
2. Based on role of the operator.
2. Assignment operators in C:
o In C programs, values for the variables are assigned using
assignment operators.
Operators Example Explanation
Simple assignment
= sum=10 10 is assigned to variable sum
operator
+= sum+=10 This_is_same_as_sum=sum+10…………
-= sum-=10 This is same as sum = sum-10
*= sum*=10 This is same as sum = sum*10
Compound
/+ sum/=10 This is same as sum = sum/10
assignment operators
%= sum%=10 This is same as sum = sum%10
&= sum&=10 This is same as sum = sum&10
^= sum^=10 This is same as sum = sum^10
Example program for C assignment operators:
# include <stdio.h>
int main()
{
int Total=0,i;
for(i=0;i<10;i++)
{
Total+=i; // This is same as Total = Total+i
}
printf("Total = %d", Total);
}
Output:
Total = 45
3. Relational operators in C: Relational operators are used to find the
relation between two variables. i.e. to compare the values of two
variables in a C program.
58
S.no Operators Example Description
1 > x>y x is greater than y
2 < x<y x is less than y
3 >= x >= y x is greater than or equal to y
4 <= x <= y x is less than or equal to y
5 == x == y x is equal to y
6 != x != y x is not equal to y
Example program for relational operators in C:
#include <stdio.h>
int main()
{
int m=40,n=20;
if (m == n)
{
printf("m and n are equal");
}
else
{
printf("m and n are not equal"); }
}
Output:
m and n are not equal
4. Logical operators in C:
These operators are used to perform logical operations on the given
expressions. There are 3 logical operators in C language.
S.no Operators Name Example Description
logical It returns true when both conditions
1 && (x>5)&&(y<5)
AND are true
logical It returns true when at-least one of
2 || (x>=10)||(y>=10)
OR the condition is true
It reverses the state of the operand
logical “((x>5) && (y<5))”
3 ! !((x>5)&&(y<5))
NOT If “((x>5) && (y<5))” is true, logical
NOT operator makes it false
Example program for logical operators in C:
#include <stdio.h>
int main()
{
int m=40,n=20;
int o=20,p=30;
59
if (m>n && m !=0)
{
printf("&& Operator : Both conditions are true\n");
}
if (o>p || p!=20)
{
printf("|| Operator : Only one condition is true\n");
}
if (!(m>n && m !=0))
{
printf("! Operator : Both conditions are true\n");
}
else
{
printf("! Operator : Both conditions are true. " \"But, status is inverted as
false\n");
}
}
Output:
&& Operator : Both conditions are true
|| Operator : Only one condition is true
! Operator : Both conditions are true. But, status is inverted as false
5. Bit wise operators in C:
These operators are used to perform bit operations. Decimal values are
converted into binary values which are the sequence of bits and bit wise
operators work on these bits.
Bit wise operators in C language are & , |, ~, ^, << and >> .
60
Truth table for bit wise operation
Bit wise operators
X y x|y x&y x^y Operator_symbol Operator_name
0 0 0 0 0 & Bitwise_AND
0 1 1 0 1 | Bitwise OR
1 0 1 0 1 ~ Bitwise_NOT
1 1 1 1 0 ^ XOR
<< Left Shift
>> Right Shift
Consider x=40 and y=80. Binary form of these values is given below.
x = 00101000, y= 01010000
x&y = 00000000 (binary) = 0 (decimal)
x|y = 01111000 (binary) = 120 (decimal)
~x =1111111111111111111111111111111111111111111111111111111111
010111= -41(dec)
x^y = 01111000 (binary) = 120 (decimal)
x << 1 = 01010000 (binary) = 80 (decimal)
x >> 1 = 00010100 (binary) = 20 (decimal)
Example program for bit wise operators in C:
#include <stdio.h>
int main()
{
int m=40,n=80,AND_opr,OR_opr,XOR_opr,NOT_opr ;
AND_opr = (m&n);
OR_opr = (m|n);
NOT_opr = (~m);
XOR_opr = (m^n);
printf("AND_opr value = %d\n",AND_opr );
printf("OR_opr value = %d\n",OR_opr );
printf("NOT_opr value = %d\n",NOT_opr );
printf("XOR_opr value = %d\n",XOR_opr );
printf("left_shift value = %d\n", m << 1);
printf("right_shift value = %d\n", m >> 1);
}
61
Output:
AND_opr value = 0
OR_opr value = 120
NOT_opr value = -41
XOR_opr value = 120
left_shift value = 80
right_shift value = 20
6. Conditional or ternary operators in C: Conditional operators return
one value if condition is true and returns another value is condition is
false. This operator is also called as ternary operator.
Syntax : (Condition? true_value: false_value);
Example : (A > 100 ? 0 : 1); // if A is greater than 100, 0 is returned else
1 is returned.
Example program for conditional/ternary operators in C:
#include <stdio.h>
int main()
{ int x=1, y ;
y = ( x ==1 ? 2 : 0 ) ;
printf("x value is %d\n", x);
printf("y value is %d", y);
}
Output:
x value is 1
y value is 2
7. C – Increment/decrement Operators
63
8. Special Operators in C:
S.no Operators Description
This is used to get the address of the
1 & variable.
Example : &a will give address of a.
This is used as pointer to a variable.
2 * Example : * a where, * is pointer to
the variable a.
This gives the size of the variable.
3 Sizeof () Example : size of (char) will give us
1.
Example program for & and * operators in C:
#include <stdio.h>
int main()
{
int *ptr, q;
q = 50;
/* address of q is assigned to ptr */
ptr = &q;
/* display q's value using ptr variable */
printf("%d", *ptr);
return 0;
}
Output:
50
Example program for sizeof() operator in C:
sizeof() operator is used to find the memory space allocated for each C data
types.
#include <stdio.h>
int main()
{
int a;
char b;
float c;
double d;
printf("Storage size for int data type:%d \n",sizeof(a));
printf("Storage size for char data type:%d \n",sizeof(b));
printf("Storage size for float data type:%d \n",sizeof(c));
printf("Storage size for double data type:%d\n",sizeof(d));
return 0;
64
}
Output:
Storage size for int data type:4
Storage size for char data type:1
Storage size for float data type:4
Storage size for double data type:8
6. a. DATA TYPES IN C
65
The qualifier may be signed or unsigned.
Unsigned chars have values between 0 and 255, signed char have values
from -128 to +127.
Integer Types:
Integers are whole numbers with a range of values supported by a
particular machine.
Integers occupy two bytes of storage. A signed integer uses one bit for
sign and 15 bits for the magnitude of the number
C has three classes of integer storage namely short int, int and long int.
Floating Point Types and Double:
Floating point or real number are stored in 32 bits (4 Bytes) with 6 digits
of precision.
Floating point numbers are defined in C by the keyword float.
A double data type number uses 64 bits giving a precision of 14 digits.
These are known as double precision numbers.
void Types:
The void types has no values. This is usually used to specify the type of
functions. The type of a function is said to be void when it does not return any
value to the calling function. It contains nothing or a NULL value. This data
type is used to specify return values of function. If there is nothing to return
from a function, the return type can be specified as “void”.
Eg:
void main()
{
------------
------------
}
Following tables shows the Size and Range of Data Types on a 16-bit
Machine:
Type Size (bits/bytes) Range
Char 8/1 -128 to 127
Int 16 / 2 -32,768 to +32,767
float 32 / 4 3.4E - 38 to 3.4E + 38
double 64 / 8 1.7E-308 to 1.7E+308
DERIVED DATA TYPES
a. Arrays
b. Pointer
c. Function
66
a. Arrays: Arrays can be defined as the collection of similar type of data. It
can also be called as subscripted variables. Each value in the array can
be retrieved using the subscript.
Example: int mark[100];
here the variable mark is defined as an array and it can hold 100 values
of type integer. Each value can be accessed as Mark[0], Mark[1], …….
Mark[99]
b. Pointer: A pointer is a variable whose value is the address of another
variable, i.e., direct address of the memory location.
The general form of a pointer variable declaration is: type *var-name;
type is the pointer's base type; it must be a valid C data type and var-
name is the name of the pointer variable.
c. Function: A function is a group of statements that together perform a
task. Every C program has at least one function, which is main(),
A function declaration tells the compiler about a function's name, return
type, and parameters. A function definition provides the actual body of
the function.
The general form of a function definition in C programming language is
as follows:
return type function_name(parameter list)
{
Body of the function
}
USER DEFINED DATA TYPE
User defined data type are those which are derive from the basic data types.
Some of the user defined data types are
a. Structures
b. Unions
c. Enumeration
Structures
Structures are nothing but a collection of data items. Unlike in arrays, it can
hold set of data items of different data types under a single name. This data
type can be created using the keyword struct
Eg:
struct student
{
int rno;
char name[25];
float avg;};
struct student s1, s2;
67
student is an user defined data type. The structure variable s1 consist of 3
values namely rno, name and avg.
Union
Union is same as that of structure; here the main difference is in the allocation
of memory. In structure the memory is allocated for each and every member.
Here the maximum memory needed to store any of a variable is allocated and
the other members share the same. In union only one member will be active
at a time. The union keyword is used to create this data type.
Eg:
union student
{
int rno;
char name[25];
float avg;
};
union student s1, s2;
ENUMERATED DATA TYPE:
Enumerated data types are those in which a variable can contain only some
specific set of values. For example if a variable needs to hold only the moths,
it can have any one of the values from January to December. These types of
variables can be created as enumerated data types. This is done using the
key word “enum”.
Eg:
enum months = { “January”, “Feburary”, “March”, “April”, “May”, “June”, “July”,
“August”, “September”, “October”, “November”, “December” };
months m1, m2;
Here the variables m1 and m2 are of enumerated data types. It can
hold only the values from January to December as declared.
6. b. Structure of a C program
68
The main ( ) function can be preceded by documentation,
preprocessor statements and global declarations.
Global Declarations: The variables are declared before the main ( ) functions
as well as user defined functions are called global variables. These global
variables can be accessed by all the user defined functions including main ( )
function.
The main ( ) function: Each and Every C program should contain only one
main ( ). The C program execution starts with main ( ) function. No C program
is executed without the main function. The main ( ) function should be written
in small (lowercase) letters and it should not be terminated by semicolon.
69
Main ( ) executes user defined program statements, library functions and user
defined functions and all these statements should be enclosed within left and
right braces.
Braces: Every C program should have a pair of curly braces ({, }). The left
braces indicates the beginning of the main ( ) function and the right braces
indicates the end of the main ( ) function. These braces can also be used to
indicate the user-defined functions beginning and ending. These two braces
can also be used in compound statements.
Local Declarations: The variable declaration is a part of C program and all
the variables are used in main ( ) function should be declared in the local
declaration section is called local variables. Not only variables, we can also
declare arrays, functions, pointers etc. These variables can also be initialized
with basic data types. For examples:
Code:
main ( )
{
int sum = 0;
int x;
float y;
}
Here, the variable sum is declared as integer variable and it is
initialized to zero. Other variables declared as int and float and these
variables inside any function are called local variables.
Program statements: These statements are building blocks of a program.
They represent instructions to the computer to perform a specific task
(operations). An instruction may contain an input-output statements, arithmetic
statements, control statements, simple assignment statements and any other
statements and it also includes comments that are enclosed within /* and */ .
The comment statements are not compiled and executed and each
executable statement should be terminated with semicolon.
User defined functions: These are subprograms, generally, a subprogram is
a function and these functions are written by the user are called user ; defined
functions. These functions are performed by user specific tasks and this also
contains set of program statements. They may be written before or after a
main () function and called within main () function. This is an optional to the
programmer.
Now, let us write a small program to display some message shown below.
Code:
# include <stdio.h>
main()
70
{
printf ("welcome to the world of C/n");
}
71
7b. C program to display a pyramid structure using numbers
72
7c. C programs to display vowels in the read character
Write a C program that reads a character and displays only the
vowels using switch case structure.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
char x1,x;
clrscr();
printf("\n Enter any character:");
scanf("%c",&x);
x1=toupper(x);
switch(x1)
{
case 'A': printf("\n%c is a vowel",x); break;
case 'E': printf("\n%c is a vowel",x); break;
case 'I': printf("\n%c is a vowel",x); break;
case 'O': printf("\n%c is a vowel",x); break;
case 'U': printf("\n%c is a vowel",x); break;
default: printf("\n%c is not a vowel");
}
getch();
}
Output:
Enter any character: a
a is a vowel
75
Write a C program to reverse a number.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,temp,d,rev=0;
clrscr();
printf("Enter a number:");
scanf("%d",&n);
while(temp>0)
{
d=temp%10;
rev=rev*10+d;
temp=temp/10;
}
printf("The reverse of the number %d is %d",n,rev);
getch();
}
Output:
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("\nEnter two numbers:");
scanf("%d%d%d",&a,&b);
if(a>b)
printf("%d is the greatest number",a);
else
printf("%d is the greatest number",b);
getch();
}
Output:
Enter numbers: 5 6
6 is the greatest number
int main()
{
double a, b, c, determinant, root1,root2, realPart, imaginaryPart;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf",&a, &b, &c);
determinant = b*b-4*a*c;
// condition for real and different roots
if (determinant > 0)
{
// sqrt() function returns square root
root1 = (-b+sqrt(determinant))/(2*a);
root2 = (-b-sqrt(determinant))/(2*a);
printf("root1 = %f and root2 = %f",root1 , root2);
}
//condition for real and equal roots
else if (determinant == 0)
{
root1 = root2 = -b/(2*a);
printf("root1 = root2 = %f;", root1);
}
// if roots are not real
else
{
81
realPart = -b/(2*a);
imaginaryPart = sqrt(-determinant)/(2*a);
printf("root1 = %f+%fi and root2 = %f-%fi", realPart,
imaginaryPart, realPart, imaginaryPart);
}
return 0;
}
Output:
Enter coefficients a, b and c: 2.3 4 5.6
Roots are: -0.87+1.30i and -0.87-1.30i
#include<stdio.h>
#include<conio.h>
void main()
{
int n, i, sum = 0;
clrscr();
printf("Enter a positive integer: ");
scanf("%d",&n);
for(i=1; i <= n; i++)
{
sum += i; // sum = sum+i;
}
printf("Sum = %d",sum);
getch();
}
Output:
Enter a positive integer: 10
Sum = 55
82
UNIT III
float a[5]={1.5,1.0,1.6,1.8,1.9};
Char vowel[5]={‘a’,’e’,’i’,’o’,’u’};
8. Define sorting.
9. Define searching.
84
Part – B
1. String
Initialization of strings:
char c[]="abcd"; OR char c[5]="abcd"; OR char
c[]={'a','b','c','d','\0'};OR
char c[5]={'a','b','c','d','\0'};
Program:
#include <stdio.h>
int main(){
char name[20];
printf("Enter name: ");
scanf("%s",name);
printf("Your name is %s.",name);
return 0;
}
Output:
Enter name: Dennis Ritchie
Your name is Dennis.
85
2. Array
Write short notes on array.
Need for array: In C programming, one of the frequently arising
problems is to handle similar types of data. For example: If the
user wants to store marks of 100 students. This can be done by
creating 100 variables individually but, this process is rather
tedious and impracticable. This type of problem can be handled in
C programming using arrays.
Definition: An array is a sequence of data item of
homogeneous value (same type).
Types of array: Arrays are of two types:
One-dimensional arrays
Multidimensional arrays
Declaration of one dimensional array:
data_type
array_name[array_size];
For example:
int age[5];
Here, the name of array is age. The size of array is 5, i.e.,
there are 5 items (elements) of array age. All elements in an
array are of the same type (int, in this case).
Array elements
Size of array defines the number of elements in an array.
Each element of array can be accessed and used by user
according to the need of program. For example:
int age[5];
Program:
#include <stdio.h>
void main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
clrscr();
/* initialize elements of array n to 0 */
for ( i = 0; i < 5; i++ )
{
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
for (j = 0; j < 5; j++ )
{
printf("Element[%d] = %d\n", j, n[j] );
}
getch();
}
Output:
Element[0]=100
Element[1]=101
Element[2]=102
Element[3]=103
Element[4]=104
3. String operations
Program:
#include <stdio.h>
#include <string.h>
void main()
{
char c[20];
printf("Enter string: ");
gets(c);
printf("Length of string c=%d \n",strlen(c));
}
Output : Enter string: String
Length of string c=6
ii. strcpy():Function strcpy() copies the content of one string to the
content of another string. It is defined under "string.h" header file. It
takes two arguments.
Syntax: strcpy(destination,source);
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s[10],s1[10];
clrscr();
puts("Enter a string");
gets(s1);
strcpy(s,s1);
puts("The string after copy");
puts(s);
getch();
}
Output:
88
Enter a string:
Hai
The string after copy
Hai
Here, source and destination are both the name of the string.
This statement, copies the content of string source to the
content of string destination.
iii. strcat():In C programming, strcat() concatenates(joins) two
strings.It takes two arguments, i.e, two strings and resultant string is
stored in the first string specified in the argument.
Syntax: strcat(destination,source);
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s[10],s1[20];
clrscr();
puts("Enter the first string:");
gets(s);
puts("Enter the second string:");
gets(s1);
strcat(s,s1);
puts(“The concatenated string is:”);
puts(s);
getch();
}
Output:
Enter the first string: come
Enter the second string: in
The concatenated string is:
comein
iv. strcmp():In C, strcmp() compares two string and returns value 0, if
the two strings are equal. It is defined under "string.h" header file.
Syntax: temp_varaible=strcmp(string1,string2);
Program:
#include <stdio.h>
#include <string.h>
void main()
89
{
char a[100], b[100];
clrscr();
printf("Enter the first string:");
gets(a);
printf("Enter the second string:");
gets(b);
if( strcmp(a,b) == 0 )
printf("Entered strings are equal.\n");
else
printf("Entered strings are not equal.\n");
getch();
}
Output:
Enter the first string:hai
Enter the second string: Hai
Entered strings are not equal.
v. strrev(): This function reverses a given string in C language.
Syntax: strrev(str)
Program:
#include <stdio.h>
#include <string.h>
void main()
{
char arr[100];
printf("Enter a string to reverse\n");
gets(arr);
strrev(arr);
printf("Reverse of entered string is %s",arr);
}
Output:
Enter a string: welcome
Reverse of entered sting is emoclew
vi. strlwr() function converts all the uppercase characters in that string
to lowercase characters. The resultant from strlwr() is stored in the same
string.
Syntax: strlwr(string_name);
Program:
#include <stdio.h>
#include <string.h>
90
void main()
{
char str1[]="LOWer Case";
puts(strlwr(str1)); //converts to lowercase and displays it.
}
Output: lower case
vii. strupr()function converts all the lowercase characters in that string
to uppercase characters. The resultant from strupr() is stored in the
same string.
Syntax: strlwr(string_name);
Program:
#include <stdio.h>
#include <string.h>
void main()
{
char str1[]="UPPEer case";
puts(strupr(str1)); //converts to upper case and displays it.
}
Output: UPPER CASE
4. a Sum of two matrices
}
else
printf("Matrix Addition is not possible");
getch();
}
Output:
Enter matrix A: 2 1 2
321
233
Enter matrix B: 2 1 0
230
112
Resultant Matrix is:
422
551
345
4b.C program to perform subtraction of two matrices
Write a C program to subtract two matrices and display the
resultant matrix. May / June 15
#include<stdio.h>
#include<conio.h>
void main()
{
int a[12][12],b[12][12],n,m,p,q,i,j,c[12][12];
clrscr();
printf("Enter the no of rows and columns of matrix a:");
scanf("%d %d",&n,&m);
printf("Enter the no of rows and columns of matrix b:");
scanf("%d %d",&p,&q);
if((n==p)&&(m==q))
{
printf("Matrix subtraction can be performed:\n");
printf("Enter Matrix A:\n");
for(i=0;i<n;i++)
{
93
for(j=0;j<m;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter Matrix B:\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<n;i++)
for(j=0;j<m;j++)
c[i][j]=a[i][j]-b[i][j];
printf("Matrix A:\n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
printf("Matrix B:\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
printf("%d\t",b[i][j]);
}
printf("\n");
}
printf("The resultant matrix is : \n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf("%d\t",c[i][j]);
94
}
printf("\n");
}
}
else
printf("Matrix subtraction is not possible");
getch();
}
95
5. C program to multiply two matrices
}
else
printf("Matrix Multiplication is not possible");
getch();
}
97
Output:Enter the no of rows and columns of matrix a:
2 2
Enter the no of rows and columns of matrix b:
2 2
Matrix Multiplication can be performed:
Enter Matrix A:
2 1
2 3
Enter Matrix B:
1 3
2 1
Matrix A:
2 1
2 3
Matrix B:
1 3
2 1
The resultant matrix is :
4 7
8 9
PROGRAM:
#include<stdio.h>
main()
{
int a[10][10],i,j,m,n,big,small;
printf("enter the values of m,n");
scanf("%d%d",&m,&n);
printf("enter the elemnts of matrix a");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
big=a[0][0];
small=a[0][0];
for(i=0;i<m;i++)
for(j=0;j<n;j++)
if(a[i][j]>big)
big=a[i][j];
if(a[i][j]<small)
small=a[i][j];
printf("biggest element =%d",big);
printf("smallest element =%d",small);
}
OUTPUT:
enter the values of m,n
3,3
enter the elements of matrix a
123
105
345
567
biggest element 7
smallest element 1
#include<stdio.h>
#include<conio.h>
void main()
{
char ch[10];
int i,count=0;
clrscr();
printf("Enter the string\n");
gets(ch);
for(i=0;ch[i]!='\0';i++)
{
if(ch[i]=='a' || ch[i]=='e' || ch[i]=='i' || ch[i]=='o' || ch[i]=='u')
{
count++;
}}
printf(“No of vowels - %d”,count);
getch();
}
Output:
Enter the string: Francis Xavier
No of vowels – 5
106
Unit – IV
Functions & Pointers
Part – A
108
An object of type void cannot be created, but it is possible to create a
pointer to void. Such a pointer is known as “void pointer” and has a type
void *. A void pointer is a generic pointer and can point to any type of
object.
11. Define pointer. What are the uses of pointers? Jan 2014
Pointer is a variable that holds the address of another variable.
Uses of pointers:
Pointers can be used to pass information back and forth between the
function and its reference points.
It provides a way to return multiple data functions from a function via
function arguments.
It reduces the length and complexity of a program
It increases the execution speed.
It enables to access the variables that is defined outside the function.
109
12. How is pointer arithmetic done? May / June 16
A pointer in c is an address, which is a numeric value. Therefore, arithmetic
operations can be performed on a pointer just as on a numeric value. There
are four arithmetic operators that can be used on pointers: ++, --, +, and -
To understand pointer arithmetic, that ptr is an integer pointer which points to
the address 1000. Assuming 32-bit integers, the following arithmetic
operation can be performed on the pointer –
ptr++
After the above operation, the ptr will point to the location 1004 because each
time ptr is incremented, it will point to the next integer location which is 4
bytes next to the current location. This operation will move the pointer to the
next memory location without impacting the actual value at the memory
location. If ptr points to a character whose address is 1000, then the above
operation will point to the location 1001 because the next character will be
available at 1001.
110
15. What is the output of the following program? May / June 15
main()
{
int a=8,b=4,c=1,*p1=&a,*p2=&b;
c= *p1**p2-*p1/*p2+9;
printf(“%d”,c);
}
Output : 39
111
Part – B
112
Output:
Enter the values of a and b 2 3
The addition of 2 and 3 is 5
b. Function with argument and without return type: In this
prototype data is transferred from calling function to called
function i.e. the called program receives some data from the
calling program and does not send back any value to the calling
program. Such functions are partly dependent on the calling
function.
113
called program receives some data from the calling program and
send back a value to the calling program.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int add(int,int);
int a,b,c;
clrscr();
printf("Enter the values of a and b");
scanf("%d%d",&a,&b);
c=add(a,b);
printf("The addition of %d and %d is %d",a,b,c);
getch();
}
int add(int a1,int b1)
{
return(a1+b1);
}
Output:
Enter the values of a and b 2 3
The addition of 2 and 3 is 5
d. Function without argument and with return type: In this
prototype the calling program cannot pass any argument to the
called program but the called program may send some return
value to the calling program.
2. Function prototype
#include<stdio.h>
void main()
{
..........
void function_name();
...........
function_name();
............Step 1
}
void function_name()
{
.............Step 2
.............
}
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int c,a,b;
int add(int,int);
clrscr();
printf("Enter the values of a and b to perform addition:");
scanf("%d%d",&a,&b);
c=add(a,b);
printf("The sum is %d",c);
getch();
}
int add(int a1, int b1)
117
{
return(a1+b1);
}
Output:
Enter the values of a and b to perform addition: 2 3
The sum is 5
Explain about call by value and call by reference. Jan 14, Nov 14
Explain about pass by value and pass by reference. May 16
OR
Explain in detail about parameter passing methods in C
4. Pointers
5. Recursion
121
Syntax: fun()
{
fun();
}
Program:
To calculate factorial of a number
#include<stdio.h>
#include<conio.h>
main()
{
int fact(int);
int n;
clrscr();
printf("Enter a number:");
scanf("%d",&n);
printf("The factorial of %d is %d",n,fact(n));
getch();
}
int fact(int n1)
{
int f;
if(n1==0||n1==1)
return(1);
else
f=n1*fact(n1-1);
return(f);
}
Output:
Enter a number: 5
The factorial of 5 is 120
#include<stdio.h>
int main(){
int num,x;
clrscr();
printf("\nEnter a number: ");
122
scanf("%d",&num);
x=findsum(num);
printf("Sum of the digits of %d is: %d",num,x);
return 0;
}
int r,s;
int findsum(int n){
if(n){
r=n%10;
s=s+r;
findsum(n/10);
}
else
return s;
}
Output:
Enter a number : 123
Sum of the digits of 123 is 6
#include<stdio.h>
#include<conio.h>
#define MAX 30
void main() {
int size, i, arr[MAX];
int *ptr;
clrscr();
ptr = &arr[0];
126
int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}
Output:
Enter the number of terms in fibonacci series:5
Fibonacci series
0 1 1 2 3
Program:
#include <stdio.h>
#include<conio.h>
void max_min(int number[],int n);
void main()
{
int i, j, a, n, number[30];
clrscr();
printf("Enter the value of N \n");
scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; ++i)
scanf("%d", &number[i]);
max_min(number,n);
getch();
}
void max_min(int number[],int n)
127
{
int a,i,j;
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (number[i] > number[j])
{
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
printf("The numbers arranged in ascending order are given below \n");
for (i = 0; i < n; ++i)
printf("%d\t", number[i]);
printf("\nThe minimum element in the array is %d",number[0]);
printf("\nThe maximum element in the array is %d",number[n-1]);
}
Output:
128
Unit – V
Structures & Unions
Part – A
Structure Union
When a variable is associated with a
When a variable is associated with a
structure, the compiler allocates the
union, the compiler allocates
memory for each member. The size
the memory by considering the size
of structure is greater than or equal
of the largest memory. So, size of
to the sum of sizes of its members.
union is equal to the size of largest
The smaller members may end with
member.
unused slack bytes.
Each member within a structure is
Memory allocated is shared by
assigned unique storage area of
individual members of union.
location.
Individual member can be Only one member can be accessed
accessed at a time at a time.
Syntax: Syntax:
struct structure_name union structure_name
{ {
Structure member1; union member1;
Structure member 2; union member 2;
------------------------ ------------------------
} }
129
3. What is the purpose of Unions in C? June 2014
What are advantages of union over structure?
State the importance of union. April / May 16
All the members use the same memory space to store the values,
hence storage space is reduced.
It can handle only one member at a time even all the members use the
same memory space.
Unions are particularly useful in situations where there is a need to use
only one of its member elements at any given point of time.
7. What is typedef?
The typedef keyword allows the programmer to create a new data type
name for an existing data type. The typedef does not occupy storage; it
simply defines a new type.
Syntax:
typedef <existing data type> <new data type...>;
Example:
typedef int id_no;
id_no regno;
The static storage class: The value of static variable persists until the
end of the program. A variable can be declared static using
keyword: static.
Syntax: static datatype var1,var2,..........;
Example: static int a;
Program:
#include<stdio.h>
#include<conio.h>
void main()
131
{ void f1();
clrscr();
f1();
printf("\tFirst Call\n");
f1();
printf("\tSecond Call\n");
getch();
}
void f1()
{ static int k=0;
int j=10;
printf("Value of K is %d and J is %d",k,j);
k=k+10;
}
Output:
Value of K is 0 and J is 10 First Call
Value of K is 10 and J is 10 Second Call
132
12. Justify the need for structured data type. Nov / Dec 14
133
Part – B
1.Structures in C
Example:
struct student
{
char name[50];
int regno;
int m1;
int m2;
};
This declaration above creates the derived data type struct student.
Structure variable declaration
Syntax: struct structure_name structure_variable;
When a structure is defined, it creates a user-defined type but, no
storage is allocated. For the above structure of student, variable can be
declared as:
struct student
{
char name[50];
int regno;
134
int m1;
int m2;
};
Inside main function:
struct student s1, s2, s[20];
Another way of creating sturcture variable is:
struct student
{
char name[50];
int regno;
int m1;
int m2;
}s1 ,s2 ,s[20];
In both cases, 2 variables s1, s2 and array s having 20 elements of type
struct student are created.
Accessing members of a structure
There are two types of operators used for accessing members of a
structure.
1. Member operator(.)
2. Structure pointer operator(->)
Syntax: Any member of a structure can be accessed as:
structure_variable_name.member_name;
Example: s.regno;
Program:
#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
int regno;
int m1,m2,m3,tot,per;
}s[10];
void main()
{
int i,n;
clrscr();
printf("Enter the number of students:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
135
printf("Enter the regno, name, marks for three subjects");
scanf("%d%s%d%d
%d",&s[i].regno,s[i].name,&s[i].m1,&s[i].m2,&s[i].m3);
}
printf("Reg No\tName\tMark1\tMark2\tMark3\tTotal\tPercentage\n");
for(i=0;i<n;i++)
{
s[i].tot=s[i].m1+s[i].m2+s[i].m3;
s[i].per=s[i].tot/3;
}
for(i=0;i<n;i++)
{
printf("%d\t%s\t%d\t%d\t%d\t%d\t
%d",s[i].regno,s[i].name,s[i].m1,s[i].m2,s[i].m3,s[i].tot,s[i].per);
printf("\n");
}
getch();
}
Output:
Enter the number of students: 3
Enter the regno, name, marks for three subjects: 1 xxx 56 56 50
Enter the regno, name, marks for three subjects: 2 eee 50 50 50
Enter the regno, name, marks for three subjects: 3 yyy 80 80 81
Reg No Name Mark1
Mark2
Mark3
Total Percentage
1 xxx 56 56 50
162 54
2 eee 50 50 50
150 50
3 yyy 80 80 81
241 80
136
2. Union
OUTPUT:-
How many students? 3
Enter the Roll Number: 201 202 203
201
202
203
Enter the name of the student: Anu Banu Angel
Anu
Banu
Angel
Enter the total marks: 100 99 100
100
99
100
3. Storage classes
What is storage class? List and explain with example. Jan 2014
Explain the concept of storage classes with suitable example.
May / June 14,15,16
A storage class defines the scope (visibility) and life-time of variables
and/or functions within a C program. These specifiers precede the type
that they modify. There are the following storage classes, which can be
used in a C program.
a. auto
139
b. register
c. static
d. extern
a. The auto storage class: Variables declared inside the
function body are automatic by default. These variables are
also known as local variables as they are local to the
function and don’t have meaning outside that function. Since,
variable inside a function is automatic by default, keyword
auto are rarely used.
Syntax: auto datatype var1,var2,........;
Example: auto int a,b; OR int a,b;
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
auto int c=3;
clrscr();
printf("C=%d\n",c);
{
c=4;
printf("C=%d\n",c);
}
printf("C=%d",c);
getch();
}
Output:
C=3
C=4
C=4
b. The static storage class: The value of static variable persists
until the end of the program. A variable can be declared
static using keyword: static.
Syntax: static datatype var1,var2,..........;
Example: static int a;
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
140
void f1();
clrscr();
f1();
printf("\tFirst Call\n");
f1();
printf("\tSecond Call\n");
getch();
}
void f1()
{
static int k=0;
int j=10;
printf("Value of K is %d and J is %d",k,j);
k=k+10;
}
Output:
Value of K is 0 and J is 10 First Call
Value of K is 10 and J is 10 Second Call
c. The extern storage class: External variable can be accessed
by any function. They are also known as global variables.
Variables declared outside every function are external
variables.
Syntax: extern datatype var1,var2,..........;
Example: extern int a;
Program:
#include<stdio.h>
#include<conio.h>
extern int d=150;
void main()
{
void calla();
void callb();
clrscr();
calla();
callb();
printf("In main() D=%d\n",d);
getch();
}
void calla()
{
141
int d=124;
printf("In calla() D=%d\n",d);
}
void callb()
{
printf("In callb() D=%d\n",d);
}
Output:
In calla() D=124
In callb() D=150
In main() D=150
d. The register storage class: Register variables are similar to
automatic variable and exist inside that particular function
only. If the compiler encounters register variable, it tries to
store variable in microprocessor's register rather than
memory. Value stored in register can be accessed much
faster than that of in memory. In case of larger program,
variables that are used in loops and function parameters are
declared as register variables. Since, there are limited
number of register in processor and if it couldn't store the
variable in register, it will automatically store it in memory.
Syntax: register datatype var1,var2,...........;
Example: register int a,b;
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
register int i;
clrscr();
for(i=0;i<=2;i++)
printf("i=%d\n",i);
getch();
}
Output:
i=0 i=1 i=2
4. Pre-processor directives
145
printf("Current time: %s",__TIME__); //calculate the current
time
}
Output
Current time: 19:54:39
5. Nested structures
Write short notes on nested structure
Explain about structure within structure
Define a structure to store date, which including day, month and
year. Jan 2014
Structures within structures: A structure can be defined with
another structure.Structures can be nested within other structures in C
programming.
struct person;
{
int pid;
char name[20];
struct dob
{
int date;
int month;
int year;
};};
struct person
{ struct dob d; }p1,p2;
To access date of dob : p1.d.date;
148
Practical and industrial connectivity of the subject
149
University Questions
FIRST SEMESTER
CIVIL ENGINEEERING
GE6151 – COMPUTER PROGRAMMING
(COMMON TO ALL BRANCHES)
(REGULATION 2013)
TIME : 3 HOURS MAXIMUM MARKS: 100
Answer ALL questions
PART – A (10*2=20 MARKS)
1. Define flowchart. Why is flowchart required? [Page No 8]
2. What is an algorithm? [Page No 8]
3. What is a variable? Illustrate with an example. [Page No 33]
4. Give an example of ternary operator. [Page No 33]
5. Declare a float array of size 5 and assign 5 values to it. [Page No 83]
6. Give an example for initialization of string array. [Page No 83]
7. What is a function? [Page No 107]
8. What is an address operator and indirection operator? [Page No 109]
9. Define static storage class. [Page No 131]
10. What is the use of #define preprocessor directive? [Page No 131]
PART – B (5*16=80 MARKS)
11. a. i. Explain in detail with neat diagram about the digital computer
organization and each of its units. [Page No 14] (10)
ii. What is pseudo code? Write a pseudo code for swapping two
numbers without using temporary storage. [Page No 30 & 31] (6)
OR
b. i. Perform the following: [Page No 32] (12)
151
1. (100101)2 – (11111001)2
2. (1011101)2*(1011)2
3. (2A947)H=(?)2
4. (4872)=(?)
ii. Discuss the need for Logical Analysis with an example in brief.
[Page No 19] (4)
12. a.What are the various operators available in C? Discuss each one of
them with suitable illustration. [Page No 54] (16)
b. Explain in detail about looping structures available in C with
illustrative programs. [Page No 48] (16)
13. a. i. Write a C programs for sorting array of numbers. [Page No 99] (8)
ii. Explain the various string operations. Write a C program to find out
the length of the string without using string functions.
[Page No 86] (8)
OR
b. i. Write a C program to multiply two matrices. [Page No 95] (8)
ii. Write a C program to search an element in a given array.
[Page No 100] (8)
14. a. What is a function in C? Discuss about call by value and call by
reference with illustration. [Page No 117] (16)
OR
b. What is recursion? Explain a recursive function with suitable
example. Write a iterative and recursive function to find power of a number.
[Page No 120] (16)
15. a.i. What is a structure? Create a structure with data members of
various types and declare two structure variables. Write a C program to
read data into these and print the same. [Page No 133] (10)
ii. Justify the need for the structured data type. [Page No 132] (6)
b. Write short notes on : (4*4=16)
i. Unions [Page No 136]
ii. Register storage class [Page No 131]
iii. #include statement [Page No 142]
iv. #ifndef…..#endif [Page No 144]
152
(REGULATION 2013)
TIME : 3 HOURS MAXIMUM MARKS: 100
Answer ALL questions
PART-A(10*2=20 Marks)
1. Convert Binary Number 110 100 111 101 to Octal. [Page No 9]
2. Draw Flow chart to find biggest of two number. [Page No 22]
3. List different data Types in C. [Page No 34]
4. Write a C Program to find a factorial of a given Number using iteration.
[Page No 35]
5. Write a Example code to declare two dimensional Array.[Page No 82]
6. List any four String handling function. [Page No 82]
7. Define Recursion. [Page No 107]
8. What is the difference between pass by value and Pass by reference?
[Page No 108]
9. What is the purpose of Union in C? [Page No 129]
10. What is the use of Pre-Processor Directives? [Page No 129]
PART-B (5*16=80 Marks)
11. (a) (i) Discuss about Generation of digital computer.
[Page No 10] (10)
(ii) Draw flow chart to find factorial of a number.
[Page No 24] (6)
OR
(b)(i) Explain the basic organization of a computer.
[Page No 14] (10)
(ii)Draw a flow chart to find sum first 100 natural numbers.
[Page No 25] (6)
12. (a) (i) Write a program to check whether a given number is prime or not.
[Page No 71] (8)
(ii) Write a C program to find sum of digits of an integer.
[Page No 72] (8)
OR
(b) (i) Write a C program to find roots of a quadratic equation.
[Page No 79]
(8)
(ii) Differentiate entry and exit checked conditional constructs with an
example. [Page No 48] (8)
13. (a) (i)Explain the concept of pass by reference with suitable example.
[Page No 117] (8)
(ii) Write a C program to find factorial of a number using recursion.
[Page No 117] (8)
153
OR
(b) (i) Write a C program to swap the content of two variables using
Pointers. [Page No 118] (8)
(ii) Explain the use of pointers in arrays with suitable example. (8)
14. (a) Write a C Program to arrange the numbers in ascending order.
[Page No 99] (16)
OR
(b) Write a C Program to subtract two matrices and display the resultant
matrix. [Page No 92] (16)
15. (a) Explain the concept of storage class with suitable example.
[Page No 138] (16)
OR
(b) Write a C Program to store the employee information using structure
and search a Particular employee using Employee Number.
[Page No 145] (16)
B.E/B.TECH. DEGREE EXAMINATION, NOVEMVER / DECEMBER 2015
FIRST SEMESTER
CIVIL ENGINEEERING
GE6151 – COMPUTER PROGRAMMING
(COMMON TO ALL BRANCHES)
(REGULATION 2013)
TIME : 3 HOURS MAXIMUM MARKS: 100
Answer ALL questions
PART – A (10*2=20 MARKS)
1. What is a pseudocode? [Page No 7]
2. What is an algorithm? [Page No 8]
3. What is compilation process? [Page No 34]
4. Discuss the working of modulo operator. [Page No 34]
5. Declare a character array of size 5 and assign vowels to it.
[Page No 83]
6. Give some examples of string functions. [Page No 82]
7. What is function definition? [Page No 107]
8. What is an address operator and indirection operator? [Page No 109]
9. Write a note on register storage class. [Page No 131]
10. What is the usage of #define pre-processor? [Page No 131]
154
OR
b. Perform the following: [Page No 32] (4*4=16)
i. (1011.11011)2=(?)10
ii. (10111)2*(1011)2=(?)
iii. (D8BC)H=(?)2
iv. (4871)10=(?)8
12. a. What are the various operators in C? Discuss each one of them with
suitable examples. [Page No 54] (16)
OR
b. Explain in detail about various decision making structures available in
C with illustrative examples. [Page No 42] (16)
13. a. Write a C program to find the largest element and smallest element in
a matrix. [Page No 104] (16)
OR
b. Write a C program to multiply two matrices. [Page No 95] (16)
14. a. Discuss about call by value and call by reference with illustrations.
[Page No 117] (16)
OR
b. What is recursion? Explain a recursive function with suitable
example. Write a recursive function to find the factorial of a number.
[Page No 120] (16)
15. a. What is a structure? Create a structure with data members of various
types and declare two variables. Write a program to read data in to
these and print the same. [Page No 133] (16)
b. Write short notes on: (4*4=16)
i. Union [Page No 136]
ii. Static storage class [Page No 131]
iii. #include statement [Page No 142]
iv. #ifndef……#endif [Page No 144]
155
B.E/B.TECH. DEGREE EXAMINATION, MAY / JUNE 2015
FIRST SEMESTER
CIVIL ENGINEEERING
GE6151 – COMPUTER PROGRAMMING
(COMMON TO ALL BRANCHES)
(REGULATION 2013)
TIME : 3 HOURS MAXIMUM MARKS: 100
Answer ALL questions
PART – A (10*2=20 MARKS)
1. What is super computer? Give an example. [Page No 6]
2. Define pseudo code. [Page No 7]
3. What is the importance of keywords in C ? [Page No 35]
4. List the various input and output statement in C. [Page No 34]
5. What is an array? Give an example. [Page No 82]
6. How is a character string declared? [Page No 82]
7. Compare actual parameters and formal parameters. [Page No 105]
8. What is the output of the following program? [Page No 110]
main()
{
int a=8,b=4,c,*p1=&a,*p2=&b;
c=*p1**p2-*p1/*p2+9;
printf(“%d”,c);
}
9. What do you mean by structures? [Page No 130]
10. Give the use of preprocessor. [Page No 129]
(ii) Convert the decimal number 681.75 into binary, octal and
hexadecimal equivalent. [Page No 32](6)
Or
(b) (i) Explain the basic organization of a computer with neat diagram.
[Page No 14] (10)
(ii) Draw a flowchart to check whether the given number is zero, positive or
negative. [Page No 28] (6)
12. (a) (i) Explain the different types of operators available in C.
[Page No 54] (8)
156
Or
(b) (i) Describe the various looping statements used in C with suitabl
examples. [Page No 48] (8)
(ii) Write a C program to solve the quadratic equation.
[Page No 79] (8)
13. (a) (i) Write a C program to add two matrices. [Page No 90] (10)
Or
(b)(i) Explain the various storage classes in C. [Page No 138] (10)
(ii)What is union? Discuss with an example. [Page No 136] (6)
B.E/B.TECH. DEGREE EXAMINATION, MAY / JUNE 2016
FIRST SEMESTER
CIVIL ENGINEEERING
GE6151 – COMPUTER PROGRAMMING
(COMMON TO ALL BRANCHES)
(REGULATION 2013)
TIME : 3 HOURS MAXIMUM MARKS: 100
Answer ALL questions
PART – A (10*2=20 MARKS)
157
1. Classify the computers based on performance, size, cost and capacity.
[Page No 7]
2. Convert the binary number 10110111.1101 into decimal number.
[Page No 9]
3. What are variables? Give examples. [Page No 33]
4. Define implicit type conversion. [Page No 37]
5. What is an array? [Page No 82]
6. Define string. Give examples. [Page No 82]
7. Specify the advantages of functions. [Page No 107]
8. How is pointer arithmetic done? [Page No 107]
9. What do you mean by structures? [Page No 130]
10. State the importance of union. [Page No 129]
PART – B (5*16=80 MARKS)
11. a.(i) Describe the basic organization with neat diagram.
[Page No 14] (10)
(ii) Draw the flow chart to solve the quadratic equation.
[Page No 29] (6)
OR
b.(i)Explain the various generations of computers.[Page No 10] (8)
(ii) What is pseudo code? Explain its guideline and its benefits.
[Page No 30] (8)
12. a. (i) Explain the different types of operators available in C.
[Page No 54] (10)
(ii) Discuss the basic data types in C. [Page No 63] (6)
OR
b. (i) Describe the various input and output statements in C with suitable
examples. [Page No 51] (10)
(ii) Write a C program for the following series:
1+2+3+4+....................+n [Page No 80] (6)
13. a.(i) Write a C program to count the number of vowels in your name.
[Page No 105] (6)
(ii) Write a C program to multiply two matrices. [Page No 95] (10)
OR
b.(i) Write a C program to check wether the given string is palindrome or
not. [Page No 102] (6)
(ii) Write a C program to arrange the given 10 numbers in descending
order. [Page No 101] (10)
14. a. (i) Write a C program to find the smallest and largest number from the
given 10 numbers using functions. [Page No 126] (10)
(ii) Explain the pass by reference with an example.[Page No 117] (6)
158
OR
b. (i) Write a C program to find the factrorial of a given number using
recursion. [Page No 121] (8)
(ii) Write a C program to count the number of words in a string using
pointers [Page No 124] (8)
15. a. Define a structure called student would contain name, register
number and marks for five subjects and percentage. Write a program to
read the details of name, rgister number and marks for five subjects for 25
students, calculate the percentage and display the name, register number,
marks of 25 subjects, percentage of all the students and also the name of
the students who got highest percentage among the 25 students.
[Page No 133] (16)
OR
b. (i) Explain the various storage classes in C. [Page No 138] (8)
(ii) Describe about the pre-processors with suitable example.
[Page No 142] (8)
159