-
Chapter 1 Introduction to C Programming Introduction: Lower
level language Higher level language Object Oriented Language
Feature of C Character set in C Structure of a C program Basic
Input / output functions Standard output function printf()
statement Syntax Format modifiers putchar() statement Escape
sequence C tokens Constants Integer constants Floating-point
constants Character constants String constants Symbolic constants
Identifiers Declaration of identifiers Operators Unary operator
Binary operator Turnary operator
Chapter 2 Introduction to standard input function and operators
Introduction Basic input function Scanf() Syntax Use getche()
Chapter 3 Operators in C Unary operator Binary operator Unary
Oerator Increment operator Decrement operator Binary Operator
Assignment operator Syntax: Arithmetic operators Addition Operator:
Subtraction Operator: Multiplication Operator: Division Operator:
Modulus operator Relations operator Logical Operator: Turnary
Operator:
-
Chapter 4 Introductions to Control Statements Introduction If( )
statement Syntax If ( ).. else statement Switch (Var).. Case
Chapter 5 Loops in C Loops in C While Loop Characteristic of
while loop Syntax For loop Characteristic of for loop Do.. while
loop Characteristic of do.. while loop Nested loop
Chapter 6: - Arrays in C Arrays in C Using variable Using Array
Single dimension array Actual declaration Initialization of an
array Linear Search Binary Search Sorting of an array Liner Sort
Bubble Sort method Double dimension array
Chapter 7 Strings in C Language
Strings in C Language Syntax
Chapter - 8 Functions in C Language Functions in C Language
Chapter 9 Pointers in C
Pointers in C
Chapter 10 Structure and union
Structure And Union
Chapter 11 File handling in C
File Handling In C
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
1
CHAPTER 1
INTRODUCTION TO C PROGRAMMING
Introduction:In our day to day life, we communicate with
different types of people. While we interact with them
we use specific language, English, Hindi, Gujarati and so on. A
language is generally used to interact andto convey our message to
other people. Similarly, to interact with the with the computer
system we needsome special language that helps us to interact with
it.
Computer language has various categories that are mention
below:Lower level language
Binary language (Machine Language)Assembly Language (uses
mnemonics)
Higher level languageProlog Prolog Programming logicAlgol
Algorithmic LanguageCP/M Control Program for MicroprocessorLISP
List ProgrammingBCPL Basic Combine Programming LanguageBASIC
Beginners All Purpose Symbolic instruction codeCOBOL Common
Business Oriented LanguageFortran Formula TranslatorPascal
Object Oriented LanguageC ++Java
These languages are not powerful enough to process large amount
of data or to hold large amount ofdata. So, a language needs that
can hold large amount and process it very efficiently. This reason
lead todevelop our most popular language C.
Dennis Ritchie, a system programmer, originally develops C
language under UNIX operatingsystem in 1970 at Bell Laboratory of
USA. When DOS is invented, Dennis Ritchie and Keringon rewritethis
compiler for DOS base Operating system in 1972.
Compiler :The problem of computers not understanding our
language is solved by using software programs
called translators. This translator is known as compiler.Feature
of C:
1. Case sensitive language2. Provide Modular Approach for
programming3. Portable Language
Structure of C program :A C program is set of blocks called
functions. A function is made up of one or more statements
used for performing a predefined task. A complete C program
structure is given below :
DocumentationSymbolic constant definition
File include sectionGlobal variable declaration
main( ){
DeclarationExecutable Statements
}Function 1Function 2Function N
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
2
Documentation Section :This section is an optional section. As
the name indicates it is used for the purpose of documen-
tation. It is enclosed within /* and */. Whenever the text is
enclosed between /* and */, it is considered as acomment in C.
Comments are not processed by C compiler and are left as it is.
This section is normallyused to tell about the purpose of program,
author, date of creation etc. Comments in C can be added an-ywhere
in the program.
Symbolic Constant Definition :There is a symbolic constant like
PI. To use such symbolic constant in our program we need to use
#de-fine as a prefix to it. Here #define is known as preprocessor
directive. It instructs the compiler to replaceall occurrences of
symbolic constant with the values specified against it. Normally,
symbolic constant aredefined using capital letters.Ex. #define PI
3.14
File include Section :C provides inbuilt or library functions.
Some examples are pow(), sqrt(), etc. These functions have a
pre-defined purpose. To use them we have to include files that hold
information about these functions. Thesefiles are known as header
files. The extension of header file is .h. WE use the syntax
#include to include header file in our program.
Global variable declaration Section :C variables are governed by
scope. A scope of variable is decided by using opening and closing
curlybraces { }. This variable can not be used outside the scope.
At times we need to use a variable in all thefunctions, such a
variable is known as global variable. This variable is defined
before defining all the func-tions.
Main Function :All C program contain one function with the name
main( ). This is the function from where the execution ofany C
program starts. The control is first transferred to this function
and from here rest of the operationsare carried out. main() is a
user-define function.
User defined function :C provides us a facility of breaking a
single program into set of small pieces. These pieces are known
asfunctions. In this section we define all the additional functions
used in our program. Functions have beendiscussed in detail later
on.
Character set in C:Character set refers to the set of character
used to provide instruction or command to the com-
puter. In include alphabets, numbers, and special
symbols.Uppercase letters Lowercase letters Digits SymbolsA Z, a z
0 9 *, /,,#,(,),{,} etc.
C tokensC tokens are the smallest unit in C language. C tokens
are given as follow
1. ConstantsInteger constantsFloating point constantsCharacter
constantsString constantsSymbolic constants
2. Keywords3. Identifiers4. Operators5. Special symbols
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
3
1) ConstantsInteger Constant:
1. Integer constant must have at least one digit.2. They must
not have a decimal point.3. They can be positive or negative.4. If
there is no any sign to integer it is assume to be positive.5. No
comma or blank spaces are allowed within the integer constant. e.g.
426, +756,-588 etc.
Real Constant:1. These are generally called as floating point
constant. They can be written two forms. That is,
fractional form & exponential form.2. Real constant can be
positive or negative.3. They must have decimal point.4. Default
sign is positive.5. No comma or blank spaces are allowed in the
real number. e.g. 22.45, -85.23, -
11.20, +3.211e-4, 5.6e4 etc.
Character Constants:There are two types of character
constants.Single character constant :
1. The character constant is a single alphabet or a single digit
or a single special symbol enclosedwithin the single quotation
marks.
2. Maximum length of a character is one character. e.g. f, h, =,
8etc.
String constants:String constant refers to the constants values,
which remains constants during program execution
enclosed within the double quotes. e.g. India, LCC Infotech Ltd.
etc are String constants.
Symbolic constants:We often use certain unique constants in a
program. These constants appears in number of plac-
es in the program. One example of such constant is 3.14159 this
value represent value of the mathemati-cal constant pi. This types
of constant can be defined with the help of #define
clause.example:
#define pi 3.14159
2) KeywordsKeywords have special meaning. Keyword is the word
whos meaning as already being given to theC compiler. The keywords
can not be given as variable name in C. These are also called as
reservewords. The C supports 32 different keywords listed below
:
Auto Double If Staticbreak else int structcase enum long
switchchar extern near typedefconst float register unioncontinue
far return unsigneddefault for short voiddo goto signed while
3) IdentifiersIt refers to the name of function, a variable, or
an structure. This is the user defined name consist
of a sequence of character or a digits with a letter as a first
character, or we can write the definition asfollow
It is a symbolic location in memory in which user can store his
data. It may store different types ofvalues according defined in
memory.
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
4
Rules to define the identifiers (Rules to define variable
name)1. An identifier must starts with an alphabet or underscore.2.
It consist alphabets and numbers.3. It should not exceed more than
10 characters but maximum length can be given up to 32 charac-
ters.4. It should not have same name as the reserve word of C.5.
No special characters allowed in variable name except under
score.
Variable :It is an entity that may vary during the program is
executing. Variable
is the name given to the location of the memory. This location
can contain integer, real or characterconstants.
Variable DeclarationAfter defining a variable we must defined to
the compiler. Declaration does two things:1. it tells the compiler
what the variable name.2. it specifies what type of data the
variable can hold.
Declaration of variable must be done before they are used in
program. We can declare variableas followsSyntax:
DataType variableName;Example:
int age;char ch;char name[10];float rate;
Here type means type of value stores in variable and name means
name of an identifier.
Initialization of variable (Assigning value to variable)We can
initialization variable as follow
Syntax:variableName = value;
Example:age = 25;
4) Operators :Operators are the special symbol use to perform
special operation (for example, arithmetic &
logical) on operands. Operands are the variables, constants or
expressions on which operators per-form operation.
As per the number of operands required by the operator, it is
classified in three categories:1. Unary operators2. Binary
operators3. Ternary operators
These operators require one, two and three operands respectively
for performing their operation. Op-erators will be discuss in
detail later on.
Basic Input / output functionsC has various types of basic input
and output function. They are used to accept input from stan-
dard input device, or to print output on standard output
device.
Standard output function:Standard output function printf( ) is
used to print output to standard output device, monitor. It is
a
library function defined in stdio.h (standard input output
header file)printf
This formatted output function statement defined in stdio.h file
used to print the string or the val-
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
5
ues of variables on the output screen.
Syntax:printf(, );
Here, the format string will contain the string and the format
specifiersor format codes to display the values of variables in the
sequence of format specifiers.e.g.
printf(Welcome to C);
it will print following string on the output screen.
Welcome to C
Sample C program 1.1:#include void main(){
printf(Welcome to C program);}Write above program in TurboC
editor and save with .c extension. It needs to translate into
machinereadable format. To do this we have to compile this
program.What is compilation?
Compilation is the process of translating program written in any
higher-level language to itsequivalent machine codes.How to
compile?
To compile a program press ALT + F9; compile will translate your
program into object code.How to run a program?
To run a program press CTRL + F9 from keyboard. Your program
will run and you will get youroutput.How to see output of a
program?
To see output of a program press ALT + F5 key from keyboard.
Escape Sequences
Character Meaning\n New line\t Tab\b Backspace\v Vertical tab\a
Audible Alert (Bell)\r Carriage return\f Farm Feed\\ Backslash\
Single Quote\ Double Quote
Separators
These are the symbols which are used to indicate where groups of
codes are dividedand arranged. They are basically used to define
the shape and function of the program code. Themost commonly used
separator is semicolon. All these separators are listed below:
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
6
Separator Name Purpose
( ) Parenthesis
Used to contain lists of parameters in function definition and
call.Also used for defining precedence in expressions, containing
ex-pressions in control statements, and surrounding cast types.
{ }Curly
Braces
Used to contain the values of automatically initialized arrays.
Alsoused to define a block of code for classes, functions, and
localscopes.
[ ]Square
bracketsUsed to declare array types. Also used when
dereferencing arrayvalues.
< >Angle
BracketsUsed to include header files in the program.
; Semicolon Terminating the statement/line
, CommaSeparates consecutive variable declarations. Also used to
chainstatements together inside a for loop statement.
Doublequotes
Used to declare any string or group of more than one
characters
Singlequotes
Used to declare a single character constant
Sample program :#include #includevoid main(){
clrscr();printf(Programming in C is easy.\n);printf(\tAnd so is
Pascal.);getch();
}The output of above program is :Programming in C is easy.
And so is Pascal.
Exercise for printf function:1. Write a program to print
different five statement of your favorite picnic place.2. Write a
program to print at least five statement for cricket game3. Write a
program to print your bio-data on screen4. Write a program to print
at least five statement about you and your likes and dislikes5.
Write a program to display five statements about legendary
personality of your choice.
DATA TYPESType of value that can be assigned to an identifier is
known as data types. C language uses set ofkeywords to relate a
data with its value. These keywords identify two things, the type
of value that canbe stored in an identifier and the memory space
required by an identifier. Each data type is allocated afixed
memory space in C. It is denoted by bytes.
1 byte = 8 bitsThe three basic data types are integer, float and
character.
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
7
INTEGERThese are whole numbers, both positive and negative.
Unsigned integers (positive values on-ly)are supported. In
addition, there are short and long integers. The keyword used to
define in-tegers is,
intAn example of an integer value is 32. An example of declaring
an integer variable called sum is,
int sumsum = 20
DATA TYPE DESCRIPTION RANGE BYTE RE-QUIRED
EXAMPLE
intshort int
To store a positiveor negative wholenumber.
-32768 to+32767
2 int amount;short int a;
long int -2147483648 to+2147483647
4 long int bal;
unsigned int To store a positivewhole number
0 to65535
2 unsigned int mark;
unsigned long int 0 to4294967295
4 unsigned long int ctr;
FLOATThese are numbers which contain fractional parts, both
positive and negative. The keywordused to define float variables
is,
floatAn example of a float value is 34.12. An example of
declaring a float variable called money is,
float moneymoney = 0.12
DATA TYPE DESCRIPTION RANGE BYTE RE-QUIRED
EXAMPLE
float To store a positiveor negative realnumber.
+/- 3.4e-38 to +/-3.4e +38
4 float amount;
double +/-1.7e-308 to +/-1.7e +308
8 double total;
long double 10 long double credit;
CHARACTERThese are single characters. The keyword used to define
character variables is,
charAn example of a character value is the letter A. An example
of declaring a character variable calledletter is,
char letterletter = 'A'
Note the assignment of the character A to the variable letter is
done by enclosing the value in singlequotes. Remember the golden
rule: Single character Use single quotes.
DATA TYPE DESCRIPTION RANGE BYTE RE-QUIRED
EXAMPLE
char To store a charac-ter.
-128 to +127 1 char gender;
unsigned char 0 to 255 1 unsigned char choice;
In order to print the values of the variables printf can also be
used as:
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
8
int y = 14, s = 10;printf(Values are : %d and %d,s, y);
this will print the following statement on the screen:
Values are: 10 and 14Here the %d is called as integer format
specifier and used to print the integer value of vari-able on the
screen. Such 16 different format specifiers / format codes are used
in printfas well as scanf. These are listed below:
Format Specifiers / format codes%c Character format specifier.%d
Decimal integer format specifier.%e Scientific notation for
floating point format specifier.%E Scientific notation for floating
point format specifier.%f Floating-point format specifier.%i
Integer format specifier (same as %d).%s String format specifier.%u
Unsigned integer format specifier.%ld Double format specifier.
Sample C program with format modifiers 1.2#include #include void
main(){
clrscr();printf(I have %d rupees in my pocket., 100);
}
Sample C program 1.3#include#includevoid main(){int a;float
b=10.444;char choice ='x';clrscr();a = 10;printf("The value of a is
%d",a);printf("\nThe value of b is %f",b);printf("\n answer =
%c",choice);getch();}
Sample C Program 1.4#include #include void main(){
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
9
int age;clrscr();
age=25;printf(Age is initialize by %d, age);
}
Standard input functionscanf
This formatted input function statement defined in stdio.h file
and used to accept the values of va-riables from the keyboard.
Syntax:scanf(, );
Here, the format string will contain the format specifiers or
format codesto accept the values of variables in the sequence of
format specifiers. For example:
int var1;float var2;scanf(%d%f, &var1, &var2);
This statement will read an integer number and a float number
from keyboard and storethese values in var1 and var2 respectively.
The scanf allows all the above format specifiers to usefor
inputting the values.
Sample C program 1.5#include#includevoid main(){int
a,b,ans;clrscr();printf("Enter two
numbers:");scanf("%d",&a);scanf("%d",&b);ans = a *
b;printf("%d * %d = %d",a,b,ans);getch();}
Output :Enter two numbers: 102010 * 20 = 200
A Sample program 1.6// to calculate area of circle.#include
#include #define pi 3.14159void main(){
float r=2.5, a=0;clrscr();printf(\n\t Area of a Circle is
);a=pi*r*r ;
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
10
printf(%d,a);getch();
}
Summary of major points:1 program execution begins at main()2
keywords are written in lowercase3 statements are terminated with a
semicolon4 text strings are enclosed in double quotes5 C is case
sensitive, use lowercase and try not to capitalize variable names6
\n means position the cursor on the beginning of the next line7
printf() can be used to display text to the screen8 The curly
braces {} define the beginning and end of a program block.
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
11
CHAPTER 2
FORMATTED INPUT OUTPUT FUNCTIONS
Computer basically has three parts namely, input, process and
output. Similarly, any program can bethought of as having three
parts, input, process and output. Input means to read data from
some inputdevices. Output means to write processed data to the
output device. I/O in C is done through some stan-dard library
functions.Input functions : getchar( ), getch( ), getche( ), getc(
), gets( ), scanf( )Output functions : putchar( ), putc( ), puts(
), printf( )
getchar( ):To read a single character from user / keyboard, a
function called getchar( ) is used. It does not
assign value to variable till we press an enter key from
keyboard. It echo the character on screen.Syntax:
Variable_name = getchar( );Example:
char choice;choice = getchar( );
Sample C Program 2.1#include #include void main(){
char ch;clrscr();printf(Enter any character );ch =
getchar();printf(\n\t Entered character is %c, ch);
}
getche( ):getche( ) function is also used to input a single
character. It assign character to a variable, without
pressing enter key from keyboard. It also echo character on
screen. The getche( ) function is similar togetchar( ) except that
the function getche( ) is included in the conio.h header
file.syntax:
Variable_name = getche( );Example:
char choice;choice = getche( );
Sample C Program 2.2#include #include void main(){
char ch;clrscr();printf(Enter any character );ch =
getche();printf(\n\t Entered character is %c, ch);
}getch( ) :
It is also a function which accepts a single character. it
assigns value to variable as we type inform keyboard. It accepts a
character form user but does not echo it on screen means character
will notbe visible to the screen.
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
12
syntax:Variable_name = getch( );
Example:char choice;choice = getch( );
Sample C Program 2.3A program to accept a character and print
it.#include #include void main(){
char ch;clrscr();printf(Enter any character );ch =
getch();printf(\n\t Entered character is %c, ch);
}
gets( ):We call a group of character as a string. A string in C
is enclosed within double quotation. It al-
ways ends with a null character (\0). We can use a sequence of
getchar( ) functions to accept a string.Alternatively we use gets(
) function to read string. It is a library function, stored in
stdio.h header file.syntax:
gets( Variable_name );Example:
char name[50];gets( name );
Sample C program 2.4#include #include void main(){
char name[10];clrscr();printf(Enter your Name please
);gets(name);printf(\n\t Name entered is %s, name);getch();
}
Sample program 2.5// A program to accept name, address, city
form user and print it.#include #include void main(){
char name[10], addr[15], city]15];clrscr();printf(Enter Name:
);gets(name);flushall();printf(Enter Address:
);gets(addr);flushall();printf (Enter City: );gets(city);
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
13
flushall();
printf(\n\t Name %s: , name);printf(\n\t Address %s: ,
addr);printf(\n\t: city %s ,city);getch();
}
getc( ) and putc( ) functions are discussed in detail later
on.
putchar( ) :putchar( ) function prints a single character on a
screen. It take a variable of type character as an
argument an displayed content of it.syntax:
putchar( variable_name );example:
char ch=A;putchar(ch);
Sample C program 2.6#include #include void main(){
char ch=x;clrscr();printf(Character is
);putchar(ch);putchar(\n);putchar(y);getch();
}Output :Character is xy
puts( ) statement:puts( ) statement is used to display string
type data. It take a string variable as an argument, or it
also take a constant string as argument.Syntax:
puts(variable_name);Example:
puts(India);
Sample C program 2.7#include #include void main(){ clrscr();
puts(Welcome to C program);}
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
14
Sample C program 2.8#include #include void main(){
char name[10]=Ashok;clrscr();puts(Name entered is
);puts(name);getch();
}
Exercise:1. Write a program to accept your name, address, city
and phone and print it.2. Write a program to accept sales man name
and his age and print it on screen.3. Write a program to accept
employee name, his department, and his basic salary and print it.4.
Write a program to accept student name, roll no, and marks of five
different subjects and print it.5. Write a program to accept item
name, quantity and rate and print it on screen.
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
15
CHAPTER 3
OPERATORS IN C
Operators are the special symbol use to perform special
operation (for example, arithmetic& logical) on operands.
Operands are the variables, constants or expressions on which
operatorsperform operation.An operator is the special capable of
performing any type of arithmetic operation.They are used in
program to manipulate data and variable. They usually form a part
of mathematical oflogical expression. C has rich set of
operators.
The operators in C can be categorized into eight types :1.
Arithmetic operator2. Assignment operator3. Relational operator4.
Increment and decrement operator5. conditional operator6. logical
operator7. bitwise operator8. special operator
1 ) Arithmetic operatorsArithmetic operators used to perform any
type of arithmetic operation such as addition, subtrac-
tion, multiplication and division etc. Arithmetic operator has
further following type:1. Addition operator ( + )2. Subtraction
operator ( )3. Multiplication operator ( * )4. Division Operator (
/ )5. Modulus Operator ( % )
Addition Operator:This operator is used to perform addition on
any numerical operand.e.g. c = a + b, c = c + 1 etc.
Subtraction Operator:This operator is used to perform
subtraction on any numerical operand.e.g. c= a b, c = c 1
Multiplication Operator:This operator is used to perform
multiplication on any numerical operand.e.g. c = a * b, c = c *
2
Division Operator:This operator is used to perform division on
any numerical operand.e.g. c = a / b, c = c / 3
Modulus Operator:This operator is used to perform modulus
operation on any numerical operand. e.g. c = a % 10, c
= a %10.
2) Assignment operatorAn assignment operator is used to assign
value to variable. Assignment always performed right to
left.Syntax:
Variable = valueExample:
Age = 25;
3) Relational Operators:Relational operators are used to perform
to or more values to set relation between them whether
one operand is greater, equal, less or not.Relational operand
has further more type:
1. Greater then operator ( > )2. Less then operator ( <
)3. Greater then or equal to operator ( >=)
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
16
4. Less then or equal to operator ( b ? a : bhere if the
condition a>b will be true then the value of max will be a
otherwise the value of max will beb.
6) Logical Operators:Logical operators are used to test more
then one condition at time. Logical operators are:1. And Operator
&&2. OR Operator ||3. Not Operator !
Logical AND is used when all the given condition must be
satisfied. Logical OR is used when any one ofthe given condition
must be satisfied.
7) Bitwise Operators:Internally the data is stored in bits. C
allows us to operate directly at bit level using bitwise operators.
Thebitwise operators available in C are :
1. Bitwise And &2. Bitwise OR |3. Bitwise Not ~4. Bitwise
Ex-OR ^5. Left shift by number of bits specified >
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
17
8) Special Operators:C provides special operators like sizeof(
), ,, ., &, *. The sizeof( ) operator is a special operator
usedto return size of bytes required to store an entity. For
example val = sizeof(int) will give value 2 to val.This is because
data type int uses 2 bytes in memory space.
Sample Program 3.1: addition of two integer numbers.#include
#include void main(){
int N1, N2, sum;clrscr();printf(Input value to N1:
);scanf(%d,&N1);printf(Input value to N2:
);scanf(%d,&N2);sum = N1 + N2;printf(\n\tSum of %d + %d = %d,
N1,N2,sum);getch();
}
Similarly, we can perform subtraction, multiplication etc.
Sample Program 3.2 multiplication of two numbers.#include
#include void main(){
float a, b, ans;clrscr();printf(Enter two numbers :
);scanf(%f%f,&a,&b);ans = a * b;printf(\n\t Multiplication
of %f * %f = %f, a,b,ans);getch();
}
Sample Program 3.3 : Division of two numbers#include #include
void main(){
int N1, N2, N3;clrscr();printf(Input value to N1:
);scanf(%d,&N1);printf(Input value to N2:
);scanf(%d,&N2);N3 = N1 / N2;printf(\n\t Division of %d / %d =
%d, N1,N2,N3);getch();
}Output :Input value to N1 : 7Input value to N2 : 3Division of
10/3 = 2
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
18
Here, the variable n1 and n2 are type of integer so value of n3
will bi 2 in integer not 2.33333. Itcan not be in float.
A Sample program 3.4// A program to accept number and find its
square.#include #include #includevoid main(){
double n, p;clrscr();printff(Enter any number for which you want
to find square: );scanf(%lf,&n);p=pow(n,2);printf(\n\t Square
of %lf is %lf, n, p);getch();
}
A Sample program 3.5// A program to accept number and find its
square root.#include #include #includevoid main(){
float n, s;clrscr();printff(Enter any number for which you want
to find square root: );scanf(%f,&n);s=sqrt(n);printf(\n\t
Square root of %f is %f, n, s);getch();
}
A sample program 3.6// A program to enter currency in Indian
rupees and convert it into dollars, and pound.#include #include
void main(){
float rs, pnd,dlr;clrscr();printf(Enter Indian Rupees:
);scanf(%f,&rs);dlr=rs/48.5;printf(\n\t Rupees %f equals
dollars %f, rs, dlr);pnd=rs/79;printf(\n\t Rupees %f equals pound
%f, rs, pnd);getch();
}A sample program 3.7// A program to enter Distance in km and
convert it into meter, feet and inches#include #include void
main(){
float d, m, f, i;
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
19
clrscr();printf(Enter Distance in KM: );scanf(%f,
&d);m=d*1000;printf(\n\t Distance in Meter is %f ,
m);f=m*3.33;printf(\n\t Distance in feet is %f,
f);i=f*12;printf(\n\t Distance in inches is %f, i);getch();
}
A sample program: 3.8// A program to convert temperature entered
in Celsius to its equivalent Fahrenheit degree.#include #include
void main(){
float c, f;clrscr();printf(Enter temperature in Celsius:
);scanf(%d, &c);f=9.0/5.0 * c + 32.0;printf(\n\t Temperature in
Fahrenheit is %f, f);getch();
}A sample program 3.9// A program to convert temperature entered
in Fahrenheit degree and convert to its equivalentCelsius
degree.#include #include void main(){
float c=0, f=0;clrscr();printf(Enter temperature in Fahrenheit:
);scanf(%d, &f);c=(5.0/9.0) * (f 32);printf(\n\t Temperature in
Celsius is %f, c);getch();
}
A Sample program 3.10// Program to find area of a circle and
circumference of a circle.#include #include #define PI 3.14void
main(){
float r, a, c;clrscr();printf(Enter Radius of a Circle :
);scanf(%d, &r);a=PI * r * r ;c= 2 * PI * r ;printf(\n\t Area
of a circle is %f, a);printf(\n\t Circumference of a circle is %f,
c);getch();
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
20
}
A Sample program 3.11// A program to enter salary and sale
amount of a salesman and calculate his commission @ 12%of sales
amount and display total salary;#include #include void main(){
float sal,amt,com,total;clrscr();printf(Enter Salary of a
Salesman: );scnaf(%d, &sal);printf(Enter sales amount of a
Salesman: );scnaf(%d, &amt);com = amt * 0.12 ;total = sal +
com;printf(\n\t Salary of a salesman: %f,sal);printf(\n\t
Commission %f, com);printf(\n\t Total salary: %f,
total);getch();
}
A Sample program 3.12//Example of increment - decrement
operator.#include#includevoid main(){
int a=10,b=20,c;c = a++;printf("a = %d b = %d c = %d",a,b,c);- -
b;printf("\nb = %d",b);c = ++a + b--;printf("\n a = %d b = %d c =
%d",a,b,c);getch();
}Output :
a = 11 b = 20 c = 10b = 19a = 12 b = 18 c = 31
A Sample program 3.13//Example of conditional
opertor.#include#includevoid main(){int a=70,b=50,max;clrscr();max
= (a>b) ? a : b;printf("Maximum number is %d",max);getch();}
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
21
A Sample program 3.14//Example of sizeof
operator.#include#includevoid main(){int a=10,b;float c;clrscr();b
= sizeof(a);printf("The value of a is %d",a);printf("\nSize of a is
%d",b);printf("\n Size of float variable is
%d",sizeof(c));getch();}
A Sample program 3.15// program to find ascii value of a
character#include#includevoid main(){char ch;clrscr();ch =
'A';printf("character is %c",ch);printf("\nAscii value is
%d",ch);getch();}/* ASCII = American standard code for information
interchange.
ASCII for A = 65 a = 97*/
Exercise:1. Accept marks of five different subjects from the
user calculate total and average and display it.2. Accept a
character and convert it to uppercase character and vise-versa.3.
Accept principle amount, rate of interest and number of years from
user and find simple interest.4. Accept simple interest, rate of
interest and number of year from the user and find principle
amount.
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
22
CHAPTER 4
INTRODUCTIONS TO CONTROL STATEMENTS
Introduction:So far we learn about data types, basic input and
output function etc. now we will learn about
branching control to some other process. Before we learn about
it. We will look at some programmingconstruct, i.e. sequential
programming, selective programming, and iterative programming.
Sequentialprogramming is that in which program starts from top and
ends with last line without branching control toother process, and
Selective programming is that in which control can be branch to
some other processThis is done using control statements in C
Language. A flow control statement is used to control flow
ofprogram execution depending upon given condition. C language has
two types of control statements.
1. if statement* Simple if statement* if else statement* nested
if* else if ladder
2.. switch statementSimple if Statement:
if statement is a powerful decision making statement and is used
to test one or more than onevalue of condition at a time. It is
also used to control the flow of execution of statements. It is
basically atwo way decision statement and is used in conjunction
with an expression. It is used when we have morethan one option to
select the process and depending on condition we want to read or
execute theprocess.Syntax:
if(condition){
action;}Statement x;
Here condition is given criteria or test condition that should
be a logical expression, and action meansstatements of process to
be performed when given criteria satisfied. The statement block may
be a singlestatement, or a group of statement. If the test
condition is true, the statement block will be executed; oth-erwise
statement block will be skipped and execution will be jump to the
statement-x. Remember, whencondition is true both statement block
and statement-x are executed in sequence.
Sample Program 4.1// Write a program to check whether entered
value is more than 100 or not.#include #include void main(){
int n;clrscr()printf(Enter any number : );scanf(%d,&n);if(n
> 100){
printf(\n\t Value %d is more than 100,n);}
}
in above example if given value is less then 100 then it wouldnt
display any thing on the screen, becausewe could not specified
alternate option for the if statement.
if .. else Statement:To perform an operation in both the case
means if given condition is true or given condition is false,
thefirst test determines whether condition is true or not. if
condition is not true then it executes statement
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
23
block immediately after if statement otherwise it executes
statement block immediately after else state-ment. we could write
the previous program as follows using if .. else
statementSyntax:
if(condition){
action;}else{
action;}
in above example if given value is less then 100 then it
displays message on the screen, because wespecified alternate
option for the if statement means if given condition is true then
it executes statementsafter the if statement, if given condition is
false then also it execute the statements after else
statement.Note:
1. Statements inside the ifs curly braces are called as if block
and statements for elses curlybraces are called as else block.
2. There is no necessity to have an else for if but, each else
must match an if statement elsethere will be a compiler error. The
error will beMisplaced else.
3. If there is only one statement inside if as well as else
block, we can eliminate the curly braces.
Sample Program 4.2/* program to display greater number between
two numbers */#include#includevoid main(){int
a,b;clrscr();printf("Enter two numbers
:");scanf("%d%d",&a,&b);if(a>b)
printf("greater no is a %d", a);else
printf("greater no is b %d", b);
getch();}
Sample Program 4.3/* program to check whether entered number is
even or odd */#include#includevoid main(){int
a;clrscr();printf("Enter a integer number \t
:");scanf("%d",&a);if(a%2 == 0)
printf("%d is Even number.",a);else
printf("%d is Odd number.",a);getch();
}
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
24
Nested if elseIf we write an entire if - else construct within
the body of the if statement or the body of
an else statement. This is called nesting of if-
else.Syntax:if(condition){
//statements1if (condition){
// statements2}else{
// statements3}
}else
// statement 4Here, the inner condition executed only when the
outer condition of if is true. This hierarchy of nestingof if can
be extended in deep with any number of if-else statements.
Sample Program 4.4/* program to find maximum number between
three numbers */#include#includevoid main(){
int a,b,c,max;clrscr();printf("Enter 3 numbers
\t");scanf("%d%d%d",&a,&b,&c);if ( a > b ){
if ( a > c )max=a;
elsemax = c;
}else{
if ( b > c)max=b;
elsemax=c;
}printf("Max = %d ",max);getch();
}
if .. else if statement (else if ladder) :There is another way
of putting ifs together when multipath decision are involved. A
multipath
decision is a chain of ifs in which associated with each else is
an if. It makes following general form of if ..else if
structure:
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
25
Syntax:if(condition){
action;}else if(condition){
action;}else{
action;}
It required when we have more then one conditional statements.
It is applied when we want to applygrades to students or to decide
who is eligible for bonus in company etc.
A Sample program 4.5//program to display grade of the student
based on marks obtained.#include#includevoid main(){float
marks;clrscr();printf("Enter marks
:");scanf("%f",&marks);if(marks>80){printf("Grade is
A.");}else if(marks>70){printf("Grade is B.");}else
if(marks>50){printf("Grade is C.");}else
if(marks>35){printf("Grade is D.");}else{printf("Student is
Fail.");}getch();}
Example:1. Write a program to enter sales amount of a salesman
and salary of a salesman and calculate is
commissionRates of commission are:Sales amount > 15000 rate
of commission is 15%Sales amount between 8000 and 15000 rate of
commission is 12%Sales amount between 5000 and 8000 rate of
commission is 10%Sales amount less then 5000 rate of commission is
8%
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
26
2.3. Write a program to check given year is leap year or not.4.
Write a program to check entered number is positive, negative or
zero.5. Write a program to check whether the person is eligible for
voting or not.
Switch case statement :C language has a built-in multiway
decision statement known as switch statement. It is another
type of control statement used to test limited scope of
condition like to check constant expression like vo-wel or operator
etc. we can not check large range of data in switch statement. It
tests the value of variable(or expression) against a list of case
values and when a match is found, a block of statements
associatedwith that case is executed. The general form of switch
statement is shown below:
The expression is an integer expression or characters,. value-1,
value-2 .. are constants orconstant expression ( evaluable to an
integer constants, and are known as case labels. Each of
thesevalues should be unique within a switch statement, block-1,
block-2 . Are statement blocks. Note thatcase labels are ends with
colon (:)
Syntax:switch(variable or expression){
case constexpr1:action1;break;
case constexpr2:action2;break;
case constexprN:actionN;break;
default:action;
}Sample Program 4.5//display word according to given
number.#include#includevoid main(){int
choice;clrscr();printf("Enter any number between 1 to 5
:");scanf("%d",&choice);switch(choice){case 1:
printf("One");break;
case 2:printf("Two");break;
case 3:printf("Three");break;
case 4:printf("Four");break;
case 5:printf("Five");
default :
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
27
printf("Invalid choice.");}getch();}
A Sample program 4.6// calculator#include#includevoid main(){int
a,b,ans,choice;clrscr();printf("Enter two numbers
:");scanf("%d%d",&a,&b);printf("\n
Calculator");printf("\n1. Addition");printf("\n2.
Subtraction");printf("\n3. Multiply");printf("\n4.
Division");printf("\n\n Enter your choice 1 2 3 4
\t");scanf("%d",&choice);
switch(choice){case 1:
ans = a + b;printf("Addition = %d",ans);break;
case 2:ans = a - b;printf("Subtraction = %d",ans);break;
case 3:ans = a * b;printf("Multiplication = %d",ans);break;
case 4:ans = a / b;printf("Division = %d",ans);break;
default :printf("Invalid choice.");
}getch();
}
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
28
CHAPTER 5
LOOPS IN C
Many times it is necessary to execute several statements
repetitively for certain number oftimes. In such cases, we can use
looping statements of C programming language. The statements
areexecuted until a condition given is satisfied. Depending upon
the position of the condition in the loop,the loop control
structures are classified as the entry-controlled loop and
exit-controlled loop. They arealso called as pre-test and post-test
loops respectively.
If I ask you to print your name 5 times what you do? Naturally,
you will write five printf statementsright?. Because you dont know
about the loop process. A loop is a process of executing statements
with-in the loop till given condition is true. It reduce redundancy
of code of program. C language has basicallythree types of
loops
1. while loop2. do .. while loop3. for loop
while loopThe simplest of all the lopping structure in c is the
while statement. A while loop is generally
known as entry-conditional loop, then the body of the loop is
executed. It is also known as pre tested loopbecause it test the
condition before it enters in loop and executes statements within
the body of the loops.Characteristic of while loop
1. Pre tested loop2. It executes statement within the body of
the loop till given condition is true.3. If condition in the
beginning is false entire loop skips and statement executes
immediately
after the body of the loop.Syntax:
while(condition){
statements;}Here, the condition is evaluated first, if it is
true then loop statements or body of the loop is ex-
ecuted. After this the program control will transfer to
condition again to check whether it is true or false. Iftrue, again
loop body is executed. This process will be continued until the
condition becomes false.When is becomes false, the statements after
the loop are executed.
Sample Program 5.1:#include #include void main(){
int count=1;clrscr();while(count
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
29
Sample program 5.2:// to print odd numbers between 1 to 20 in
descending order.#include#includevoid main(){int
a=20;clrscr();while(a>0){printf("%d\n",a);a = a -
2;}getch();}
Sample Program 5.3:A program to find average of n
numbers.#include #include void main(){
int n, c=1;float s=0, a, no;clrscr();printf(Enter Limit to
N:);scanf(%d, &n);while( c
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
30
Syntax:do{
statements;} while(condition);
Characteristic of do .. while loop1. It is post tested loop2. It
executes the statements within the body of loop till given
condition is false3. if condition in the beginning is false it
executes statements within the body of loop at least
once.
Sample Program 5.4#include #include void main(){
int count;clrscr();do{
printf(\n\tcount = %d,count);count++;
} while(count
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
31
Sample Program 5.6A program to print multiplication table of
given number.// to print multiplication table.#include#includevoid
main(){int a,n;clrscr();printf("\n\tEnter number
:");scanf("%d",&n);a = 1;do{printf("\n\t%d * %d =
%d",n,a,a*n);a++;}while(a =1);getch();}
No. while loop do-while loop1 It checks the condition at the
start of the loop It checks the condition at the end of the loop2
This is of type entry controlled loop structure. This is of type
exit controlled loop structure.
3 The while loop is called as pre- test loop. The do-while loop
is called as post-test loop.
4 It is not guaranteed that how many times the loopbody will get
executed.
The loop body will be executed at least once.
5 Syntax:while(condition){
//loop body}
Syntax:do{
//loop body}while(condition);
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
32
Exercise:1. Generate the following Fibonacci series using while
loop till n number. Accept n from user. 0 1
1 2 3 5 8 13 n2. Write a program to find sum of all even numbers
from n to m. Accept values of variables n and m fromkeyboard.3.
Write a program to print numbers between 1 to n and its square.4.
Write a program to input a number and display its all digit in
reverse order.
For LoopThe for loop is another entry-controlled loop that
provides more concise loop control structure. It
is also an example of pre tested loop. We can use this loop only
when we know the number of iteration.Loop contains initialization,
test condition, and increment together.Syntax:
for(initialization; condition; increment/decrement){
statements;}
The execution of for loop statement takes as follows:1.
Initialization of loop control variables is done first using
assignment operators such as:
i = 1 or count = 0 etc. Remember this part is executed only
once.2. The condition given afterwards is checked then. If this
condition is true, the statements inside theloop are executed. Else
program control will get transferred nest statement after the loop.
The condi-tion can be combination of relational as well as logical
operators such as:
count < 103. When the body of the loop is executed, program
control will get transferred back to forstatement for executing the
third statement that is, increment/decrement. In this part the loop
con-trol variables value is incremented or decremented. Then
program controls the condition again tocheck whether it is true or
not. If true, the loop body executed again. And the process is
continuedagain until the condition evaluates to false.
Characteristic of for loop1 Pre tested loop2 It executes
statement within the body of the loop till given condition is
true.3 If condition in the beginning is false entire loop skips and
statement executes immediately
after the body of the loop.
Sample Program 5.8#include #include void main(){
int count;clrscr();for(count=1; count
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
33
A Sample program 5.9Program to print series of numbers and its
cube.#include#includevoid main(){int i,n;clrscr();printf("Enter
ending value :");scanf("%d",&n);printf("\nNumber
Square\n");for(i=1;i
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
34
}printf("\n");
}getch();
}
A sample program 5.12A program to print x^y and 1/x^y using for
loop#include #include void main(){
long pass=0;int n=0;double
q=0;clrscr()printf(-----------------------------------------------------------);printf(
2 to power n n 2 to power
n);printf(-----------------------------------------------------------);p
= 1;for(n=0; n
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
35
}}
similarly, you can nest for loop and do while loop.
Sample Program 5.13Create following pattern on screen** ** * **
* * *#include #include void main(){
int i=1,j;clrscr();while(i
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
36
scanf(%lf, &number);if(number == 9999)
break;if(number < 0){
printf(\n\t Number is negative);negative++;continue;
}sqroot = sqrt(number);printf(\n\t Number = %lf, sqroot);count
++
}printf(\n\t Number of items done = %d\n, count);printf(\n\t
Negative intes = %d\n, negative);getch();
}Sample Program 5.15A program to print following pattern on
screen12 23 3 34 4 4 45 5 5 5 5
#include #include void main(){
int i,J;clrscr();for(i=1; i
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
37
The output of this program will be:1011
Because, when value of x becomes 12, the condition will be
evaluated to true and break get executed.
The continue statementThe continue statement is used to continue
the next iteration of the loop by skipping the statements
inbetween. That is, when the continue is executed the statements
following is will not be executed,the program control will directly
transfer to next iteration of the loop by increment or decrement.
Gen-erally, the continue is associated with if-statement. General
form of using continue is :
continue;Example
int x;for(x = 10;x < 20; x++){
if(x%4==0)continue;
printf(%d\n);}
The output of this program will be:1011131415171819It has
skipped the numbers which are divisible by 4, for which we have
used the continue state-
ment.
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
38
CHAPTER 6 :-
ARRAYS IN C
An array is a collection of group of variable or data items that
can share common name to accessit. All elements in an array are
stored consecutively. An array can be of any variable type. A
specific valuestored in an array can be displayed by a number
called index or subscript.The ability to use a single name to
represent a collection of item and to refer to an item by
specifying theitem number enables us to develop concise and
efficient program. Suppose you want to store marks offive students
that we can store in different variables but in array we have only
one variable and we canstore marks of five students in an array as
givenUsing variableint m1=36,m2=36, m3=36,m4=36,m5=36;Using
arrayint marks[5]={36,45,54.68,75};Arrays are very helpful in C
programming. You can manipulate number of variables at a time. We
canstore more than on value in a using array. Arrays have two
category given below:
1) Single dimension2) Two dimension
Single dimension array:A list of items can be given one variable
name using only one subscript and such a variable is
called a single-subscripted variable or a single dimension
array. In mathematics, we often deal with va-riables that are
single-subscripted. The subscript can begin with number 0. Like any
other variable arraysmust be declared before they are used. The
general form of the array declaration is given below:Syntax:
DataType ArrayName[size]
Here type means data type of a array style variable, name is the
name of array, and boundary meansnumber of elements within the
array.
Example: Declaration of Array:int marks[5];
Initialization of an array:Like other variable we can initialize
an array. It prevent garbage value in processing. We can in-
itialize an array as follows:Syntax:
variable[index]= value;Example:
marks[0] = 50;marks[1] = 25;. And so on.
orint marks[5]={ 50,25,23,56,70}; // declaration with
initialization
Sample Program 6.1:Program to Input five value to an array and
print it on screen#include #include void main(){
int a[5], i;clrscr();printf(Enter Five values : );for(i=0; i
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
39
printf(\n\t%d,a[i]);getch();
}similarly you can manipulate array using arithmetical operators
and calculate sum of arrays. Exampleshows summation of a
array.Sample Program 6.2:Program to Input five value to an array
and calculate of sum and print it on screen#include #include void
main(){
int a[5], i, sum=0;clrscr();printf(Enter Five values :
);for(i=0; i
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
40
scanf("%s",&name);printf("name = %s",name);for(i=0;i
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
41
clrscr();
printf(Enter values to array\n);for(i=0; i sv)high=mid -1;
else if(n[mid]==sv){
f=1;break;
}}
if(f == 1)printf(\n\t Search value found in array);
elseprintf(\n\t Search value found in array);
getch();}above program search value within the array using
binary search.
Sorting of an arraySorting is a process in which we arrange an
array either in ascending order or in descending or-
der, C Language generally provides two types of searching
methodsLinear sorting or sequential sort methodBubble sort
method.Linear sort
In l Liner sort we assume that the first element of the array is
the highest value we compares itwith the next element of array if
the first element value is larger then the second, exchange it, and
repeatprevious steps by comparing value to next element till all
elements in array are sorted.Sample Program 6.7Program to sort an
array using liner sort#include #include void main(){
int n[5], i, j, t=0;clrscr();
printf(Enter Values to an array:\n);for(i=0; i
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
42
for(i=0; i
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
43
[0][0] [0][1] [0][2] [0][3]
[1][0] [1][1] [1][2] [1][3]
[2][0] [2][1] [2][2] [2][3]
[3][0] [3][1] [3][2] [3][3]
[4][0] [4][1] [4][2] [4][3]
Bubble sort methodIn bubble sort method the smallest value comes
up like a bubble. In this method we starts with
the last element assuming that value of the last elements is the
smallest one then it compare with theprevious element if ii really
small then previous element exchange them, and repeat all step till
entire ar-ray is sorted.Sample Program 6.9//Program to sort an
array using bubble sort#include #include void main(){
int n[5], i, j, t=0;clrscr();printf(Enter Values to an
array:\n);for(i=0; i
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
44
there respective row and column number as,table[2][3] = 10;
table[1][1] = -52;A two dimension array contains number of rows
and number of columns, to read or to write a two dimen-sion we need
nested loop. Possible operation can be performed on double
dimension is, reading and writ-ing an array, transpose of matrix,
addition of matrix and multiplication of a matrix.Two dimensional
arrays can also be initialized as.
int table[2][2] = {8, 5, 9, 6};It will initialize the array as
shown below,
8 5
9 6Following declaration and initialization is more
understandable than previous one.
int table[][] = {{8, 5}, {9, 6}};orint table[][] = {
{8, 5},{9, 6}
};
Sample Program 6.10// Program to read and print values of two
dimension array.#include #include void main(){
int n[3][3], i, j;clrscr();printf(Enter 9 numbers :
\n);for(i=0;i
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
45
CHAPTER 7
STRINGS IN C LANGUAGE
The string is sequence of characters that is treated as a single
data item. In general, thecharacter array is called as string. Any
group of characters defined between double quotationmarks is a
string constant. Such as
The C Programming Language.Declaring a string
C does not support string as the data type. However is allows us
to represent strings ascharacter arrays. It can be declared as
char string_name[size];Here, string_name is the valid variable
name given to the string and
size determines the number of characters in the string. For
example:
char city[10];char name[30];
Here, city is the character array or a string can be stored with
10characters. The name will store 30 characters as
well.Initializing a string
Like numerical arrays the strings can also be initialized when
they are declared which is re-ferred as compile time
initialization. It can be done in following three forms:
char city[6] = Nashik;char city[ ] = Nashik;char city[6] = {N,
a, s, h, i', k };
For initializing the string at run-time, we use scanf function
with %s format specifier such as:char str[10];scanf(%s, str);
This statement will initialize the string str by taking the
input from the keyboard. This will read the cha-racter sequence
until occurrence of first separator such as space character, tab or
enter and store it intostr. We can also use the following function
to input the string including spaces.
char str[10];gets(str);
The gets() function defined in stdio.h file reads the string
from the keyboard until the en-ter is not pressed.For printing the
string, we can use the printf function in the similar format such
as:
printf(%s, str);Note:A string consists of characters which is
known as string. String terminates by a terminator charactermeans a
NULL character that is \0. When we input a string from key board
and when we stopped input-ting string C compiler automatically adds
a special at the end of string which is known as NULL ( \0
)character.
There are various types of functions which can be helpful to
manipulate string, to use string function wemust include string.h
header file, string functions are given below:
1. strlen( ): it is used to find the length of a string;eg. Len
= strlen(India);
This will give the length of a given string India. It will stor
5 as length of a sting in variable Len.
Sample Program 7.1//A program to find length of a given
string.#include #include #include void main()
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
46
{char s[80];int ln;printf(Enter any string
:);gets(s);ln=strlen(s);printf(\n\t Length of %s is
%d,s,ln);getch();
}
2. strcpy( ): it is used to copy a string to another. Means we
can copy source string to targetstring
eg. char s1[10]=India,s2[10];strcpy(s2,s1);
Sample Program 7.2//A program to copy a given string to another
strings#include #include #include void main(){
char s1[80],s2[80];printf(Enter any
string:);gets(s1);strcpy(s2,s1);printf(\n\t Copy of %s is
%s,s1,s2);getch();
}3. strcmp( ): This function is used to compare two strings and
accordingly returns the val-ue. That is, it returns the numerical
difference between the strings. This function is case-sensitive
func-tion. It takes the following general form:
strcmp(string1, string2);Here, string1 and string2 may be string
variables or strings constants. The function will compare
thestrings and returns the value. If this value is 0, implies that
both the strings are equal. If it is positive,implies that string1
is greater and if negative, implies that string2 is greater. For
example:
strcmp(city1, city2);strcmp(Pune, city1); etc.
Sample Program 7.3//A program to compare two string and find the
largest string among them.#include #include #include void
main(){
char s1[80],s2[80];printf(Enter First string
:);gets(s1);printf(Enter Second string :);gets(s2);if(strcmp(s1,s2)
== 0)
printf(\n\t %s is equals to %s,s1,s2);else if(strcmp(s1,s2) >
0)
printf(\n\t %s is larger than %s,s1,s2);else if(strcmp(s1,s2)
< 0)
printf(\n\t %s is larger than %s,s2,s1);getch();
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
47
}4. strrev( ): it is used to reversed a string.
eg. char s1[10]=India;strrev(s1);
above function code will reverse string India to aidnI
Sample Program 7.4//A program to reverse a string a given
string#include #include #include void main(){
char s[80];clrscr();printf(Enter any string
:);gets(s);printf(\n\t Original String is %s,
s);strrev(s);printf(\n\t Its reverse string is %s ,s);getch();
}5. strupr( ): it converts a lower case string to its equivalent
upper case string.
eg. char s1[10]=india;strupr(s1);
above function will prints upper case string. As INDIA on
screen
Sample Program 7.5//A program to convert a lower case string to
its equivalent upper case string#include #include #include void
main(){
char s[80];int ln=0;printf(Enter a string
below\n);gets(s);printf(\n\t Entered lower case string is
%s,s);strupr(s);printf(\n\t Converted String is %s ,s);getch();
}6. strlwr( ): it converts upper case string to its equivalent
lower case string.
eg. char s1[10]=BARODA;strlwr(s1);
above command will convert upper case string BARODA to
baro-da
Sample Program 7.6//A program to convert a upper case string to
its equivalent lower case string#include #include #include void
main(){
char s[80];int ln=0;
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
48
printf(Enter any string :);gets(s);printf(\n\t Entered lower
case string is %s,s);strlwr(s);printf(\n\t Converted String is %s
,s);getch();
}7. strcat( ): This function joins two strings together. That
is, this function is used to
concatenate the strings. It takes the following general
form:strcat(string1, string2);
here, string1 and string2 are character arrays. When this
function is executed, content of string2 isattached at the end of
string1. Content of string2 remains unchanged.
Sample Program 7.7// A program to append a string to another
string#include #include #include void main(){
char s1[80], s2[80];clrscr();printf(Enter first string
:);gets(s1);printf(Enter second string :
);gets(s2);strcat(s1,s2);printf(\n\t Converted String is %s
,s);getch();
}Above program will append second string at the end of the first
string. similarly you can developed logicfor all the function
Additional programsSample Program ad1:// Reading a line of text
from terminal#include #include void main(){
char line[81], character;int c=0;clrscr();printf(Enter text,
press at end\n);do{
character = getchar();line[c] = character;c++;
} while(character != \n);
c = c-1;line[c]=\0;printf(\n\t%s, line);getch();
}
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
49
Sample Program ad2:// Sort a list of string in alphabetical
order#include #include void main(){
char string[5][20], dummy[20];int i=0, j=0;clrscr();printf(Enter
the name of five items \n);while(i < 5)
scanf(%s,string[i++]);for(i=1; i 0){
strcpy(dummy,string[j-1]);strcpy(string(string[j-1],string[j]);strcpy(string[j],dummy);
}}
}printf(\n\t Alphabetical list of items\n);for(i=0; i
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
50
CHAPTER - 8
FUNCTIONS IN C LANGUAGE
A function is self-contained block of statements that performs
particular task. C functionscan be classified into two types:
1) Library functions (Built-in Functions)2) User-defined
functionsThe library functions are the functions which are already
defined in Cs functions library i.e.
header files. For example, the functions scanf() and printf()
are the library functions defined in filestdio.h same as functions
sqrt() is defined in math.h and getch() is defined in conio.h. User
definedfunction is the function defined by the programmer who has
written the program. The task to per-form is decided by the user.
For example, the main() function is an user-defined function. We
decidewhat is to be written in this function.
Need of user-defined function1. The functional program
facilitates top-down modular programming approach.2. The length of
source program can be reduced by using functions at appropriate
places.3. It is easy to locate and isolate a faulty function for
further investigations.4. A function may be used by many other
programs. This means that a C programmer can build on whatothers
have already done. That is we can reuse the functions already
defined in some program files.user-defined function
In order to make use of user defined functions, we need to
establish three elements that arerelated to functions.
1. Function definition2. Function call3. Function
declaration
1. Declaration of a functionSyntax:
Return-type name_of_function(list of arguments);Example:
int length(char ch);float factorial(int);
A function has four type of declaration according to it type.
There are four type of function declarationNo return value no
argument; means a function will not return any value or it will not
accepting argumentsform user.Eg. void sumNo(void);
No return value with argument, means a function will not return
value but it will accept one or more thenone arguments for
process.Eg. void sumNo(int, int)Above function will not return any
value but it will accept two integer type arguments.
With return value with no argument, means a function will return
a value but never accept anyargument from userEg. int
sumNo(void);
With return value with arguments, means a function will return a
value and it also accepts one or morethen one arguments for
process.Eg. int sumNo(int, int);A declaration of a function is
known as a prototype of a function.
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
51
2. Function definitionThe function definition is an independent
program module that is specially written to implement
therequirements of the function. So it is also called as function
implementation.Syntax:
Return_type function_name(parameters list){
local variables declaration;statements;- - - - - -;- - - - -
-;return statement;
}It includes three parts:
1. Function typeIt specifies type of the value that the function
is expected to return to the program calling thefunction. It is
also called as return type. If function is not returning any values
we have tospecify it as void.
2. Function nameIt is any valid C identifier name and therefore
must follow the rules for creation of variable namesin C.
3. Parameters listIt declares variables that will receive the
data sent by the calling program. They serve asinput data to the
function to carry out specific task. Since, they represent the
actual input valuesthey are referred as formal parameters or formal
arguments.
Example:float mul(float x, float y){
float result; /* local variable */result = x * y; /* find the
result */return(result); /* return the result */
}Return values
A function may or may not send back any value to the calling
function. If it does, it is done byreturn statement. The return
statement also sends the program control back to the
callingfunction. It is possible to pass a calling function any
number of values but called function canonly return one value per
call.
3. Function callA function can be called by simply using
function name followed by a list of actual parameters (or
ar-guments) if any, enclosed in parentheses.Example:
main(){
float m;m = mul(5.2, 3.71); /* function call
*/printf(\n%d,m);
}When compiler encounters the function call, it transfers
program control to the function
mul() by passing values 5.2 and 3.71 (actual parameters) to the
formal parameters on the functionmul(). The mul() will performs
operations on these values and then returns the result. It will be
storedin variable m.
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
52
Sample Program 8.1// A function with no return no
arguments#include #include void main(){
void sumNo(void); // Declaration of a function / Prototype of a
functionclrscr();sumNo(); // Calling a function.getch();
}
void sumNo(void) // function Definition{
int n1, n2, n3;
printf(Enter value to N1: );scanf(%d,&n1);
printf(Enter value to N2: );scanf(%d,&n2);
n3=n1+n2;
printf(\n\t Sum is %d, n3);}Sample Program 8.2:// A function
with no return with arguments#include #include void main(){
int n1, n2;void sumNo(int, int); // Declaration of a function /
Prototype of a functionclrscr();
printf(Enter value to N1: );scanf(%d,&n1);
printf(Enter value to N2: );scanf(%d,&n2);sumNo(n1,n2); //
Calling a function.getch();
}void sumNo(int x, int y) // Body of a function{
int z;z=x+y;printf(\n\t Sum is %d, z);
}Sample Program 8.3// A function with return type and no
arguments.
#include #include void main(){
int n3;
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
53
int sumNo(void); // Declaration of a function / Prototype of a
functionclrscr();n3=sumNo(); // Calling a function.printf(\n\t Sum
is %d, n3);getch();
}int sumNo(void) // Body of a function{
int n1,n2;printf(Enter value to N1: );scanf(%d,&n1);
printf(Enter value to N2: );scanf(%d,&n2);return
(n1+n2);
}Sample Program 8.4// A function with return with arguments
#include #include void main(){
int n1,n2,n3;int sumNo(int,int); // Declaration of a function /
Prototype of a functionclrscr();
printf(Enter value to N1: );scanf(%d,&n1);
printf(Enter value to N2: );scanf(%d,&n2);
n3=sumNo(n1,n2); // Calling a function.
printf(\n\t Sum is %d, n3);
getch();}
int sumNo(int x,int y) // Body of a function{
int z;return (z);
}
Similarly you can developed function for subtraction,
multiplication, and division of two numbers. Forabove mentioned
type.A function may called with reference to value is known as
called by value, where as when a function iscalled with reference
to address of a variable is known as called by reference.In called
by value type of function calling we send a copy of a variable to
the called function. Where as incalled by reference we send the
address of variable.
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
54
Recursive functionWhen a function calls itself within the same
function is called as recursion of a function. A recur-
sive function is more efficient then a normal function. It
provide faster process.
Sample Program 8.5/*A Program using recursive functionFind a
factorial number of a given number.*/#include #include void
main(){
long n=0,f=0;long factorial(long); // Declaration of a function
/ Prototype of a functionclrscr();printf(Enter value to N:
);scanf(%ld,&n);f=factorial(n); // Calling a
function.printf(\n\t %ld! = %ld, n,f);
getch();}long factorial(long n) // Body of a function{
long f=1;if(n==1)
return 1;else
f=n * factorial(n-1);
return f ;}
Exercise of a functionWrite a function to find square root of a
given number.Write a function to find square of a given
number.write a function to convert temperature entered in Celsius
degree to its equivalent Fahrenheit.Write a function to print first
n fibbonacy number.Write a function to find circumference and area
of a circle with given radiusWrite a function to find distance
entered in km to it equivalent meter, feet and inches.Write a
function to convert Indian currency to its equivalent dollar, and
pound and vise versa.Write a function to swap a value of
variables.Write a function to calculate number of words,
characters, digits in a given string.Write a function to remove
extra spaces from given string.Write a function to reverse a
string.Write a function to check whether entered character is vowel
or not.Write a function to check whether entered year is leap year
of not.Write a function to check whether a entered number is odd of
even.
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
55
Additional ProgramsSample program ad1Function to find compound
interest (no return no argument)#include #include void main(){
clrscr() ;void printline();void value();void
printline();printline();value();printline();getch();
}
void printline(){
int i;for(I=1;I
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
56
printline();print( %12.2f,sum);getch();
}void printline(){
int i;for(I=1;I
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
57
CHAPTER 9
POINTERS IN C
A pointer is a variable capable of holding address of another
variable. A pointer provides fasterprocess as well as variables
that are not accessible to the function that also can be accessed
through thefunction. Pointer variable occupies less memory means it
occupy only two bytes in memory. It also usedto developed system
programs like virus, anti-virus, operating system etc. A pointer is
denoted by * sign.
We can declare a pointer variable same as normal variable but we
must put * sign before a varia-ble to indicate pointer
variable.Syntax:
dataType *name_of_pointervariable;Example:
int *p;char *ptr;
The address can be collected in a variable, by ,p = &i;here,
p is not an ordinary variable. It is a pointer variable that
contains the address of other integer varia-ble ( i ).
Sample Program of pointer variable 9.1// Write a program to
inter change value of two variable.
#include #include void main(){
int n1, n2, t, *p1, *p2;clrscr();
p1=&n1; //Storing address of n1 to p1;p2=&n2; //Storing
address of n2 to p2;
printf(Enter value to N1: );scanf(%d, &n1);
printf(Enter value to N2: );scanf(%d, &n2);
printf(\n\t Before Swapping value of n1 and n1 );pritnf\n\t N1 =
%d,n1);pritnf\n\t N2 = %d,n2);
t=*p1;*p1=*p2;*p2=t;
printf(\n\t After Swapping value of n1 and n1 );pritnf\n\t N1 =
%d,n1);pritnf\n\t N2 = %d,n2);getch();
}Generally we can use a pointer for a different purpose for e.g.
pointing to an array, a array of a pointersetc.
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
58
Pointer to an array:Pointer to an array is that a pointer
variable points to an array. A pointer variable holds address
of
the first elements of an array which is known as base address.
Then after we can manipulate an arrayusing pointer.Syntax:
int n[5]={0}, *p1p1=n;
Here p1 holds the address of first element of an array. This
address of first element is known as baseaddress. A sample program
shows use of pointers with an array.
Sample Program 9.2// Program to accept five value to an array
and print it with the help of array.#include #include void
main(){
int n[5], i, *p1;clrscr();
p1=n;
printf(Enter five values to an array\n);for(i=0; i
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
59
scanf(%d,n2);
printf(\n\t Output of variables using array of
pointer\n);for(i=0; i
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
60
CHAPTER 10
STRUCTURE AND UNION
A structure is a collection of different types of variables
which are known as member of a struc-ture. An advantage of the
structure is that we can store different types of values. Generally
a normal arraycan hold more than one variable of similar type,
where a structure can hold more than one variable of dif-ferent
size. A structure can be defined with struct clause. A structure
member can occupy individualmemory location.Declaring a
StructureSyntax:
struct StructureName{
member1;member2;memberN;
};Example:
struct book{
char name[20] ;float price;int pages;
};This statement defines a new data type called struct book.
Each variable of this data type will consist ofa character variable
name, a float variable called price and integer variable called
pages. Once the newstructure data type has been defined one or more
variables can be declared to be of that type. For exam-ple the
variables b1, b2, b3 can be declared to be of the type struct book,
as,
struct book b1,b2,b3;
This statement sets aside space in memory. It makes available
space to hold all the elements in the struc-ture.We can combine the
declaration of the structure type and the structure variables in
one statement.For example,
struct book{
char name[20] ;float price;int pages;
};struct book b1,b2,b3;
is same asstruct book
{char name[20] ;float price;int pages;
} b1,b2,b3;Or evenstruct
{char name[20] ;float price;
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
61
int pages;}b1,b2,b3;
Like variables and array, structure variables can also be
initialized where they are declared. The formatused is quite
similar to that used to initiate arrays.struct book
{char name[20] ;float price;int pages;
};struct book b1 = { Basic, 130.00,550};struct book b2 = {
Physics, 150.00,300};
Accessing a structure ElementsIn arrays we can access individual
elements of an array using a subscript/index. Structures use a
differentscheme. They use a dot (.) operator. So to refer to pages
of the structure defined above example, wehave to use,b1.pages
similarly, to refer to price we would use,b1.price
Note that before the dot there must always be a structure
variable and after the dot there must always bea structure
element.
Sample Structure Program 10.1/* Declare a structure of a student
which has following member rno, name, address, city, acceptdata
from user and print it. */#include #include struct student{
int rno;char name[10],address[15],city[20];
};void main(){
struct student s1;clrscr( );
printf(Enter Rollno: );scanf(%d,&s1.rollno);flushall( );
printf(Enter Name: );gets(s1.name);flushall();
printf(Enter Address: );gets(s1.address);flushall( );
printf(Enter City: );gets(s1.city);flushall( );
printf(\n\t Rollno: %d,s1.rollno);
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
62
printf(\n\t Name: %s,s1.name);printf(\n\t Address:
%s,s1.address);printf(\n\t City: %s,s1.city);getch();
}similarly we can also define a pointer to a structure, a
pointer to a structure is quite efficient and occupiesonly two byte
in memory, where as a structure occupies memory as the size of
structure.Syntax:
struct student *s1;to access member of a structure we have to
use -> (arrow) operator like s1->rollno and so on.We can also
declare a structure array variable to store more then one
value.syntax:
sturct student s1[5];
above notation can store details of five student.Sample
structure program 10.2/* Declare a structure of a student which has
following member rno, name, address, city, acceptdata from user and
print it. Use structure array. */#include #include struct
student{
int rno;char name[10],address[15],city[20];
};void main(){
int i;struct student s[3];clrscr();for(i=1; i
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
63
}
similarly we can assign a pointer to structure object
variable
Sample structure program 10.3/* Declare a structure of a student
which has following member rno, name, address, city, acceptdata
from user and print it. Use pointer variable */#include #include
struct student{
int rno;char name[10],address[15],city[20];
};void main(){
int I;struct student s1,*s;clrscr();
s=&s1;printf(Enter Rollno:
);scanf(%d,&s->rollno);flushall();
printf(Enter Name: );gets(s->name);flushall();
printf(Enter Address:
);gets(s->address);flushall();printf(Enter City:
);gets(s->city);flushall();
printf(\n\t Rollno: %d,s->rollno);printf(\n\t Name:
%s,s->name);printf(\n\t Address: %s,s->address);printf(\n\t
City: %s,s->city);
getch();}similarly we can assign a pointer to structure object
variable which an array type.
Sample Structure Program 10.4/* Declare a structure of a student
which has following member rno, name, address, city, acceptdata
from user and print it. Use structure array and pointer variable
*/#include #include struct student{
int rno;char name[10],address[15],city[20];
};void main(){
int i;
-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph:
32902903rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race
course Ph: 3249499
64
struct student s1[2],*s;clrscr();
s=&s1;
for(i=0;irollno);flushall();
printf(Enter Name: );gets(s->name);flushall();
printf(Enter Address: );gets(s->address);flushall();
printf(Enter City: );gets(s->city);flushall();
}
s=&s1[0];for(i=0;irollno);printf(\n\t Name:
%s,s->name);printf(\n\t Address: %s,s->address);printf(\n\t
City: %s,s->city);
}getch();
}
Union:Union is quite similar to a structure but the different is
that a structure member can store an indi-
vidual memory location, where a union member can share