UNIT I INTRODUCTION
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
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
Arrays Initialization Declaration One dimensional and Two dimensional arrays. StringString operations String Arrays. Simple programs- sorting- searching matrix operations.
UNIT IV FUNCTIONS AND POINTERS
Function definition of function Declaration of function Pass by value Pass by reference
Recursion Pointers - Definition Initialization Pointers arithmetic Pointers and arraysExample Problems.
UNIT V STRUCTURES AND UNIONS
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.
UNIT I INTRODUCTION
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.
Introduction
Definition of computer:
The computer is an electronic device which converts raw data into valid (or) meaningful
information.
Data :
* facts about anything.
*Data is the raw material of information processing.
Information:
The processed data is called the information and the data or information comes in various shapes
(or) size depending upon the application.
Generations of computers:
1. First Generation [1940-1956]: Vacuum Tubes
2. Second Generation [1956-1963]: Transistors
3. Third Generation [1964-1971]: Integrated Circuits
4. Fourth Generation [1971-Present]: Microprocessors
5. Fifth Generation [Present and Beyond]: Artificial Intelligence
First Generation - 1940-1956: Vacuum Tube
The first generation computers used vacuum tubes for circuitry and magnetic drums for
memory.
A magnetic drum, also referred to as drum, is a metal cylinder coated with magnetic ironoxide material on which data and programs can be stored.
Input was based on punched card and paper tape.
It have 3 leads
1st lead-voltage
2nd lead-current
Magnetic cores used as primary memory and magnetic disks used as secondary
memory.
They still relied on punched cards for input and printout for output
Progress from machine language to assembly language.
Assembly language used mnemonics [abbreviations] for instructions rather than numbers.
High-level programming languages were also being developed at this time, such as early
versions of COBOL and FORTRAN.
Characteristics of second generation computer:
Based on transistor technology
Comparatively smaller
Computational time reduced from milliseconds to microsecond
Assembly language was used to program, become more efficient.
Advantages:
Smaller in size as compared to first generation computers.
More reliable.
Less heat generated.
These computers were able to reduce computational times from milliseconds to
microseconds.
The development of the integrated circuit was shown start of third generation computers.
Also called as IC, an integrated circuit consists of a single chip [silicon] with transistor
and resistors.
It replaces several individual wired transistors.
It replaces the punched cards and printouts, it uses keyboard and monitors interfaced with
operating system.
It allows different applications run at one time.
First time computers are used by many peoples.
Eg: NCR 395and B6500
Characteristics of third generation computer:
Based on IC technology
Computational time reduced from microsecond to nano seconds
Consume less power and generate less heat
Hardware is rarely failed.
Eg:Apple-II,CRAY-1
Characteristics of fourth generation computer:
Microprocessor-base system.
GUI and pointing device lead to learn computer quickly.
They could be linked together to form networks leads to resource sharing
Very small.
Cheapest among all generations
Advantages:
Smallest in size.
Very reliable.
Heat generated is negligible.
No air conditioning required in most cases.
Hardware failure is negligible easily portable because of their small size.
Cheapest among all generations.
Disadvantage:
Highly sophisticated technology required for the manufacture of LSI chips.
Fifth Generation [Present and Beyond]: Artificial Intelligence
The dream of creating a human like computers would be capable of reasoning and
reaching a decision through a series of what-if-then.
Computers should learn from its mistakes and posses the skill of experts.
Three characteristics of 5th generation computer are
1. Mega chips
2. Parallel processing
3. Artificial Intelligence [AI]
1. Mega chips:
Fifth generation computer use SLSI (super large scale integrated circuit).
SLSI is production of micro
Mega chips may enable the computer to approximate memory capacity of the human
mind.
2.Parallel processing:
Access and execute only one instruction at a time, this is called serial processing
Access several instructions at once and also works on them at same time.
3.Artificial Intelligence
Artificial Intelligence is the branch of computer science concerned with making
computers behave like humans.
Series of related technologies tries to reproduce human behavior include thinking,
speaking and reasoning.
Comprises a group of related technologies: expert system[ES],natural language
processing[NLP],speech recognition, vision recognition and robotics.
Characteristics of fifth generation computer:
This generation computers are very fast, highly reliable, user friendly systems.
Having much faster and large primary storage capacity.
Support parallel programming
Support wide operating system.
S.no
Generation
computers
of Component used
speed
Language used
1.
First generation
Vaccum tube
Milliseconds
Machine language
2.
Second
generation
Transistor
Micro seconds
assembly language
3.
Third generation
Integrated circuits
Nanoseconds
4.
1 to 10 nanoseconds
4GL
5.
fifth generation
1 to 100 nanoseconds
Artificial
intelligence
Artificial
intelligence
TYPE
DESCRIPTION
a) Analog
b) Digital
c) Hybrid
Based on
Utility
Based on Size
a) Micro Computer
and Capacity
b) Mini Computer
c) Mainframe Computer
d) Super Computer
Based on
a) palmtop PC
Mode of Use
b) Laptop pc
c) PC
d) Workstation
e)mainframe system
f) Server
Analog Computers: These computers recognize data as a continuous measurement of a physical property
(voltage, pressure, speed and temperature).
An analog computer operates on inputs of continuously varying electrical Voltages.
Analog computers are used mainly in scientific design and production environments.
Characteristics:
Requires by measuring.
Function on continuously varying quantity.
Hybrid Computers:
This computer that processes both analog and digital data.
Desirable features of analog and digital machines can be combined to create a Hybrid
Computer.
This type of computer operates by counting as well as by measuring.
Measuring functions are performed by analog way.
Control and logic functions are digital in nature.
2. Based on utility
1. General purpose Computers
2. Special purpose Computers
General purpose Computers
It is designed to satisfy the needs of the society.
A General Purpose Computer is a machine that is capable of carrying out some general
data processing under program control.
Applications:
Business
Scientific problems
It consist of microprocessor whose components namely input, output and cpu are on a single
integrated circuit chip.
Advantages:
Small and portable.
Relatively inexpensive.
Dont occupy much space and power.
Disadvantages:
Relatively slow.
Storage capacity also slow.
Minicomputers:
They are smaller than mainframe, general purpose computers, and give computing power
without adding the prohibitive expenses associated with larger systems. It is generally easier to
use.
Word length -32 bits.
Processing speed is in the range of 10 to 30 MIPS.
Memory [RAM] capacity lies in the range 8 to 256 MB.
Minicomputers usually have multiple terminals.
Minicomputers may be used as network servers and Internet servers.
Eg: payroll preparation, accounting computation.
Advantages:
General purpose computer.
Storage capacity is about 2 mega words.
Use all high level languages
Mainframe Computers:
These computers are usually slower, less powerful and less expensive than supercomputers.
A technique that allows many people at terminals, to access the same computer at one time is
called time sharing. Mainframes are used by banks and many businesses to update inventory etc.
to
mobile
users.
c) Personal computers
It is mainly designed to meet the personal computing requirements of users at working place or
at home
Non-portable
These computers have rapidly changed the work culture and habits of individuals
It is used by children, adults for education, entertainments and common everywhere.
Control Unit
Input unit
Memory Unit
Output Unit
ALU
Secondary Storage
Data Flow
Control Flow
It having
1) Input unit
2) CPU
3) Output unit
1. Input unit
Computer must need the data and instructions to solve any problem.
We put data and instructions into the computer.
Keyboard is one of the most commonly used input device.
The input device perform following functions
a. Accept data and instructions from the outside world.
b. Convert it to a form that computer can understand.
c. Supply the converted data to the computer system for further processing.
Eg for input devices are
o It controls the flow of data and instructions from storage unit to ALU.
o It controls the flow of data and instructions from ALU to storage unit.
ii) Arithmetic and logic unit
It performs all arithmetic and logical operations.
Arithmetic operations like addition, subtraction, multiplication and logical
operations such as comparison are performed in ALU.
All calculations are performed in ALU.
It performs comparison and takes decision.
E.g.: if the number A is less than, equal to or greater than the number B. Once the calculation is
over, then the result transferred to storage unit.
iii)Memory unit
Memory is a device which is used to store information temporarily or permanently.
Memory is the part of computer which holds data for processing and other information. It
is called main memory or primary memory.
Secondary storage also used for storage purpose but permanently.
memory
primary
memory
RAM
ROM
secondary
memory
Serial access
memory
Serial random
access memory
Eg:magnetic
tape
Eg:floppy disk
Primary memory
The primary memory is also called main memory. stores and access information very
fastly.
It is used to hold the program being currently in the computer, the data being received
from input unit, the intermediate and final results of the program.
It loses its content when we switch off the computer. primary memory is also known as
system memory, internal, temporary and RAM.
Primary memory is two types
i) ROM [read only memory]
ii) RAM [random access memory]
i) ROM [Read Only Memory]
It having
a) Floppy disk
b) Hard disk
c) CDROM
d) Magnetic tape
e) Cache memory
f) Virtual memory
a) Floppy disk
It is the piece of a plastic that we put into computer to store information.
b) Hard disk
It is permanent storage, where we store lots of information.
c) CDROM [Compact Disk-Read Only Memory]
It is used to store large amount of data.i.e 700MB to 1.4GB
d) Magnetic tape
It is used as a backup storage for data stored on online storage devices.
e) Cache memory
A small memory between CPU and main memory are called cache memory.
f) Virtual memory
It is just an imaginary memory.
3) Output unit
Devices used to get the response (or) result of a process from the computer.
Output unit is communication between user and computer.
It provides the information and results of a computation to outside world.
Computers does not work in the decimal system,they work in binary system.
Output unit converts the binary data into a form the users can understand.
Commonly used output devices are
a) Monitor
b) Printer
c) Plotter
c) Computer output microfilm
Write the uses of algorithm with suitable examples.
Algorithm
Algorithm is a finite sequence of instructions required for producing the desired result.
Characteristics:
Time
Memory
Accuracy
Sequence etc,.
Representations:
Flowcharts
Normal English
Pseudo code etc,.
Example
Step1: Start
Step2: Read a, b
Step3: Add the value of a with b and store the result in c.
Step4: Display the value of c.
Step5: Stop.
Terminal symbol
It is used to represent the start, end of the program logic.
Input/Output
It is used for input or output.
Process Symbol
It is used to represent the calculations, data movements, initialization operations
etc,.
Decision Symbol
Flow lines
It is used to connect the symbols
Connectors
It is used to connect the flow lines.
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.
START
STOP
Only one flow line should enter the decision symbol and two or three flowlines may
leave from the decision symbol.
Benefits of Flowcharts
Limits of Flowcharts
It is difficult to use flowcharts for large program
Difficult to modify
Cost etc,.
Design Structures
1. Sequence structure
START
Read
Process
Output
STOP
A series of statements performed one after other. Because the flow always continuous
in same direction every time the structure is executed.
A sequence may include a number of instructions, but each would be done in turn in
the same order.
2. Selection structure
Is
A>B
False
B is big
True
A is big
Start
Count=0
If
count<10
No
Add 1 to count
Stop
Display Count
Yes
START
Count=0
Add 1 to count
Display count
No
If count
> 10
Yes
STOP
Keywords
READ,GET
PRINT,DISPLAY
COMPUTE,CALCULATE
Example
READ a,b
C=a+b
WRITE C
stop
Example
READ a,b
IF a>b
PRINT a is greater
ELSE
PRINT b is greater
ENDIF
Stop
Flow chart
Process 1
Pseudocode
Process 1
Process 2
Process 2
Process n
Process n
The instructions are computed in sequence i.e. it performs instruction one after another.
It uses top-down approach
Example
START
Read a,b
C=a+b
Print c
STOP
Specification
Review
Informal Design
Formal Design
Coding
Specification review
collect the requirements
understand the requirements
Informal Design
Identifies the major tasks
Identifies the subtasks
Formal Design
It converts the informal design to some format that can be understand by others.
Coding
It converts the Design into Programs.
It translate these programs to machine language.
Test & Debug
It use sample data to test whether it works properly.
It also eliminate the errors.
Maintaining
It Modifies the programs if necessary
Waterfall method
Feasibility
Analysis
Design
Impl
Testing
Maintenance
Feasibility
It determines whether it is possible to create the project or not.
It also produce the plans and the estimates.
Analysis
Design
It is the process of designing how the requirements to be implemented.
Implementation
It converts the designs into code.
After coding it use language translators to compile the code.
Testing
Here the modules are integrated together.
Then the project is tested and find whether it meets the customer/user
requirements.
Maintenance
It make modifications based on the customer feedbacks.
Introduction:
1. Application Software: It is set of programs necessary to carry out for specific applications.
2. System Software: The general programs written for the system which provide the
environment to facilities the writing of application software.
(i)
(ii)
FORTAN
COBOL
(iii)
(iv)
(v)
BASIC
PASCAL
C Language
Introduction to C
'C' is one of the most popular programming language; it was developed by Dennis Ritchie
at AT & T's Bell Laboratories at USA in 1972.
It is an upgraded version of two earlier languages, called BCPL and B, which were also
developed at Bell laboratories.
History of C Language
ALGOL
BCPL
ANSI
All modern computer languages are started through the ALGOL language in 1960.
After the COBOL was being used for commercial applications.
FORTAN was developed for scientific applications.
A committee was formed to develop a new language called Combined Programming
Language (CPL) at Cambridge University.
Basic CPL was derived by BCPL.
BCPL was developed by Martin Richards at Cambridge University by 1967.
At the same time a language called B was developed by Ken Thomson at AT &
Ts Bell labs in 1970.
Then C language is developed by Dennis Retchie in 1972 with some additional
features of BCPL and B which is very simple.
ANSI C American National Standard Institute has began to work on a standardized
definition of the C language that makes it still powerful.
Types of Language:
Low level Language (or) Machine Language.
High Level Language normal English, human understandable language,
machine independent, C, C++, etc
Structure of C Program
A C program may contain one or more section.
Documentation section
Preprocessor section
Definition section
main()
Declaration part;
Executable part;
1. Documentation Section :
of the program etc.
Comments:
3. Global Declaration Section: The section declares some variables that are used more
than one function. These variables are known as global variables. These variables must
be declared outside of the main function.
Function main:
3. Blank space may be inserted between words. But blank space is not used while
declaring a variable, keyword, constant and function.
4. The programmers can write the statement anywhere between the two braces.
5. We can write one or more statements in a same line by separating each statement
in a same line by separating each statement with semicolon (:)
6. The opening and closing braces should be balanced.
*************************************************************
CONSTANTS, VARIABLES AND DATA TYPES
Character Set
Character set is a fundamental raw material of any language.
C Character Set
Alphabets
Digits
Special
Character
Execution Character
Set
White
Spaces
Escape Sequence
Alphabet A to Z and a to z
Digit 0 to 9
Special Character +,-,?,/,(,),*,&,^,$,#,@,!,<,>,:,;,,,_,=
White space Blank Space, horizontal tabs, vertical Tab, newline, form feed.
Character
Escape Sequence
Result
Bell
\a
Beep Sound
Back Space
\b
Horizontal Tab
\t
Vertical Tab
\v
\n
Form feed
\f
Carriage return
\r
Question mark
\?
Question mark
Apostrophe
Backslash
\\
NULL
\0
NULL
C Tokens
Token is defined as collection of entity. They are identifiers, keywords, constants, strings,
operators, special symbols.
Tokens are usually referred as individual text & punctuation in a passage of text.
C Tokens
Identifiers
Keyword
Constants
Eg : main()
Eg., int
Eg., 39.77
String
Eg., XYZ
Operator
Eg., +,-,*
Special symbols
Eg., #,$,%
Identifiers:
Keywords
Keywords are reserved words by the compiler that have standard and fixed (or)
predefined meaning in C Language.
auto
double
int
struct
break
else
long
case
enum
registertypedef
char
extern
return
union
const
float
short
unsigned
continue
for
signed void
default goto
do
sizeof
if
switch
volatile
static
while
Constants:
C Constants
Numeric Constants
*Integer constant
*Real constant
Character Constants
*Single character
constants
*String Constant
Definition:
Constants do not change during the execution of a program.
Numerical Constant:
1. Integer constant
2. Real constant
Integer constant
They are the sequence of numbers from 9 without decimal point (or) fractional part (or)
any symbols.
Eg., 10,20,+30,-5, etc
Real Constant
Real constant are often known as floating point constants
Eg: 2.4, 5.345, 4.123 etc
Character constant:
Data types:
Allows the programmers to select the appropriate data type as per the need of the
application.
Data types are used to specify the types of data.
They are in different types
1. char
(i) Signed Character
(ii) Unsigned Character
2. int
3. float
4. double
5. long double
ANSI C supports four class of data type:
1.
2.
3.
4.
Signed Char
Occupies 1 byte in memory range- 128 to
127 control string %c
Unsigned Char
Occupies 1 byte in memory range 0 to 255
control string %c
Signed Integer
1.
2.
3.
4.
Unsigned Integer
1.
2.
3.
4.
Float:
Long double:
Primary data
types
Integer
Signed
int
Short int
Character
Unsigned
Signed Char
Long int
Unsigned
int
Unsigned
short int
Unsigned
long int
Unsigned Char
Integer Types:
Type
Size (bits)
Range
16
unsigned int
16
0 to 65535
short int
-128 to 127
0 to 255
long int
32
32
-2,147,483,648 to 2,147,
483, 647
0 to 4,294,967,295
Type
Size (bits)
Range
Float
32
3.4E-38 to 3.4E+38
Double
64
1.7E-308 to 1.7E+308
long double
80
3.4E-4932to 1.1E+4932
Type
Size (bits)
Range
Char
-128 to 127
unsigned char
0 to 255
Character Types:
VARIABLE DECLARATION:
Syntax:
Eg: int a;
char m;
float s;
Initializing Variables:
Syntax:
Variable name must begin with a character without spaces but underscore(_) is permitted.
The variable should not be a Cat keyword
The variable names may be a combination uppercase and lower case character.
Scope of the variable implies the availability variables within the program.
Variables have 2 types of scope
(i)
Local variable
(ii)
Global variable
Local variable:
Local variables are defined inside a function block(or) inside a compound statement of a
function subprogram are called local variables.
Eg:
function()
{
int i,j;
}
function()
{
int i,j;
}
{
}
Operator:
An operator is a symbol that specifies an operation to be performed on the operands.
Operand:
Eg: a+b
Here, a, b Operator
+ Operand
Explain various types of operators in C language with suitable example
Types of Operator:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
Arithmetic operators
Arithmetic operators are,
+ , - , * , / , %.
C allows basic arithmetic operations like addition, subtraction, multiplication and division.
+
Addition
2+9 = 11
Subtraction
9-2= 7
Multiplication
2*9= 18
Division
9/3= 3
Modulo division
9%2=1
b=3.5
a+b 6.5+3.5 = 10
Sample program:
#include<stdio.h>
#include<conio.h>
void main()
{
int b,c,d;
int sum, mul, sub, rem;
float div;
clrscr();
printf(Enter values of b,c,d:);
scanf(%d%d%d\n\n\n, &b,&c,&d);
sum=b+c;
sub=b-c;
mul=b*c;
div=b/c;
rem=b%d;
printf(\n sum=%d,\n sub=%d,\n mul=%d,\n div=%f,sum,sub,mul,div);
printf(\n Remainder of division of b&d is %d,rem);
getch();
}
Output:
Div=0.6666666
Reminder of division of b&d is 0
Relational operator
Relational operators are used to compare two or more operands. Operands may be variables,
constants or expression.
Operator
Meaning
<
is less than
<=
>
is greater than
>=
==
is equal to
!=
is not equal to
Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf(\n condition: Return value \n);
printf(\n 5!=5: %5d, 5!=5);
printf(\n 5==5:%d,5==5);
printf(\n 5>=50: %d,5>=50);
printf(\n 5<=50: %d,5<=50);
Return value
5!=5
5==5
5>=50
5<=50
5!=3
Logical operators:
Logical operators are used to combine the results of two or more conditions.
Operator
Meaning
Example
Return value
&&
Logical AND
(9>2)&&(17>2)
||
Logical OR
(9>2)||(17==7)
Logical NOT
29!=29
#include<stdio.h>
#include<conio.h>
void main()
{
int c1.c2,c3;
clrscr();
printf(Enter the values c1,c2,c3);
scanf(%d%d%d, &c1,&c2&c3);
if((c1<c2)&&(c1<c3))
printf(c1 is less than c2 and c3);
if(!(c1<c2))
printf(\n c1 is greater than c2);
if((c1<c2)||((c1<c3))
printf(c1 is less than c2 or c3 both);
getch();
}
Output:
Enter the values c1,c2,c3
9
6
3
C1 is greater than c2
Assignment Operator:
Example : x=10;
x=a+b;
x=y;
+=
x+=y
x=x+y
-=
x-=y
x=x-y
*=
x*=y
x=x*y
Nested assignment
Assign a value (or) Expression to variable.
Syntax:
var1 = var2 = var3
Ex: i=j=k=1
x=y=z=(i+j+k)
Sample Program for assignment operator
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k;
clrscr();
k=(i=4,j=5);
printf(k=%d,k);
getch();
}
Output:
k=5
Increment & Decrement Operator:
'C' has two way useful operators not generally found in other languages, these are the
increment (++) and decrement (--) operators. + & - operators are called unary operators.
Because they acts upon only one variable.
++x Pre increment
--x Pre decrement
x++ Post increment
x-- Post decrement.
#include<stdio.h>
#include<conio.h>
Void main()
{
int a=10;
clrscr();
printf(a++=%d\n,a++);
printf(++a=%d\n,++a);
printf(-- a=%d\n,--a);
printf(a--=%d\n,a--);
getch();
}
Output:
a++=10
++a=12
--a=11
a--=11
Conditional Operator
#include<stdio.h>
#include<conio.h>
void main()
{
int a=5,b=2,big;
clrscr();
big=(a>b)?a:b;
printf(Largest number is %d,big);
getch();
}
Output:
Largest number is 5
Bitwise Operator:
Bitwise operators are used to manipulate the data at bit level. It operates on integers only
Operator
Meaning
&
Bitwise AND
Bitwise OR
Bitwise XOR
<<
Shift left
>>
Shift right
One's complement
#include<stdio.h>
#include<conio.h>
Void main()
{
int a,b,c;
clrscr();
a=10;
b=20;
c=a&b;
printf(Bitwise AND=%d,c);
c=a/b;
printf(Bitwise OR=%d,c);
c=a+b;
printf(Bitwise XOR=%d,c);
c=~a;
printf(ones complement=%d,c);
getch();
}
Output:
AND=2
OR=10
XOR=8
Ones complement= 5
Special Operator:
Operators
Meaning
Comma Operator
Sizeof
size of operator
& and *
Pointer Operator
Special Operator:
Sizeof() Operator:
The sizeof() operator : The sizeof() is a unary operator, that returns the length in bytes of
the specified variable, and it is very useful to find the bytes occupied by the specified variable in
the memory.
Expressions:
An expression represents data item such as variables, constants and are interconnected
with operators as per the syntax of the language.
Example:
y=(a/b)+c; z=(a*b)-d;
*************************************************************
Explain briefly formatted and unformatted in input/output functions in C
Or
Explain Managing Input and Output Operator:
In C Language two types of Input/output statements are available and all input and
output operations are carried out by through function calls.
(i)
(ii)
Formatted functions :
Definitions :
1. scanf();
2. fscanf();
scanf();
This statements reads all the types of data values from the input device
(Keyboard)
It is used for runtime assignment of variables.
Scanf() requires conversion symbol(control string) to identify the data to be
read during execution of the program.
Syntax:
Eg:
scanf(%d %f %c&a,&b,&c);
Control string:
It is type of data that user going to accept via input statements.
Eg:
%c,%d,%f,%s
& var :
Each variable name must be proceeded by an ampersand(&).
A symbol gives the meaning address of the variable.
The address operator prints memory location of the variable.
Rules for writing scanf() function:
1.The control string must begin with (%)sign and must be within quotations.
2.If there is a number of input data items, items must be repeated by commas,and
must begin with(&)sign except for string input.
3.The control string and the variables going to input should match with each other.
4.It must have termination with semicolon.
#include<stdio. h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf (Enter the values of a, b;);
scanf(%d %d, &a, &b);
c=a+ b;
printf (c=%d ,c);
getch();
}
Output:
Enter the values of a, b
2
4
6
Formatted output function:
printf()
printf() is formatted output function.
It is used to print the result message on the output screen.
It prints all types of data values.
Syntax:
Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf(Enter the value;);
scanf(%d ,&a);
printf(b=%d,a);
getch();
}
Output:
Enter the value
3
4
b=3
}
*getchar();
This functions reads character type data from the standard input. It reads one
character at a time till the user processes the enter key.
put();
put ch();
put char();
put s();
put c();
This functions is used to display single character in a character variable to standard output
device.
Syntax:
put c (char variable);
Eg: char c;
put(c);
putch();
This function prints any alphanumeric character taken by standard input device.
ch=get ch();
putch(ch);
putchar()
This function prints one character on the screen at a time which is read by the standard
input.
Eg:
#include <stdio.h>
#include<ctype.h>
#include <conio.h>
main()
{
char ch;
clrscr();
printf(enter any alphabet either in lower or uppercase)
ch=getchar();
if(is lower(ch))
put char (to upper (ch));
else
put char (to lower (ch));
}
Output
enter any alphabet either in lower or uppercase
record
RECORD
puts()
This function print the string (or) character array to the standard output device.
Eg:
#include<stdio.h>
main()
{
char scientist[40];
puts(Enter name);
gets(scientist);
puts(print the name);
puts(scientist);
}
Decision making:
C language provides four general categories of control structure.
a) Sequential structure
In which instructions are executed in sequence
Eg:
i=i+1;
j=j+1;
b) Selection structure
Sequence of the instructions is determined by using the result of the condition.
Eg:
if(x>y)
i=i+1;
else
j=j+1;
c) Iteration structure
In which statements are repeatedly executed. These form program loops.
Eg:
for(i=1;i<=5;i++)
{
i=i+1;
}
Encapsulation structure:
if(a==b)
{
..
..
}
}
*********************************************************
Explain different types of conditional statement
Or
Explain in detail about Decision making
Decision making:
Conditions are placed in the program using decision making statements.
Decision making statements check the condition and then executes its sub blocks.
C language provides the following conditional statements.
if statements
if..else statements
nested if.else statements
if statements
ifelse ladder
if is a c keyword.
The if statement is a decision making statement
Used to control the flow of execution by executing statements when the logical condition
is true (or) false.
condition
True
Statement-1
Eg:
False
#include<stdio.h>
void main()
{
int a;
printf(enter the value);
scanf(%d,&a);
if(a==10)
{
printf(Both are equal);
}}
if ..else statement
condition
Statement 1
Statement 3
Statement 2
Statement 4
Syntax:
if(condition is true)
{
statement 1;
statement 2;;
}
else
{
statement 3;
statement 4;
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf(enter the value);
scanf(%d,&a);
if(a==10)
{
printf(both are equal);
}
else
{
printf(both are not equal);
}
getch();
Output :
#include<stdio.h>
#include<conio.h>
void main()
{
int num,rem;
clrscr();
printf(Enter ur number);
scanf(%d,&num);
rem=num%2;
if(rem==0)
printf(the number is even);
else
printf(the number is odd);
getch();
Output:
Enter the number
2
The number is even
if..else statement is written in another if.else statement called nesting and the
statement is called nested if
Syntax:
if(condition 1)
{
if(condition 2)
{
True statement 2;
}
Else
{
false statement 2;
}
}
else
{
false statement 1;
}
/*For nested if..else to find out smallest of 3 number*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,small;
clrscr();
printf(Enter three numbers);
scanf(%d%d%d,&a,&b,&c);
if(a<b)
{
if(a<c)
small=a;
else
small=c;
}
else
{
if(b<c)
small=b;
else
small=c;
}
printf(the smallest value is %d,small);
getch();
}
Output:
Enter the three numbers
2
3
4
The smallest value is 2
if.else Ladder
if(condition 1)
{
Statement 1;
else
if(condition 2)
{
Statement 2;
}
else
if(condition 3)
{
Statement 3;
}
else
{
default-statement;
}
True
False
Condition 1
True
Statement 1
False
Condition
2
True
Statement 2
False
Cond
3
Statement 3
Default
Statement
#include<stdio.h>
main()
{
int a,b,c,d;
printf(enter the four numbers);
scanf(%d%d%d%d,&a,&b,&c,&d);
if((a<b)&&(a<c)&&(a<d))
printf(a is greater);
else
if((b>a)&&(b>c)&&(b>d))
printf(b is greater);
else
if((c>a)&&(c>b)&&(c>d))
printf(c is greater);
else
printf(d is greater);
return(0);
}
Output:
enter the four numbers
2
5
3
6
d is greater
case constant 2:
statement 2;
break;
case constant 3:
statement 3;
break;
default:
statement;
}
Switch
Case 1
Statement
Case 2
Statement
Default
Statement
Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, c, option;
printf(\n 1.Addition);
printf(\n 2.subtraction);
printf(\n 3.multiplication);
printf(\n 4.Division);
printf(\n 5.Exit);
printf(\n Enter two number);
scanf(%d %d, &a, &b);
printf(\n Enter your option)
scanf(%d, &option);
switch(option)
{
Case 1:
c=a+b;
printf(\n Addition=%d ,c);
break;
case 2:
c=a-b;
printf(\n subtraction=%d,c);
break;
case 3:
c=a*b;
printf(\n multiplication=%d,c);
break;
case 4:
c=a/b;
printf(\n division=%d,c);
break;
case 5:
Exit(0);
break;
default:
printf(Invalid Choice);
}
getch();
}
Output:
*************************************************************
Describe the statements for looping
Loop:
A loop is defined as a block of statements which are repeatedly executed for certain
number of times.
They are three types of loop control statements
1. for
2. while
3. do-while
Give the syntax for loop statement and explain with suitable example
for loop
Syntax:
counter)
{
statement 1;
statement 2;
}
Initialization
Increment/
Decrement
Body of loop
Condition
True
False
Increment/
Decrement
Condition
Body of loop
Ex:
#include<stdio.h>
#include<conio.h>
main()
{
int i, sum=0;
for(i=1;i<=10;i++)
{
sum=sum+i;
}
printf(The addition of numbers upto 10 is %d,sum);
getch();
}
Output:
While loop:
It is repetitive control structure used to executed the statements within the body
until the condition becomes false.
Condition
false
true
Syntax:
while(test condition)
{
body of the loop;
}
Test Condition:
It may be any expression.
The while loop is an entry controlled loop statement means the condition is evaluated
first and it is true, then the body of the loop is executed.
After executing the body of the loop, the condition is once again evaluated and if it is
true, the body is executed once again, the process of repeated execution of the body of the
loop continues until the condition becomes false and the control is transferred out of the
loop.
Eg: Sum of given number using while loop.
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1,sum=0;
while(i<=10)
{
sum=sum+1;
i++;
}
printf(the sum of numbers upto 10 is %d);
getch();
}
Output:
#include<stdio.h>
void main()
{
int number, digit, rev=0;
printf(Enter the number:);
while(number!=0)
{
digit=number%10;
rev=rev*10+digit;
number=number/10;
}
printf(%d,rev);
getch();
}
do.while
Syntax:
do
{
Statement;
}
while(condition);
Condition
#include<stdio.h>
#include<conio.h>
void main()
{
int i=2,sum=0;
do
{
sum=sum+i;
i++;
}
while(i<=10)
printf(sum of the numbers upto 10 is=%d,sum);
getch();
}
Output:
sum of the numbers upto 10 is 54
Difference between while and do.while
While
do.while
Continue statement:
The condition statement is used for continuing next iteration of loop statements.
It is useful when we want to continue the program without executing any part of the
program.
Eg:
#include<stdio.h>
void main()
{
int i,n,sum=0;
for(i=1;i<=5;i++)
{
printf(Enter any number);
scanf(%d,&n);
if(n<0)
continue;
else
sum=sum+n;
}
Printf(sum is.%d,sum;);
}
Output:
Syntax:
goto label;
Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
int x;
printf(Enter a number);
scanf(%d,&x);
{
if(x%2==0)
{
goto even;
}
else
{
goto odd;
even;
printf(number is even number);
return;
odd:
}
printf(number is odd);
}
}
Output:
Enter a number 5
number is odd
Continuous
1. Continue statement takes the
control to the beginning of the loop.
2. This can be used only in loop
statements.
3. This is also associated with if
condition.
The group of charcter,digits and symbols enclosed with in a quotation marks are called string.
Header file used is string.h Null charater(\0) is used to mark the end of the string.
Eg:
Char name[]={b,t,o,j,\0};
Example:
char city[9]=New York;
char city[ ]=New York;
.
Strcmp ()
Strcat()
Strcpy ()
strlwr()
strupr()
strdup()
strrev()
strchr()
strrchr()
Strnset()
Strrchr()
strcmpi
strlen() function:
This function is used to count and return the number of characters present in a string.
Syntax:
Var=strlen(string);
#include <stdio.h>
#include <string.h>
int main()
{
char name[]=INDIA;
int num;
printf(enter your name\n");
num = strlen(name);
printf(The length of the string is %d,num);
return 0;
}
Output
The length of the string is 5
Strcpy()
This function is used to copy the contents of one string to another string.
Syntax:
strcpy(string1,string2);
string1-destination string.
String2-source string.
#include <stdio.h>
#include <string.h>
int main ()
{
char source[10]=hello;
char target[10];
strcpy (target,source);
printf (The Target string is:%s,target);
return 0;
}
Output
strcat(string1,string2);
string2 is combined with string1 and it removes the null character(\0) of string1 and
places string from there.
#include<stdio.h>
#include<string.h>
void main()
{
char name1[ ]=Computer;
char name2[10]=science;
strcat(name1,name2);
printf(The concatenated string is%s,name1);
printf(name2 is%s,name2);
}
Output:
The cancatenated string is Computerscience
name2 is science
strcmp()
This function is used to campares two string and find whether are same or not.
Syntax:
strcmp(string1,string2);
#include<stdio.h>
#include<string.h>
void main()
{
char name1[ ]=vino;
char name2[ ]=mano;
int a,b,c;
a=strcmp(name1,vino);
b=strcmp(name1,name2);
c=strcmp(name1,vino mano);
printf(/n %d %d %d,a,b,c);
}
output
If two string are identical strcmp() returns a value zero.If they are not identical it returns
the numeric difference between the first non-matching character.
strrev()
This function is used to reverse a string.
Syntax:
strrev(string);
#include<stdio.h>
#include<string.h>
void main()
{
char city[];
char rcity[];
printf(enter the city\n);
gets(city);
printf(\nThe reversed string is %s, strrev(city));
}
Output
enter the city
chennai
The reversed string is iannehc
Eg:
enum n;
enum operator
};
{
plus;
minus;
multiplication;
division;
};
enum operator opr1,opr2;
opr1=plus;
opr2=division;
By default the values in the enum are assigned ffom 0.In the above mentioned
example,plus=0,minus=1 and so on.
#include<stdio.h>
#include<string.h>
void main()
{
enum week{sunday = 0,Monday,Tuesday,Wednesday,Thursday,friday}
clrscr();
printf(mon=%d\n,Monday);
printf(tue=%d\n,tuesday);
printf(fri=%d\n,friday);
getch();
}
Output:
Mon=1
Tue=2
Fri=5
************************************************************************
Explain in detail about Array
ARRAYS
Arrays are data structures which hold multiple variables of the same data type. Consider the
case where a programmer needs to keep track of a number of people within an organization. So
far, our initial attempt will be
to create a specific variable for each user. This might look like,
Arrays, like other variables in C, must be declared before they can be used. The replacement
of the above example using arrays looks like,
int names[4];
names[0] = 101;
names[1] = 232;
names[2] = 231;
names[3] = 0;
We created an array called names, which has space for four integer variables. You may also
see that we stored 0 in the last space of the array. This is a common technique used by C
programmers to signify the end of an array.
Arrays have the following syntax, using square brackets to access each indexed value (called
an element).
x[i]
so that x[5] refers to the sixth element in an array called x. In C, array elements start with 0.
Assigning values to
array elements is done by,
x[10] = g;
and assigning array elements to a variable is done by,
g = x[10];
In the following example, a character based array named word is declared, and each element
is assigned a character. The last element is filled with a zero value, to signify the end of the
character string (in C, there is no
string type, so character based arrays are used to hold strings). A printf statement is then used to
print out all
elements of the array.
/* Introducing array's, 2 */
#include <stdio.h>
main()
{
char word[20];
word[0] = 'H';
word[1] = 'e';
word[2] = 'l';
word[3] = 'l';
word[4] = 'o';
word[5] = 0;
printf("The contents of word[] is -->%s\n", word );
}
DECLARING ARRAYS
Arrays may consist of any of the valid data types. Arrays are declared along with all other
variables in the declaration section of the program.
/* Introducing array's */
#include <stdio.h>
main()
{
int numbers[100];
float averages[20];
numbers[2] = 10;
--numbers[2];
printf("The 3rd element of array numbers is %d\n", numbers[2]);
}
The above program declares two arrays, assigns 10 to the value of the 3rd element of
array numbers, decrements this value ( --numbers[2] ), and finally prints the value. The number
of elements that each array is to have is
included inside the square brackets
The declaration is preceded by the word static. The initial values are enclosed in braces, eg,
Example:
#include <stdio.h>
main()
{
int x;
static int values[] = { 1,2,3,4,5,6,7,8,9 };
multi[i][j]
In the above example, the first index value i specifies a row index, whilst j specifies a
column index.
DECLARATION
int
m1[10][10];
static int m2[2][2] = { {0,1}, {2,3} };
{ 0, 1 },
{ 2, 3 }
Remember that arrays are split up into row and columns. The first is the row, the second
is the column. Looking at the initial values assigned to m2, they are,
m2[0][0] = 0
m2[0][1] = 1
m2[1][0] = 2
m2[1][1] = 3
Example:
#include <stdio.h>
#include<conio.h>
main()
{
#include <stdio.h>
#include<conio.h>
main()
{
static char name1[] = {'H','e','l','l','o'};
static char name2[] = "Hello";
clrscr();
printf("%s\n", name1);
printf("%s\n", name2);
getch();
}
Output: Hello
The difference between the two arrays is that name2 has a null placed at the end of the
string, ie, in name2[5], whilst name1 has not. To insert a null at the end of the name1 array, the
initialization can be changed to,
Consider the following program, which initializes the contents of the character based array word
during the program, using the function strcpy, which necessitates using the include file string.h
Example:
#include <stdio.h>
#include <string.h>
#include<conio.h>
void main()
{
char word[20];
strcpy( word, "hi there." );
printf("%s\n", word );
getch();
}
Output:
hi there
Function definition:
Defining its element and characteristics.
Function Declaration:
Like the normal variables in a program,the function can also be declared before they
defined and invoked.
Syntax:
datatype func_name(parameter list)
{
Variable declaration;
Body of the function;
}.
Func_name-name of function.
Parameter list-list of parameters that the
function can convey.
Eg:
int add(int x,int y)
{
}
Function call:
The function can be called by simply specifying the name of the function,return value
and the parameters if presence.
func_name();
func_name(parameter);
return value=func_name(parameter);
Parameter:
Parameters provide the data communication between the calling function and called function.
Example:
main()
{
fun(a,b);
}
fun(x,y)
{
}
a &b are actual parameter
x & y are formal parameter
Types of variable
LOCAL AND GLOBAL VARIABLES:
There are two kinds of varibles.
1. Local variable.
2. Global variables.
1. Local variable:
The local variable are defined within the body of the function.these variables are
defined local to that function only or block only,other function cannot access these variables.
Eg:
Value(int a,int b)
{
int c,d;
}
c and d local variables.
2. Global variables.
Global variables are defined outside the main() function.multiple function can use
these variables.
Eg:
int m=5,n=10;
main()
{
int a,b;
}
m and n are global variables.
Program to demonstrate local and global variables
#include<stdio.h>
#include<conio.h>
int i=0;
void f1();
i=o;
clrscr();
printf(value of i in main:%d\n,i);
f1();
printf(value of i after call:%d\n,i);
getch();
}
Void f1(void)
{
int k;
i=50;
}
Output:
Value of i in main:0
Value of i after call:50
RETURN statement
The return statement may or may not send back any values to main program.
The return statement can take the form:
Syntax:
return;
or
return(exp);
Eg:
if(x <= 0)
return(0);
else
return(1);
FUNCTION calling:
A function can be called by simply using the function name in the statement.
Eg:
main()
{
message();
printf(main message);
}
message()
{
printf(function message\n);
}
Explain different function prototypes:
Function prototypes:
The functions are classified into the following types depending on the arguments are
present or not and whether the value is returned or not. These are also called function prototypes.
A function prototype declaration consists of the function return type, name and
arguments list.
Prototype:
Function with no arguments & no return value.
Function with arguments & no return value.
Function no arguments & with return value.
Function with arguments & return value.
Main()
func1()
..
Func1();
..
..
..
}
Main()
func1(x,y)
..
Func1(a.b);
..
..
}
main()
{
void add(int,int);
int a,b;
printf(enter the values);
scanf(%d %d,&a,&b);
add(a,b) ;
}
void add(int x,int y)
{
int z;
..
}
z=x +y:
printf(the sum is%d:,z);
}
In this prototype, one way data communication takes place. i.e the calling program cannot
pass any arguments to called program but, the called program may send return value to the
calling program.
Main()
data_type func1(x,y)
..
func1();
return(z);
..
..
}
void main()
{
int add();
int c;
c=add();
printf(the sum %d,c);
}
int add()
{
int x,y,z;
printf(enter the values);
scanf(%d %d,&x,&y);
z=x+y;
return(z);
}
data_type func1(x,y)
..
Func1(a.b);
return(z);
..
..
}
void main()
{
int add(int,int);
int a,b,c;
printf(enter the values);
scanf(%d %d,&a,&b);
c=add(a,b);
printf(the result %d,c);
}
/* a=5,b=3; */
int add(int x,int y)
{
int z=x+y;
return(z);
}
****************************************************************
Explain in detail about parameter passing methods
Or
Explain in detail about call by value and call by reference
Call by value
Call by reference.
1. Call by value
It copies the value of actual parameter in to formal parameter.
Change of formal parameter cannot affect the actual parameter.
void main()
int square(int x);
main()
{
int n=3;
printf(the square %d,n,square(n));
}
int square(int)
{
x=x*x;
return(x);
}
Output:
the square 9
Call by reference
The address of arguments are copied into the parameter inside the function, address is
used to access the actual argument.
void change(int *a,int *b)
main()
{
int x=5,y=10;
printf(values of x,y %d%d,x,y);
change(&x,&y);
printf(after interchange %d%d,x,y);
}
}
output:
values of x,y 5 10
after interchange 10 5
Recursion
Recursion is the process of calling the same function itself again and again until some
condition is satisfied.
#include<stdio.h>
#include<conio.h>
main()
{
int a;
printf(enter the value);
scanf(%d,&a);
printf(the factorial is %d,fac(a));
}
fac(int x)
int n;
{
if(x==1)
return(1);
else
n=x*fac(x-1);
return(n);
}
POINTERS
1. Definition
A pointer is a variable which contains the address in memory of another variable. We can
have a pointer to any variable type.
The unary or monadic operator & gives the ``address of a variable''.
The indirection or dereference operator * gives the ``contents of an object pointed to by a
pointer''.
Declaring a pointer
Declaring pointers can be very confusing and difficult at times. To declare pointer
variable we need to use * operator before the variable identifier and after data type . Pointer can
only point to variable of the same data type.
Datatype * pointer-name;
Ex:
int *pointer;
sample Example program:
#include<stdio.h>
main()
{
int sno=89;
printf(address of sno=%u,&sno);
printf(value of sno=%u,&sno);
}
Output:
address of sno=3932
value of sno=89
Accessing a Variable Through its Pointer
The indirection operator (*) is used to access the value of a variable by its ptr
Syntax:
*pointer variable;
where
* - indirection operator
pointer variable - declared pointer variable
Program:
#include<stdio.h>
main()
{
int a;
int *b;
a=100;
b=&a;
printf("The content of the pointer b=%d\n", *b);
}
Output:
The content of the pointer b=100
Null pointer
A pointer is said to be null pointer when its right value is 0.
A null pointer can never point to valid data.
For checking a pointer, if it is assigned to 0,then it is null pointer and is not valid.
Example: int *a;
int *b;
b=a=0;
Hence a and b become null pointers after the integer value of 0 is assigned to them.
Pointer to pointer :
Pointer is a variable that contains the address of the another variable.
Similary another pointer variable can store the address of this pointer variable.so we can say this
is a pointer to pointer.
Ex:
#include<stdio.h>
main()
{
int a=22;
int *b;
int **c;
b=&a;
c=&b;
printf(\n value of a is %d,a);
printf (\n value of a is %d,*(&a));
printf (\n value of a is %d,*b);
printf (\n value of a is %d,**c);
printf (\n value of b and address of a = %u,b);
printf (\n value of c and address of b = %u,c);
printf (\n address of a = %u,&a);
printf (\n address of b = %u,&b);
printf (\n address of a = %u,*c);
Value of a is 22
Value of a is 22
Value of a is 22
Value of a is 22
value of b and address of a =2000
value of c and address of b =4000
address of a =2000
address of b = 4000
address of a =2000
address of b =4000
address of b=4000
address of c =6000
******************************************************************
Explain in detail about Array and Pointer:
Array and pointer:
When an array is declared, the compiler allocates a base address and sufficient amount of
storage to contain all the elements of array in contiguous memory location. The base addresses
the location of the first element (index 0) of the array. The compiler also defines the array name
as a constant pointer to the first element. Suppose we declare an array x as follows:
static int x[5] = {1,2,3,4,5};
Suppose the base address of x is 1000and assuming that each integer requires twobytes,
Elements
x[0]
x[1]
x[2]
x[3]
x[4]
value
1
Address
1004
1000 1002
1006
1008
The name x is defined as a constant pointer pointing to the first element x[0] and
therefore value of x is 1000, the location where x[0] is stored . That is ,
x = &x[0] =1000
main ( )
{
int *p, sum , i
static int x[5] = {5,9,6,3,7};
i = 0;
p = x;
sum = 0;
printf(Element Value Address \n\n);
while(i < 5)
{
printf( x[%d] %d %u\n, i, *p, p);
sum = sum + *p;
i++, p++;
}
printf(\n Sum = %d \n, sum);
printf(\n &x[0] = %u \n, &x[0]);
printf(\n p = %u \n, p);
}
Output
Element Value Address
X[0] 5 166
X[1] 9 168
X[2] 6 170
X[3] 3 172
X[4] 7 174
Sum = 55
&x[0] = 166
p = 176
Array
Structure
Structure can
s.no;
s.name;
s.marks;
STRUCTURE INITIALIZATION
Like any other data type, a structure variable can be initialized at compile time.
main()
{
struct
{
int weight;
float height;
}
student ={60, 180.75};
}
This assigns the value 60 to student. weight and 180.75 to student. height. There is a oneto-one correspondence between the members and their initializing values.
struct st _ record
{
int weight;
float height;
};
main()
{
}
C language does not permit the initialization of individual structure member within the
template. The initialization must be done only in the declaration of the actual variables.
#include<stdio.h>
#include<conio.h>
struct student
{
int rno;
char name[20];
int m1;
int m2;
int m3;
int total;
float avg;
}struct std s;
void main()
{
OUTPUT
Enter the roll no,name,mark1,mark2,mark3
1 raja 99 95 97
1 raja 291.00 97.00
******************************************************************************
Union:
Union is user defined data type used to stored data under unique variable name at single
me
memory location.
Union is similar to that of stucture. Syntax of union is similar to stucture. But the major
Difference between structure and union is 'storage.'
In structures, each member has its own storage location, whereas all the members of union
use the same location. Union contains many members of different types, it can handle only
one member at a time. To declare union data type, 'union' keyword is used. Union holds value
for one data type which requires larger storage among their members.
Syntax:
union union_name
{
<data-type> element 1;
<data-type> element 2;
<data-type> element 3;
}union_variable;
Example:
union techno
{
int comp_id;
char nm;
float sal;
}tch;
In above example, it declares tch variable of type union. The union contains three members
as data type of int, char, float. We can use only one of them at a time.
Memory allocation:
{
clrscr();
union name c;
c.a=99
printf("\n\t c.a value is :%d\n ",c.a);
printf("\n\t c.b[0] value is :%d\n ",c.b[0]);
printf("\n\t c.b[1] value is :%d\n ",c.b[1]);
getch();
}
Output :
c.a value is :99
c.b[0] value is :0
c.b[1] value is :1
*************************************************************************
Explain the different types of storage classes
Storage Class
A storage class defines the scope (visibility) and life time of variables and/or functions within a C Prog
There are following storage classes which can be used in a C Program
auto
register
static
extern
{
int Count;
auto int Month;
}
The example above defines two variables with the same storage class. auto can only be used within fun
local variables.
register is used to define local variables that should be stored in a register instead of RAM. This means
variable has a maximum size equal to the register size (usually one word) and cant have the unary '&' operator
(as it does not have a memory location).
{
register int Miles;
}
Register should only be used for variables that require quick access - such as counters. It should also be
defining 'register' goes not mean that the variable will be stored in a register. It means that it MIGHT be stored
register - depending on hardware and implementation restrictions.
static is the default storage class for global variables. The two variables below (count and road) both ha
storage class.
static int Count;
int Road;
{
printf("%d\n", Road);
}
static variables can be 'seen' within all functions in this source file. At link time, the static variables defined her
be seen by the object modules that are brought in.
static can also be defined within a function. If this is done the variable is initalised at run time but is not reinita
the function is called. This inside a function static variable retains its value during vairous calls.
void func(void);
main()
{
while (count--)
{
func();
}
i is 6 and count is 9
i is 7 and count is 8
i is 8 and count is 7
i is 9 and count is 6
i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i is 15 and count is 0
Extern is used to give a reference of a global variable that is visible to ALL the program files
When you use 'extern' the variable cannot be initialized as all it does is point the variable name at a stor
location that has been previously defined.
When you have multiple files and you define a global variable or function which will be used in other f
then extern will be used in another file to give reference of defined variable or function. Just for unders
extern is used to decalre a global variable or function in another files.
File 1: main.c
int count=5;
main()
{
write_extern();
}
File 2: write.c
void write_extern(void);
void write_extern(void)
{
printf("count is %i\n", count);
}
This fill produce write program which can be executed to produce result.
Count in 'main.c' will have a value of 5. If main.c changes the value of count - write.c will see the new value
*************************************************************
age
20
#define
CITY
#define
9.8
#define
10
CHENNAI
The #define A 10 macro substitutes A with 10 in all occurrences in the source program.
ii) Argumented macros
The Argumented macros are used to define more complex and useful form of
replacements in the source program.
Syntax:
#define identifier (v1 v2 v5.v4)string/integer
#define B A+2
2. Conditional Inclusion:
These are used to control the preprocessor with conditional statements.
Example:
#define op P
main()
{
#ifdef P printf(PENTIUM);
#else printf(CELERON);
#endif
}
The preprocessor directives are,
Directive
Function
#include
#define
#ifdef
#else
#undef
******************************************************************