0% found this document useful (0 votes)
12 views

C Language

The document provides an introduction to the C programming language, including its history and development. It describes C's ability to write concise programs and its portability. It also outlines some fundamental aspects of C like tokens, variables, data types, constants, and the main function.

Uploaded by

Pawan G
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

C Language

The document provides an introduction to the C programming language, including its history and development. It describes C's ability to write concise programs and its portability. It also outlines some fundamental aspects of C like tokens, variables, data types, constants, and the main function.

Uploaded by

Pawan G
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

C Language Introduction to C Language

INTRODUCTION TO ‘C’ LANGUAGE

This book offers instruction in computer programming using a popular, structured


programming language called C. We will learn how programs can be written in C. In addition,
we will see how problems those are initially described in very general terms can be analyzed,
outlined and finally transformed into well-organized C programs. These concepts are
demonstrated in detail by the many sample problems that are included in the text.
C is characterized b the ability to write very concise source programs, due in part to
the large number of operators included within the language. It has a relatively small
instruction set, though actual implementations includes extensive library functions which
enhance the basic instructions. Furthermore, the language encourage the user to write their
own library functions.
An important characteristics of C is that its programs are highly portable, even more so
than with other high level languages. The reason for this is that C relegates most computer-
dependent features to its library functions. Thus every version of C is accompanied by its own
set of library functions, which are written for the particular characteristics of the host
computer.

Page 1 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Historical Development of C Language

HISTORICAL DEVELOPMENT OF C LANGUAGE

 Developed between 1969 and 1973 along with Unix


 Due mostly to Dennis Ritchie
 Designed for systems programming
o Operating systems
o Utility programs
o Compilers
o Filters
 Evolved from B, which evolved from “BCPL”
o Designed by Martin Richards (Cambridge) in 1967
o Typeless
o Everything an n-bit integer (a machine word)
o Pointers (addresses) and integers identical
o Memory is an undifferentiated array of words
o Natural model for word-addressed machines
o Local variables depend on frame-pointer-relative addressing: dynamically-sized
automatic objects not permitted
o Strings awkward
o Routines expand and pack bytes to/from word arrays

Page 2 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Fundamental of C Language

Fundamental of C Language
 A Programming language (PL) is a set of instructions used to communicate with the
computer
 The set of instruction written in a PL is known as “program”.
 All PL language can be divided into three categories.
Programming Languages
 Problem Oriented or High Level Languages.
 Machine Oriented or Low Level Languages.
 Middle Level Language.
Language Translator
 These are special programs, which accepts the user program and convert to corresponding
machine language instructions
 There are two types of translators
o Compilers
o Interpreters
Character set
Communicating with a computer involves speaking the language the computer
understands.
Steps in learning English language

Alphabets (a-z & A-Z)


Numbers (0-9)
Symbols (+,/%#!=.* etc.) Words Sentence Para Story

Steps in learning C

Alphabets (a-z & A-Z)


Numbers (0-9) Token Statement Program Software
Symbols (+,/%#!=.* etc.)
Token
The smallest unit of the program is known as Token. The tokens are classified is given
next.

Keyword
These words are predefined in C Compilers. Their meaning cannot be modified by the
programmers. There total 32 Keyword in C Language.

Page 3 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Fundamental of C Language

Variable
Variables are temporary memory storage, in which we store the data for temporary
operations during the execution of the program. Like for adding of two numbers, these basic
values are stored in the variables and their resultant also stored in another variables.
When we declare any variable it reserves some memory location in System Memory
Registers.
Method of Declaration
DataType identifier;
Ex. int x;
Assignment
This process always flow from Right to Left.
X=6; z=x+y; Correct
6=x; x+y=z; Wrong
Initialization
The variables can be assign a value with declaration.
int a=4; double c=3e+8; char ch=‘a’;
Constant
These constant are used to maintain a value fixed during the execution of the program.
Like  has value 3.14 which required for many scientific calculation.

const float pi=3.14; // this value can’t be modified by new value.

Identifiers
Identifiers are names given to various program elements, such as variables, functions
and arrays

Rules for declare identifier


 Starts with Alphabets Or ‘_’
 Contains No space
 Contains No any symbol
 Only ‘_’ can be anywhere (Start, mid or end)
 Not a keyword
 Case Sensitive (Sum, sum, SUm,SuM, SUM,sUM are different)

Page 4 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Turbo C++ IDE

Introduction to IDE
This stands for Integrated Development Environment. This is a fine environment for
development of console application that can be easily written/edited/update and
compile/execute (test). While working with IDEs programmer feel very friendly environment
for their development.
How to Execute TC.EXE
Find the TC.EXE file in your PC along with it’s libraries. For example:
C:\Tc\Tc.EXE or C:\Tc\Bin\TC.EXE
This depends on installer where it has install Turbo C++ IDE.
Configuration
Set the “library” and “include” Directories from Option menu.
Shortcuts
To do this Do this
Open/New Source Code........................................................................................................................F3
Save active source Code.......................................................................................................................F2
Full screen the console window............................................................................................. Alt+Enter
Full screen the editing window........................................................................................................... F5
Copy the Selected Text...............................................................................................................Ctrl+Ins
Paste the Copied text................................................................................................................ Shift+Ins
Cut the Selected Text...............................................................................................................Shift+Del
Undo....................................................................................................................................Alt+Backspace
Redo........................................................................................................................ Shift+ Alt+Backspace
Compile............................................................................................................................................ Alt+F9
Execute (Run)................................................................................................................................ Ctrl+F9
User Screen......................................................................................................................................Alt+F5
Trace into................................................................................................................................................F7
Step Over.................................................................................................................................................F8
Make EXE................................................................................................................................................. F9
Select menubar.........................................................................................................................Alt or F10

Main function
Main function is the function that execute very first of all the instructions. This is semi
user defined function. Because it’s name is pre-defined and all the statement inside this
function is defined by the programmer.
Turbo C++ IDE is required that “Main” function should return a value. That’s why main
function returns an “int” type value after the execution of all the statement. So main function
can be defined like:
main() or int main() and void main()
{ { {

------------------------------------------statements sets--------------------------------------------

reutrun 0; reutrun 0;
} } }

Page 5 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Basic Program Structure in C Language

A Sample Program structure


Type this program into turbo C++ IDE, then save and execute.

/* This is an application for adding two numbers input by the user. */ // 1


#include<stdio.h> // 2
#incldue<conio.h> // 3
void main()
{
int x,y,z; // 4
clrscr(); // 5
printf(“Enter 1st number : ”); // 6
scanf(“%d”,&x); // 7
printf(“Enter 2nd number : ”);
scanf(“%d”,&y);
z=x+y; // 8
printf(“Sum of these number= %d”,z); // 9
// printf(“%d + %d = %d”,x,y,z);
getch(); // 10
}

Description
1. Remark: used to define the description about the program.
2. Preprocessor directive: include information about standard library functions like printf() &
scanf().
3. Preprocessor directive: include information about standard library functions like clrscr() &
getch().
4. Declaration of the variables.
5. clrscr(); Clear the Screen for new output.
6. printf(); send string output to the standard output device “Monitor”.
7. scanf(); reads a string input from standard input device “Keyboard” and assign to the
variables.
8. Assign the result of the operation to the resultant variable “z”.
9. printf(); sends string output with variable information.
10. getch(); waits for the user to press any key then terminate from the program.

Page 6 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Data Types in C Language

DATA TYPE
C Supports several different types of data, each of which may be represented
differently within the computers memory.
Basic data types are listed below:

Page 7 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Data Types in C Language

More about Data Type


 Data type determines how much storage space is allocated to variables.
 Data type determines the permissible operations on variables.
 The variables should be declared by specifying the data type.
 There is a family of integer data types and floating-point data types.
 Characters are stored internally as integers
 Characters are interpreted according to the character set.
 The most commonly used character set is ASCII.
 In the ASCII character set, A is represented by the number 65.

Date Range
Keyword Variable Type Range .

char Character (or string) -128 to 127


int Integer -32,768 to 32,767
short Short integer -32,768 to 32,767
short int Short integer -32,768 to 32,767
long Long integer -2,147,483,648 to 2,147,483,647
unsigned char Unsigned character 0 to 255
unsigned int Unsigned integer 0 to 65,535
unsigned short Unsigned short integer 0 to 65,535
unsigned long Unsigned long integer 0 to 4,294,967,295
float Single-precision +/-3.4E+38 to +/-3.4E+38
floating-point
(accurate to 7 digits)
double Double-precision +/-1.7E+308 to +/-1.7E+308
floating-point
(accurate to 15 digits)

Page 8 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Operators in C Language

Operators

 Assignment Operator
 Arithmetic Operators
 Increment decrement Operator
 Comma Operator
 Relational Operators
 Logic Operators
 Ternary operator
 Short Calculation

Assignment Operator #include<stdio.h>


Assigning the value of an expression to a variable.
main( )
var = expression. {
int a = 1,b =2,c =3,d=4;

You can use other formats such as var += expression, a += b * c + d;


Which means var = var + expression printf("\n a = %d",a);
}
 The assignment operators have the lowest priority. Output
 The assignment operators are evaluated from right to left. a=11
 The assignment operators include: =, +=, -=, *=, /=, %=.

Operator Description Example


* Multiplication Result = Operand1 * Operand2;
/ Division Result = Operand1 / Operand2;
% Modulus (remainder) Remainder = Operand1 % Operand2;
+ Addition Result = Operand1 + Operand2;
- Subtraction Result = Operand1 -Operand2;

Increment operator
Prefix: the value is incremented/decremented first and then applied.
Postfix: the value is applied and the value is incremented/decremented.

#include<stdio.h> Output
i = 4, j = 3, k = 6
main( )
{
int i = 3,j = 4,k;
k = i++ + --j;
printf("i = %d, j = %d, k = %d",i,j,k);
}

Relational operators
 Relational operators are used in Boolean conditions or expressions.
 Boolean conditions or expressions return either true or false.
 The relational operator returns zero values or nonzero values.

Page 9 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Operators in C Language

 The zero value is taken as false while the nonzero value is taken as true.
 The relational operators are as follows: <, <=, >, >=, ==, !=.
 The priority of the first four operators is higher than that of the later two operators

Logical operator
You can combine multiple relations or logical operations by logical operation.
The logical operators are negation (!), logical AND (&&), and logical OR (||).

Short circuiting
When evaluating logical expressions, C uses the technique of short circuiting.
C1 && C2 && C3 && C4
So if C1 is false C2, C3, and C4 are not evaluated.
C1 || C2 || C3 || C4
So if C1 is true C2, C3, and C4 are not evaluated

Ternary operator
Ternary operators return values based on the outcomes #include<stdio.h>
of relational expressions.
main(){
The general form of the ternary operator is: int i= 2;
=(expr 1) ? expr2 : expr3 int j= 3;
If expr1 returns true then the value of expr2 is int k = ( i>j ) ? i : j;
returned as a result; otherwise the value of expr3 is printf("\n k = %d",k);
returned. }
Output Description
If i > j then k will get the value
Comma operator can return a value equal to i, otherwise it will get
the value equal to j.
Comma operator returns the value of the rightmost operand.
#include<stdio.h>

main(){
int i, j;

printf("%d",(i = 0, j = 10));

}
Output
10

Page 10 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Control Structure in C Language

Control Structures
Control structures: sequential, selection, iteration and encapsulation.
A sequential structure is one in which instructions are executed in sequence. For
example:
# include<stdio.h>
main()
{
int i=0, j =1;
printf("A");
i = i + 1;
printf("B");
j = j + 1;
printf("C");
}

Selection structure
The sequence of the instruction is determined by the condition.
The statements in this category are if and switch
Decision Making with If- Else-If
If statement is used to control that any statement(s) is to be execute or not.
For Example:
# include<stdio.h>
main()
{
“Not” is depends on
int x,y;
printf("Enter Any number : "); Logical text “x!=y”. If
scanf(“%d”,&x); this is true so “not” will
printf("Enter other number : "); print other wise it will
scanf(“%d”,&y); skip to “not”.
printf(“These numbers are ”);
if(x!=y)
{
printf(“not ”);
}
printf(“Equal”);
}
Using If-Else
# include<stdio.h>
main()
{
int x,y;
printf("Enter Any number : ");
scanf(“%d”,&x);
printf("Enter other number : ");
scanf(“%d”,&y);
if(x!=y){
printf(“These numbers are not Equal”);
}
else{
printf(“These numbers are Equal”);
}

Page 11 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Control Structure in C Language

printf(“OK”);
}

The switch statement


To take one of a number of possible actions. switch is preferred over multiple if...else
statements.
The general form of a switch statement is
switch(switch_expr)
{
case constant expr1 : S1;
S2;
break;
case constant expr1 : S3;
S4;
break;
.....
default : S5;
S6;
break;
}
The clause 'default' is optional
For example:
/* This is program to Print Input number is Word.*/ This program illustrate that if we’ve
#include<stdio.h> many values and we’ve to select one of
#include<conio.h> them, we use multiple if-else-if statement.
void main() Note: If we’ve only single statement
{ depends on if-else then it suitable
int x; for this kind of application but
clrscr(); when we’ve a lot of statement
printf(“Enter the number 0-9 : ”); depends on if-else block then we’ve
scanf(“%d”,&x); to use curly bracket ‘{‘ ‘}’ to
if(x==0) printf(“Zero”); enclose the statements. This will
else if(x==1) printf(“One”); become more tedious(Fkdkusokyk), to
else if(x==2) printf(“Two”); resolve this kind of problems we use
else if(x==3) printf(“Three”); switch-case beside if-else-if
else if(x==4) printf(“Four”); statement for selecting single
else if(x==5) printf(“Five”); choice among multiple choice.
else if(x==6) printf(“Six”); switch(x){
else if(x==7) printf(“Seven”); case 0: printf(“Zero”); break;
else if(x==8) printf(“Eight”); case 1: printf(“One”); break;
else if(x==9) printf(“Nine”); --------------------------
else printf(“Out of Range”); case 9: printf(“Nine”); break;
getch(); default: printf(“Out of Range”);
} }
Here inside the ‘case’ a lot of statements
can be enclose with ‘{‘ ‘}’.
break; statement is optional.

Page 12 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Control Structure in C Language

Looping control
This kind of control are used to repeat the statement or set of statements several
number of times.
Like when we’ve to check the given number is Prime or Not Prime so we’ll be divide
this number by all number from 2 to n/2 and check that this divisible or not. So that the Task
is to check the Remainder of given number and all number excepting 1 and that number.
To control looping statement we require “SSS”

Start Stop Step


Initialization Termination Modification
(Exp1) (Exp2) (Exp3)
Ex. x=1 x<=10 x++ or
X=10 x>=1 x--

For Loop
This is very simple looping statement. In this kind of loop we write all the expressions
in a sequence like initialization, termination and the modifying value to the loop counter
variable. Compiler read all the expression at once and then repeat the set of statement(s)
many number of times as mentioned with “for” statement.
Note: 1- exp1, exp2 exp3 are optional in the For loop.
2- more than initialization, termination condition and modification can be used within
the loop. In this situation ‘,’ is used to separate each of them.
While loop
This loop is required only the second expression which tells the termination point of
the iteration.
In this loop the First iteration will be carried out after checking the logical text.
Do-While
This loop is too much similar to the while loop but the first iteration is carried out
without checking the logical text.
It will check the condition for the rest or iterations.
Break Statement
This statement is used to terminate all the iterations unconditionally.
Continue
This statement is used to terminate the current iteration only and rest of iteration will be
going on.

Page 13 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Control Structure in C Language

Demonstration for BREAK statement Demonstration of CONTINUE statement


#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main() void main()
{ {
int x; int x;
for ( x=1;x<=10;x++) { for ( x=1;x<=10;x++) {
if(x==5) if(x%2==0)
break; continue;
printf(“%3d”,x); printf(“%3d”,x);
} }
} }
Output: Output:
1 2 3 4 1 3 5 7 9

Nested Looping
When any repeated statement is enclosed within another loop (loop-inside the loop), is
termed as Nested Loop.
In this case when the iteration of the inner loop will be finished then iteration of the
outer loop will be forward.

Page 14 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Arrays in C Language

ARRAY
An Array is a collection of similar type of data. When we requires to store more and
more data of a same type for further processing we need for having more variables that use
to store those data. For this if we take a lot of variables this become more tedious because if
we’ve salary or 10 or 100 employee then we need to declare 10 or 100 memory variables to
store those salary.
For resolving this kind of problems we declare an array of some size that is we are
requires. In array each element will be store in the different block so that this can be retrieve
very easily.

Page 15 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Arrays in C Language

Consider this Example:


#include<stdio.h> This program is to find the
#include<conio.h> maximum number among 10 numbers but
void main() all the numbers are being store in a same
{ variable.
int n,i,j=0; As new value will be replace the old
for(i=0;i<10;i++){ one so that after finishing the task we’ve
printf(“Enter %d number”,i+1); only the last number.
scanf(“%d”,&n); Further preceding any other
if(j<n) j=n; operations like find the Minimum and all,
} we’ve to input all number again.
Printf(“Max=%d”,j);
}

For resolving this kind of problems we use a continuous memory allocation for storing our
large number of data of a same type.

Declaration of Array
Type of Array arrayName [ size of Array ];
Type of Array
Type refers the data type which kind of data will be used to store in this Array. It can
be “int”, “char”, “float”, “double”. “Char” array is considered as “String”.
Array Name
The name of the Array is same as a variable name.
Size of Array
Defines how many elements can be store in this array. This also defines how many
memory index is to be allocated.
Note: This can’t be any variable.
Memory Representation of Array:
int arr[10];
5 3 6 8 9 2 4 1 0 7
0 1 2 3 4 5 6 7 8 9
2000 2002 2004 2006 2008 2010 2012 2014 2016 2018
--------------------------- Index numbers and Memory Address of each -----------------------
Consider this Example:
#include<stdio.h> program for another operation like Finding
#include<conio.h> the minimum elements among these
#define size 10 numbers or list them.
void main(){ for(i=0;i<size;i++) printf(“%4d”,n[i]);
int n[size],i,j=0; int min=n[0];
for(i=0;i<size;i++){ for(i=1;i<size;i++) if(min>n[i]) min=n[i];
printf(“Enter %d no:”,i+1); printf(“Minimum=%d”,min);
scanf(“%d”,&n[i]);
if(j<n[i]) j=n[i];
}
printf(“Maximum=%d”,j);
}

In this example, all the values are being


entered into another index (memory
location) so that all the values can be
retrieve later during the execution of

Page 16 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Arrays in C Language

Character Array
Character array represents a String, like name or address of any person.
Ex: char name[20]; //By default all the block contains null ‘\0’ characters.

E L I T E I N F O S Y S T E M S \0 \0 \0
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
----NULL---

String input/output
Using standard library method “scanf” or “gets” we can receive the character by
character from keyboard.
Ex; Input: scanf(“%s”,name); or gets(name);
Output: printf(“%s”,name); or puts(name);
Note: 1- Using “scanf” we can’t read space between character sequence. If we Type space
between the character sequence it will be considered as a argument separator and
this will enter a new string.
But using “Gets” we can also read space between the string.
2- When we use “puts” method to print a string the line will automatically terminated
after print the string on the screen but “printf” not follow this.
Sorting
“Sorting is a method to arranging the data into predetermine order either ascending or
descending.” There are various method to sort a list of items here in our course we are
learning the three most frequently used sorting techniques, these are Selection, Bubble and
Insertion.
Selection Sorting
This sorting method used to select an item then compare this to all the elements, then
like that check all the element one-by-one with all the remaining elements.

Description
Here is this kind of
sorting process first of
all we compare the
first element to all the
rest elements, if any
element is find lighter
than this they will
swap each other.
Repeat those steps
to remaining all the
elements.
Only those Phase
are showing here in
which the swapping is
occurred.

Page 17 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Arrays in C Language

#include<stdio.h> //sorting algorithm


#include<conio.h> for(i=0;i<size;i++){
#define size 5 for(j=i+1;j<size;j++){
void main() if(arr[i]>arr[j]){
{ temp=arr[i];
int arr[size]; arr[i]= arr[j];
int i,j,temp; arr[j]= temp; }
printf(“Enter %d numbers :”,size); }
for(i=0;i<size;i++){ }
scanf(“%d”,&arr[i]); printf(“\nYour Elements After sorting”);
} for(i=0;i<size;i++){
printf(“\nYour Elements Before sorting”); printf(“%4d”,arr[i]);
for(i=0;i<size;i++){ }
printf(“%4d”,arr[i]); }
}
Bubble Sorting
This sorting method each element is compare with next elements. And this step
repeated as number of time as number of elements.
Description
Here each element
is being compare with
the it’s next element,
if this element is
heavier then the next
then swap them.
Repeat this step as
number of times as
total elements.
Here those phase
are shown in which
the swapping is
occurred.

#include<stdio.h> //sorting algorithm


#include<conio.h> for(i=0;i<size;i++){
#define size 5 for(j=0;j<size-1;j++){
void main() if(arr[j]>arr[j+1]){
{ temp=arr[j];
int arr[size]; arr[j]= arr[j+1];
int i,j,temp; arr[j+1]= temp;
printf(“Enter %d numbers :”,size); }
for(i=0;i<size;i++){ }
scanf(“%d”,&arr[i]); }
} printf(“\nYour Elements After sorting”);
printf(“\nYour Elements Before sorting”); for(i=0;i<size;i++){
for(i=0;i<size;i++){ printf(“%4d”,arr[i]);
printf(“%4d”,arr[i]); }
} }

Page 18 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Arrays in C Language

Insertion sorting
Every repetition of insertion sort removes an element from the input data, inserting it
into the correct position in the already-sorted list, until no input elements remain. The choice
of which element to remove from the input is arbitrary, and can be made using almost any
choice algorithm.
Sorting is typically done in-place. The resulting array after k iterations has the
property where the first k + 1 entries are sorted. In each iteration the first remaining entry of
the input is removed, inserted into the result at the correct position, thus extending the
result:

Insertion sort is very similar to selection sort. As in selection sort, after k passes through the
array, the first k elements are in sorted order. For selection sort these are the k smallest
elements, while in insertion sort they are whatever the first k elements were in the unsorted
array. Insertion sort's advantage is that it only scans as many elements as needed to
determine the correct location of the k+1st element, while selection sort must scan all
remaining elements to find the absolute smallest element.
Calculations show that insertion sort will usually perform about half as many
comparisons as selection sort. Assuming the k+1st element's rank is random, insertion sort will
on average require shifting half of the previous k elements, while selection sort always
requires scanning all unplaced elements. If the input array is reverse-sorted, insertion sort
performs as many comparisons as selection sort. If the input array is already sorted, insertion
sort performs as few as n-1 comparisons, thus making insertion sort more efficient when given
sorted or "nearly-sorted" arrays.
While insertion sort typically makes fewer comparisons than selection sort, it requires
more writes because the inner loop can require shifting large sections of the sorted portion of
the array. In general, insertion sort will write to the array O(n2) times, whereas selection sort
will write only O(n) times. For this reason selection sort may be preferable in cases where
writing to memory is significantly more expensive than reading, such as with EEPROM or flash
memory.
#include<stdio.h> //sorting algorithm
#include<conio.h> for(i=1;i<size;i++){
#define size 5 temp=arr[i];
void main() for(j=i-1;j>=0;j--){
{ if(temp<arr[j]){
int arr[size]; arr[j+1]=arr[j];
int i,j,temp; arr[j]=temp;
printf(“Enter %d numbers :”,size); }
for(i=0;i<size;i++){ }
scanf(“%d”,&arr[i]); }
} printf(“\nYour Elements After sorting”);
printf(“\nYour Elements Before sorting”); for(i=0;i<size;i++){
for(i=0;i<size;i++){ printf(“%4d”,arr[i]);
printf(“%4d”,arr[i]); }
} }

Page 19 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Arrays in C Language

2D Array 0 1 2
Two-Dimensional Array is nothing just an Array of Array. This 0 00 01 02
kind of array is also represent in the memory as in row. 1 10 11 12
Declaration: 2 20 21 22
int arr[r][c]; //r as row and c as column

0 1 2 0 1 2 0 1 2
00 01 02  10 11 12  20 21 22
0th index row 1st index row 2nd index row

This will presented to the used in the pattern like:

Elements in 2D array can


be presented either “Row”
or “Column” major matrix
form.
#include<stdio.h> //Retrieve Elements from 2D Array (Matrix)
#include<conio.h> printf (“Elements of Matrix\n”);
#define rows 3 for(i=0;i<rows;i++){
#define cols 3 for(j=0;j<cols;j++){
void main() printf(“%3d”,mat[ i ][ j ]);
{ }
int mat[rows][cols]; printf(“\n”);
int i,j; }
//input into 2D Array (Matrix) //Transpose Elements of Matrix
printf(“Enter the Elements of Matrix\n”); printf(“Transpose of Matrix\n”);
for(i=0;i<rows;i++){ for(i=0;i<rows;i++){
for(j=0;j<cols;j++){ for(j=0;j<cols;j++){
scanf(“%d”,&mat[i][j]); printf(“%3d”,mat[ j ][ i ]);
} }
} printf(“\n”);
}
}
==========================================================================
/* Program to Multiply Two Matrixes into Third for(i=0;i<r;i++) {
Matrix */ for(j=0;j<c;j++){ mat3[i][j]=0;
#include<stdio.h> for(k=0;k<r;k++)
#include<conio.h> mat3[i][j]+=mat1[i][k]*mat2[k][j];
#define r 3 }
#define c 3 }
void main() //Print Matrix1
{ //Print Matirx2
int mat1[r][c], mat2[r][c], mat3[r][c]; //Print Matirx3
int i,j,k; }
// Take input the element into mat1
// Take input the element into mat2

Page 20 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Functions in C Language

FUNCTIONS
Functions are small-handy programs, are used to perform some specific job. In general
those statements which are frequently used to perform the same tasks, like if we’ve to check
the given number is prime or not. And this task is to be repeat for many numbers again and
again. So for this we’ll be define a subroutine (function) to perform this task and this
subroutine can be called when it is required.

Page 21 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Functions in C Language

Kinds of Functions
Functions are classified into two types as follows:
1- Library
2- User Define

Library Function
These function are already defined into our library along with our compliers. These
functions are very useful to perfume standard operation like to find the Square root of the
given number we’ve “sqrt” function which is defined in “math.h” header file. Similar to this
we’ve a lot of predefined method to operate/calculate our data.
Mathematical Function
S.No. Function Description Prototype & example
1. sqrt This function calculate the double sqrt(double);
square-root of the given double x=sqrt(64);
argument.
2. abs This function is used to evaluate int abs(signed int);
the absolute value of the given int x=abs(-3); // 3
integer argument. int y=abs(3); // 3
3. fabs This function is used to evaluate float fabs(signed float);
the absolute value of the given float x=fabs(-3); // 3
float/double argument. float y=fabs(3); // 3
4. labs This function is used to evaluate long double labs(double);
the absolute value of the given long double x=labs(-3);//3
long double argument. long double y=labs(3); //3
5. floor This function returns the largest double floor(double);
integer less than the given double y=345.43;
argument. double x=floor(y); //x=345
6. ceil, ceill This function returns the smalles double ceil(double);
integer more than the given double y=345.43;
argument. double x=ceil(y); //x=346
7. modf This function breaks the double x double modf(double, double *);
into two parts: the integer and double frc, intr;
the fraction. It stores the integer double num = 100000.567;
in ipart and returns the fraction. frc=modf(num,&intr);
8. fmod This function returns remainder double fmod(double,double);
after dividing a number (double) double y=234.0;
from other number (double). double x=fmod(y,10);
//x = 4
9. frexp frexp splits a double number into double mant, num;
mantissa and exponent int expt;
num = 8.0;
mant = frexp(num, &expt);
//mant=2 & expt=3
10. log This function returns the Natural double log(int);
Log (logen) of any integer (n). double x=log(2);
//x=0.693147181
11. log10 This function returns the Log double log10(int);
(log10n) of any integer (n) on the double x=log10(2);
base 10. //x= 0.301029996
12. pow Power function, x to the y (x**y) double pow(double , double);
double x=2.0,y=3.0;

Page 22 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Functions in C Language

S.No. Function Description Prototype & example


double z=pow(x,y); //8.0
13. pow10 Power function, 10 to the p double pow(double);
(10**p) double p=2.0;
double x=pow10(x); //100
14. sin This function calculates the Sine double sin(double);
of an angle. #define pi 3.14
Note: argument should be in double x=90*pi/180;
radians. double val=sin(x); //1.0
15. cos This function calculates the Cosine double cos(double);
of an angle. #define pi 3.14
Note: argument should be in double x=60*pi/180;
radians. double val=cos(x); //0.5
16. tan This function calculates the double tan(double);
Tangent of an angle. #define pi 3.14
Note: argument should be in double x=45*pi/180;
radians. double val=tan(x); //1
Character Functions
S.No. Function Description Prototype & example
1. isprint This function checks whether int isprint(char); //0-F 1-T
passed character is Printable or printf(“Press any key…”);
Not printable. char ch=getch();
if(isprint(ch)) printf(“Yes”);
else printf(“Not”);
2. isspace This function checks whether int isspace(char); //0-F 1-T
passed character is Space or Not. printf(“Press any key…”);
char ch=getch();
if(isspace(ch)) printf(“Yes”);
else printf(“Not”);
3. isalnum This function checks whether int isalnum(char); //0-F 1-T
passed character is Alphanumeric printf(“Press any key…”);
(A-Z,a-z,0-9) or Not. char ch=getch();
if(isalnum(ch)) printf(“Yes”);
else printf(“Not”);
4. isalpha This function checks whether int isalpha(char); //0-F 1-T
passed character is Alphabet (A- printf(“Press any key…”);
Z,a-z) or Not. char ch=getch();
if(isalpha(ch)) printf(“Yes”);
else printf(“Not”);
5. isdigit This function checks whether int isdigit(char); //0-F 1-T
passed character is digit (0-9) or printf(“Press any key…”);
Not. char ch=getch();
if(isdigit(ch)) printf(“Yes”);
else printf(“Not”);
6. isxdigit This function checks whether int isxdigit(char); //0-F 1-T
passed character is hex-decimal printf(“Press any key…”);
digit (0-9,A-F,a-f) or Not. char ch=getch();
if(isxdigit(ch)) printf(“Yes”);
else printf(“Not”);
7. islower This function checks whether int islower(char); //0-F 1-T
passed character is Alphabet is in printf(“Press any key…”);

Page 23 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Functions in C Language

S.No. Function Description Prototype & example


lower case (a-z) or Not. char ch=getch();
if(islower(ch)) printf(“Yes”);
else printf(“Not”);
8. isupper This function checks whether int isupper(char); //0-F 1-T
passed character is Alphabet is in printf(“Press any key…”);
UPPER case (A-Z) or Not. char ch=getch();
if(isupper(ch)) printf(“Yes”);
else printf(“Not”);
9. toascii This function converts character int toascii(char);
argument into the Byte (ASCII) char ch=‘a’;
value. int code=toascii(ch); //97
10. tolower This function converts upper case char tolower(char);
character into lower case char ch= ‘A’;
character. printf(“%c”,tolower(ch)); //a
11. toupper This function converts lower case char toupper(char);
character into upper case char ch= ‘a’;
character. printf(“%c”,toupper(ch)); //A

Page 24 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Functions in C Language

String Functions (string.h)


S.No. Function Description Prototype & example
1. strlen This function calculate the total int strlen(char*);
number of character (with char nm[]={“Elite Infosystems”};
space) in the character array. int len=strlen(nm);
printf(“%d”,len); //17
2. strcpy Copies a string into another char *strcpy(char *,char*);
string. char nm[]={“Elite”};
char nm2[10];
puts(strcpy(nm2,nm)); //Elite
3. strncpy Copies ‘n’ characters from a char *strncpy(char *,char*);
string into another string. char nm[]={“Elite”};
char nm2[10];
puts(strncpy(nm2,nm,4)); //Elit
4. strcat Concatenate a string into char *strcat(char *,char*);
another string. char nm[]={“Elite”};
char nm2[]={“ infosystems”};
puts(strcat(nm,nm2);
//nm= Elite infosystems
5. strncat Concatenate ‘n’ characters from char *strncat(char *,char*);
a string into another string. char nm[]={“Elite”};
char nm2[]={“ infosystems”};
puts(strncat(nm,nm2,4);
//nm= Elite info
6. strcmp This function compare two int strcmp(char*,char*);
strings and return an integer char nm1[]={“Sachin”};
value. char nm2[]={“Sehwag”};
int x=strcmp(str1,str2); if(strcmp(nm1,nm2)>0)
Value of x > 0 str1>str2 printf(“nm1>nm2”);
Value of x < 0 str1<str2 else if(strcmp(nm1,nm2)<0)
Value of x = 0 str1=str2 printf(“nm1<nm2”);
else printf(“nm1=nm2”);
7. strncmp This function compare “n” int strncmp(char*,char*,int);
characters of two strings and char nm1[]={“ram”};
return an integer value. char nm2[]={“Ram”};
int x=strncmp(str1,str2,n); if(strncmp(nm1,nm2,1)>0)
Value of x > 0 str1>str2 printf(“nm1>nm2”);
Value of x < 0 str1<str2 else if(strncmp(nm1,nm2,1)<0)
Value of x = 0 str1=str2 printf(“nm1[0]<nm2[0]”);
else printf(“nm1[0]=nm2[0]”);
8. stricmp This function compare two int stricmp(char*,char*);
strings with ignoring the case char nm1[]={“ram”};
and return an integer value. char nm2[]={“Ram”};
int x=stricmp(str1,str2,n); if(stricmp(nm1,nm2)>0)
Value of x > 0 str1>str2 printf(“nm1>nm2”);
Value of x < 0 str1<str2 else if(stricmp(nm1,nm2)<0)
Value of x = 0 str1=str2 printf(“nm1<nm2”);
else printf(“nm1=nm2”);
9. strlwr Converts a string into lowercase. char* strlwr(char*);
char nm[]={“ELITE”};
puts(strlwr(nm)); // elite
10. strupr Converts a string into char* strupr(char*);
Page 25 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001
C Language Functions in C Language

S.No. Function Description Prototype & example


UPPERcase. char nm[]={“elite”};
puts(strupr(nm)); // ELITE
11. strrev Reverse a string. char* strrev(char*);
char nm[]={“madam”};
puts(strrev(nm)); //madam
12. strdup Copies a string into a newly char *dup_str, *string = "abcde";
created location. dup_str = strdup(string); //abcde

User Define Functions


We can also define our own subroutines as a predefine set of instructions, which can
be used for anywhere when it is required to be execute.
Function Prototype
Outline of the Function model in known as function prototype. Which define all about
the function like which kind of value that the function will return it may be the function will
not return the value, next what will be the name of the function and at the last what will be
the arguments passed to function (optional).
Syntax: Return_type functionName (argumentList);
Return type
If function dose not return any value this will be “void” but if the function return the
value so it may be any kind of data type like int/char/char*/int*/double/float etc.

For Example: a) void sum(int,int); b) int sum(int,int);


a) This function will never return any value due to “void” return type, it will process the
arguments passed to the function as parameter and produce the sum of these integer
and print them on output device or any other resource like files etc.
b) This kind of function will gives us an integer type data after performing the operation
on the given parameters.
Note: 1- Return type and argument list of the function are case depended.
2- Function name are case sensitive they will work like an identifier, so all the rules
of an identifier are applied on them.

Page 26 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Functions in C Language

#include<stdio.h> Description
void dispMsg(void); Here function ‘dispMsg’ has a ‘void’
//function prototype return type as well as argument type, it
void main(){ means this will not return kind of value and
dispMsg(); //calling of function also not having parameter value to be
process.
for(int i=1;i<=10;i++) dispMsg(); Note: When we compile our program we
// calling of function through loop are required function prototype and
} when we execute our program we
void dispMsg(){ require the function definition.
printf(“Welcome the Elite\n”);
}

/* Program to demonstrate that the given parameter is prime or not. */


#include<stdio.h> int isPrime(int n){
int isPrime(int); int x;
for(x=2;x<=n/2;x++)
void main(){ if(n%x==0) return 0; //false
int n; return 1; //true
printf(“Enter any number :”); }
scanf(“%d”,&n); Description: Here function ‘isPrime’ have
an integer type argument for ‘n’ and this
if( isPrime(n) ) printf(“Yes”); will return ‘0’ as false and ‘1’ as true.
else printf(“Not”);
}

/*Find the nearest three Prime number of a given number including self. */
#include<stdio.h> 1- Function can defined above of the
int isPrime(int n){ main function, in this case it not
int x; required to declare.
for(x=2;x<=n/2;x++) 2- Function can be declare any where but
if(n%x==0) return 0; //false just before calling of the function.
return 1; //true
}
void main(){
int n,x,I,count=0;
printf(“Enter any number ”);
scanf(“%d”,&n);
if(isPrime(n)) {count++;printf(“%d”,n);}
i=1;
while(count<3){
x=n+i;
if(isPrime(x)) {count++;printf(“%d”,x);}
if(count==3) break;
x=n-i;
if(isPrime(x)) {count++;printf(“%d”,x);}
i++;
}//end of while
}//end of main

Note:

Page 27 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Functions in C Language

Recursion #include<stdio.h>
The special feature of the C Language is long int fact(int n){ …..}
that it supports the recursive functions. When void main(){
the function is being call itself within the int n;
definition of itself it is known as RECURSIVE long int f;
calling. printf(“Enter number : ”);
All the parameter which are used inside scanf(“%d”,&n);
the functions are works like static data, their if(n<=0) printf(“Invalid number”);
life time is until the job is not finished else{ f=fact(n);
completely. }//end of else
For example: }//end of main
5!=5 x4! Note: When the Function ‘fact’ is being
4!= 4x3! call recursively then the current
3!=3 x2! expression will be paused until the
2!= 2x1! function don’t return any value. As
1 soon as the function will back to it
long int fact(int n){ old situation this will continue.
long int j=n; if(j==1) return 1;
j=j*fact(n-1);
return j;
}

Passing an Array to function as Argument


We can pass whole of the Array to the function as an argument to be input elements
into it or process the data.
returnType functionName ( dataType []);
For example:
#include<stdio.h> printf(“\n Enter Element of 1st Array”);
#define size 10 inputArray(arr1); displayArray(arr1);
void inputArray(int ar[]){ printf(“\n Enter Element of 2nd Array”);
int i; inputArray(arr2); displayArray(arr2);
for(i=0;i<size;i++)
scanf(“%d”,&ar[i]); printf(“\n Enter Element of 3rd Array”);
} inputArrayN(arr3,size*2);
void inputArrayN(int ar[],int n){ displayArrayN(arr3,size*2) ;
int i; }
for(i=0;i<n;i++)
scanf(“%d”,&ar[i]);
}
void displayArray(int ar[]){
int i;
for(i=0;i<size;i++)
printf(“%3d”,ar[i]);
}
void displayArrayN(int ar[],int n){
int i;
printf(“\nYour Elements :”);
for(i=0;i<n;i++)
printf(“%3d”,ar[i]);
}
void main(){
int arr1[size],arr2[size],arr3[size*2];
Page 28 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001
C Language Pointers in C Language

POINTERS
Pointer is a variable that is refers the address of the other variable of the same base
type. It will not hold the value, but using variable location we can find the value of that
variable.
The concept of pointers is somewhat complex but is simple when compared to its
advantages. Pointers is more difficult to understand but the proper use of it makes the “C”
language excellent.

Page 29 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Pointers in C Language

When any variable is declared it will occupy some memory space obviously it has
allocation in the memory registers.
For example:
int x,y;// memory presentation

x 2002 When variable is declared named ‘x’ and ‘y’ they have a
2004 reserve location on the memory registers, for example 2002, 2006
2006 respectively.
y 2008 To get the value of that location we must have their location.
2010

Key Points:
 Pointers is used For Saving Memory Space
 Use of Pointer, Assigns The Memory space and also releases it. This concept helps in
making the best use of The available memory (dynamic memory allocation).
 With Pointer data manipulation is done with address, so the execution time is faster
 Two-dimensional and multi-dimensional array representation is easy with pointers.
 Pointer concept is used with data structures such as linked list.
For Example:
#include<stdio.h> Output:
#include<conio.h> Enter the value of a : 5
void main() Value of a = 5
{ Value of a = 5
clrscr(); Value of a = 5
int a,*ptr; //* use to define pointer Address of a = 36234
ptr=&a; //assign the address of ‘a’ Address of a = 36234
printf(“Enter the value of a : ”); Address of ptr = 36236
scanf(“%d”,ptr); // scanf(“%d”,&a); Value of ptr=address of a =36234
printf(“value of a = %d\n”,a);
printf(“value of a = %d\n”,*ptr); Description:
printf(“value of a = %d\n”,*(&a));
printf(“address of a = %u\n”,&a);
printf(“address of a = %u\n”,ptr); a < variable > ptr
printf(“address of ptr = %u\n”,&ptr);
printf(“value of ptr = address of a = %u\n”,&a); 5 < value > 36234
getch();
} 36234 < Address > 36236

/*Program to swap two number using function swap(x,y); //call by value


call by value */ }
#include<stdio.h> Here the function is being call by
void swap(int x,int y){ passing the value of x, y (copy of actual
int z;z=x; x=y; y=z; data). Originally the actual value is as it is.
printf(“\nAfter Swapping\n”); Function swap those value which is
printf(“x=%d and y=%d”,x,y); received in the formal parameters.
} Conclusion: Still actual data is intact.
void main(){ Discussion: There is no effect on the
int x,y; actual data when we call the function
printf(“Enter value of x and y : ”); passing by value as argument.
scanf(“%d %d”,&x,&y);
Page 30 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001
C Language Pointers in C Language

/*Program to swap two number using function printf(“\nSorted Array\n”);


call by Reference*/ printArrayRef(&arr[0],size);
#include<stdio.h> }
void swapRef(int *x,int *y){ Note: Using Pointer we receive the start
int z;z=*x; *x=*y; *y=z; location of the array index and it will
} make automatic increment to the
void main(){ next memory location.
int x,y; Dynamic memory Allocation
printf(“Enter value of x and y : ”); Using pointer we can allocate the
scanf(“%d %d”,&x,&y); memory space as we require for our data
swapRef(&x,&y); //call by Reference operations.
printf(“\nAfter Swapping\n”); This will save our access memory
printf(“x=%d and y=%d”,x,y); allocation using static size arrays.
} /* Program to Allocation memory space for
In this program we’ve passed the reference array as number of elements as user wants.
(Memory location Address) of the variable so */
that we can work with the actual data, which is #include<stdio.h>
stored in the memory registers. #include<alloc.h>
Conclusion: Actual data has been update. void main(){
Passing of Array to the Function using Pointer int *arr;
Each element in array has a memory int i,n,size;
location, and consume 2 byte space (for i=0;
integers). If we get the location of very first while(1) //infinite loop
element to it easy to find the remaining element {printf(“Enter Element, ‘0’ to stop:”);
due to continuous allocation of elements scanf(“%d”,&n); if(n==0) break;
#include<stdio.h> arr[i]=(int)malloc(sizeof(int));
#define size 10 arr[i++]=n; size=i;
void inputArrayRef(int *x,int n){ }
int i; for(i=0;i<size;i++){
printf(“Enter %d Element(s) \n”,n); printf(“%4d”,arr[i]);
for(i=1;i<=n;i++) }
scanf(“%d”,x++); }
} Description:
void printArrayRef(int *x,int n){ ‘While (1)’ is a infinite loop it never
int i; terminate until user will enter ‘0’ as
printf(“\n%d Element(s) \n”); element for array.
for(i=1;i<=n;i++) ‘(int)malloc(sizeof(int))’ will
printf(“%4d”,*(x++)); calculate the size of a integer and allocate
} some memory space(2 byte) for an integer
void sort(int *x,int n){ type data, so that we can assign here an
int i,j,*p,*q; integer value.
for(i=1,p=x;i<=n;i++,p++) After assigning a value to the
for(j=i+1,q=p+1,j<=n;q++,j++) generated index position ‘i++’ for next
if(*p>*q) swapRef(p,q); memory allocation.
} ‘int *x’ will keeps all the elements on
void main(){ tracks in a single Variable.
int arr[size]; After allocation of the memory space
inputArrayRef(&arr[0],3); we can retrieve elements same as from an
inputArrayRef(&arr[3],3); Array.
inputArrayRef(&arr[6],4);
printArrayRef(&arr[0],size);
sort(&arr[0],size);
Page 31 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001
C Language Pointers in C Language

Dynamic Allocation - Char 2D Array


Char 2D Array will work as Array of String.
Many String can be assigned and operate for
operation like searching and sorting.
0 1 2 3 4 5 6 7 8 9
0 R a m e s h
1 K a i l a s h
2 S a c h i n
3 S e h w a g
4 K r i s h n a

#include<stdio.h>
#include<string.h>
#include<alloc.h>
void main(){
char **arr;
char *tmp;
int i,j,size;
int len;
i=0;
while(1) //infinite loop
{printf(“%d Name, ‘ENTER’ to stop:”,i+1);
gets(tmp); len= strlen(tmp);
if(len==0) break;
arr[i]=(char*)malloc(len+1);
strcpy(arr[i++],tmp); size=i;
}
printf(“Before sort %d Names: \n”,size);
for(i=0;i<size;i++) puts(arr[i]);
//Sorting of name ----------------
for(i=0;i<size;i++)
for(j=i+1;j<size;j++)
if(strcmp(arr[i],arr[j])>0){
strcpy(tmp,arr[i]);
strcpy(arr[i],arr[j]);
strcpy(arr[j],tmp);
}
printf(“After sort %d Names: \n”,size);
for(i=0;i<size;i++) puts(arr[i]);
}

Page 32 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Structure and Union in C Language

STRUCTURE
A collection of one or more variables, typically of different types, grouped together under a
single name for convenient handling.
Defines a new type ex, a new kind of data type that compiler regards as a unit

Page 33 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Structure and Union in C Language

Declaring struct variables


struct motor p, q, r;
Declares and sets aside storage for three variables – p, q, and r – each of type struct
motor
struct motor M[25];
Declares a 25-element array of struct motor; allocates 25 units of storage, each one big
enough to hold the data of one motor
struct motor *m;
Declares a pointer to an object of type struct motor.
Accessing Members of a struct
Let
struct motor p;
struct motor q[10];
Then
p.volts — is the voltage
p.amps — is the amperage
p.phases — is the number of phases
p.rpm — is the rotational speed

q[i].volts — is the voltage of the ith motor


q[i].rpm — is the speed of the ith motor

Let
struct motor *p;
Then
(*p).volts — is the voltage of the motor pointed to by p
(*p).phases — is the number of phases of the motor pointed to by p

The (*p).member notation is a nuisance


Clumsy to type; need to match ( )
Too many keystrokes
This construct is so widely used that a special notation was invented, i.e.,
p->member, where p is a pointer to the structure

Page 34 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Structure and Union in C Language

Operations on struct Initialization of a struct


Copy/assign Let struct motor {
struct motor p, q; float volts;
p = q; float amps;
Get address int phases;
struct motor p; float rpm;
struct motor *s }; //struct motor
s = &p; Then
Access members struct motor m = {208, 20, 3, 1800};
p.volts; //initializes the struct
s -> amps;

Memory layout
struct COST { int amount; A better alternative (from a space
char currency_type[2]; } perspective):
struct PART { char id[2]; struct COST { int amount;
struct COST cost; char currency_type; }
int num_avail; } struct PART { struct COST cost;
layout of struct PART: char id[2];
int num_avail;
}

Here, the system uses 4-byte alignment of


integers,
so amount and num_avail must be aligned
Four bytes wasted for each structure!

Unions
Storage
size of union is the size of its largest member
avoid unions with widely varying member sizes;
for the larger data types, consider using pointers instead
Initialization
Union may only be initialized to a value appropriate for the type of its first member

Page 35 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Structure and Union in C Language

/* Program to demonstrate structure*/ /* Program to demonstrate Array of


#include<stdio.h> structure*/
#include<conio.h> #include<stdio.h>
struct emp{ #include<conio.h>
int id,age; #define size 4
char name[30]; struct emp{
int salary; int id,age;
}; char name[30];
void main(){ int salary;
struct emp e1,e2; };
printf(“Information about 1st Emp : \n”); void main(){
printf(“----------------------------------\n”); struct emp e[size];
printf(“ID : ”); scanf(“%d”,&e1.id); int I;
printf(“Name : ”); fflush(stdin); for(i=0;i<size;i++){
gets(e1.name); printf(“Information about %d Emp :
printf(“Age : ”); scanf(“%d”,&e1.age); \n”,i+1);
printf(“Salary: ”); printf(“----------------------------------\n”);
scanf(“%d”,&e1.salary); printf(“ID : ”); scanf(“%d”,&e[i].id);
printf(“Information about 2nd Emp : \n”); printf(“Name : ”); fflush(stdin);
printf(“----------------------------------\n”); gets(e[i].name);
printf(“ID : ”); scanf(“%d”,&e2.id); printf(“Age : ”); scanf(“%d”,&e[i].age);
printf(“Name : ”); fflush(stdin); printf(“Salary: ”);
gets(e2.name); scanf(“%d”,&e[i].salary);
printf(“Age : ”); scanf(“%d”,&e2.age); }
printf(“Salary: ”);
scanf(“%d”,&e2.salary); printf(“ID \t Name\t Age\tSalary\n”);
printf(“\n\npress any key….”); for(i=0;i<size;i++){
getch(); clrscr(); printf(“%d \t %s \t %d \t %d\n”,e[i].id,
e[i].name, e[i].age, e[i].salary);
printf(“ID \t Name\t Age\tSalary\n”); }
printf(“%d \t %s \t %d \t %6d\n”,e1.id, e1.name,
e1.age, e1.salary);
printf(“%d \t %s \t %d \t %6d\n”,e2.id, e2.name,
e2.age, e2.salary);
getch();
}

Page 36 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Files in C Language

FILES
In general when develop any application we used some variables for storing data for
temporary operation. After finishing the execution of the program, data will be lost.
It is necessary to keep data in the secondary storage device due to volatile behavior of
memory registers. C supports the concept of the file through which the data can be stored in
the permanent storage device like HDD/FDD/USB Drive, so that the data can be obtained
whenever required. “A File is a collection of information (operated data) on the disks.”

Page 37 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Files in C Language

Step for file operation in C Programming are as follows:


1- Open a file for Read/Write/Append
2- Perform the Operation (R/W/A)
3- Close that file

Opening a file
When we store a record in the file then at first we need a temporary area in the
memory we store the data/records then we transfer it to any file. For storing those records in
the memory, we use the pointer, which points the starting address, where this data/record is
stored.
We write this a-
FILE *p;
Here p is a pointer of file type. For declaring any variable to file type pointer it is
necessary to write FILE in capital and then pointer variable name.
For opening a file we use the library function fopen(). First we declare pointer variable
and open() as file type pointer.
We write this as-
FILE *p;
Then p=fopen(“filename”, “mode”);
Modes
1 w (write)
This mode opens a opens a file for write a record, if the filename already exists then using
this mode, new data/record entered is written (overwritten) to the file.
Ex.
p=fopen(“abc.txt”, “w”);
Here ‘abc.txt’ is the file name and ‘w’ is the mode.
2- a (append)
This mode opens a file for appending (adding new at the end of the File) data/record if
the file doesn‘t exists then work of this mode is same as “w” mode.
Ex.
p=fopen(“abc.txt”, “a”);
Here ‘abc.txt’ can be already exists or new file.
3- r (read)
This mode is used for reading data from file purpose only.
Ex.
p=fopen(“abc.txt”,”r”);
If the file “abc.txt” doesn’t exists then compiler return NUL to the file pointer
This is written as-
p=fopen(“abc.txt”.”r);
if (p==NULL) printf(“File does not exist’);

4 w+ (write+read)

This mode is used both for reading and writing purpose. This is same as the “w” mode but
we can also read the record which is stored in the file.

p=fopen (“abc.txt”,”w+”);

5 a+(append + read)
This mode is used both for reading and appending the record. This mode is same as the
“a” mode but we can also read the record which is stored in the file
Ex.

Page 38 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Files in C Language

p=fopen (“abc.txt”,”a+”);
6 r+ (read + write)
This Mode is used both for reading and writing purpose. We can read the record and also
write the record in the file. From This mode the previous record of the file is not deleted .
Ex.
p=fopen(“abc.txt”, “r”);
If the file “abc.txt” doesn‘t exists then compiler return NUL To The file pointer.
This is Writen as-
p=fopen(“abc.txt”,”r”);
if(p==NULL) printf(“File does not exit”);

Closing A File
The file which are opened from the fopen() function must be close at the end of the
program. this written as-
fclose(p);
If the opening file is more than one then we close all the files.
fclose(p1);
fclose(p2;
fclose(p3);
/* Program to Write the input data by the user }//end of loop
into a FILE. */ }//end of main
#include<stdio.h>
void main(){
int id,age;
char name[30];
printf(“Enter Student Information \n”);
printf(“ID : ”);scanf(“%d”,&id);
printf(“Name : ”); fflush(stdin);
gets(name); //removeSpace(name);
printf(“Age: ”);scanf(“%d”,&age); /* Program to search any Record from
FILE *p; “stdRec.dat” file. */
p=fopen(“stdRec.dat”, “a”); #include<stdio.h>
fprintf(p,“%d %s %d\n”,id,name,age); #define TRUE 1
fclose(p); #define FALSE 0
} void main(){
Note: This program will be executed many int id,age; char name[30];
number of times, each time user will enter their int roll;
information and these data will be append to a printf(“Enter Roll number : ”);
file “stdRec.dat”. scanf(“%d”,&roll);
We can retrieve it later. int found=FALSE;
/* Program to List all the Records from FILE *p=fopen(“stdRec.dat”, “r”);
“stdRec.dat” file. */ while(fsacnf(p,”%d %s %d”,&id, name,
#include<stdio.h> &age) !=EOF){
void main(){ if(roll==id){ found=TRUE;
int id,age; char name[30]; printf(“ID \t Name \t\t Age \n”);
FILE *p=fopen(“stdRec.dat”, “r”); printf(“-----------------------------\n”);
printf(“ID \t Name \t\t Age \n”); //recvSpace(name);
printf(“-----------------------------\n”); printf(“%d \t %s \t %d”,id,name,age);
while(fscanf(p,”%d %s %d”,&id, name, }//end of if
&age) !=EOF){ }//end of loop
//recvSpace(name); If(!found) printf(“Not Found”);
printf(“%d \t %s \t %d\n”,id,name,age); }//end of main

Page 39 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001


C Language Files in C Language

/* Program to Read a Text file content using


command line argument.*/
#include<stdio.h>
void main(int n ,char **arg){
int i; char ch;
if(n==1)printf(“No File name Entered”);
else{
FILE *p=fopen(arg[1], “r”);
while(fscanf(p,”%c”,&ch)!=EOF){
printf(“%c”,ch);
}//end of loop
}//end of else
}//end of main

 Save this Program with name “eType.c”


 Make EXE (press F9).
 Select Dos prompt from File.

Page 40 Elite Infosystems, An ISO 9001:2008 Certified Organization Since 2001

You might also like