book4
book4
• Group of bits
Word • Varies from machine to machine
• Eg: 16-bit, 32-bit, 64-bit words
Data processing in computer
Data processing in computer
Computer bus:
• Is a communication system that transfers data between components
• The size or width of a bus is how many bits it carries
• Eg: 8 bits, 16 bits, 32 bits, 64 bits etc.
Two types
1. System software
2. Application software
Computer Software
Application software
• Set of one or more programs designed to perform some specific
application
• Eg: MS Word, Photoshop, AutoCAD, Web Browsers
Computer Software
System software
• Set of one or more programs designed for computer system
management
• It control the operations of computer system
• Acts as an interface between application software & computer
hardware
• Eg:
• Operating system (windows)
• Language translators (compilers, interpreters)
• Utility programs (anti-virus, disk cleaners)
Operating System
Operating system (OS) is system software which operates the
computer system & manages its resources
Disadvantages
• Very difficult to program
• Programmer has to remember a lot of codes
• Hardware dependent
• Prone to errors while writing code
• Difficult to debug the program
Assembly Language
• A low level language/second generation
• Is almost like the machine code , except that it uses words in place of
binary digits
• These words are called mnemonics
• Is machine dependent
Assembly Language
•Advantages:
• Assembly language is easier to understand than machine language
• Easier to correct errors and modify program instructions
• Has the same efficiency of execution as the machine level language
Disadvantages:
• Assembly language is machine dependent
Assembly Language
Assembler:
Translator which converts program in assembly language
(source code) to machine language (object code)
PROGRAMING IN C
High Level Language
• High level languages were developed to make programming
easier
• The instruction sets are more compatible with human
language
• Eg: C, Java
• Programs written in high level languages must also be
translated into machine language
High Level Language
Advantages:
Disadvantage:
• Slow Execution
Translator
Translator is a program that converts source code into object code
ØOnce compiling & linking is done, the program can be loaded &
executed any number of times without any need to return to
source code
ØIf any change is to be made, it must be done in source code and
modified program can be complied and linked and loaded
Interpreter
• A special program that processes statements written in a programming
language (source code) and translates them into machine language
(object code)
• Interpreter translates one statement at a time & executes it
• Translation happening during the execution phase
• Python, MATLab
Compiler Interpreter
Takes entire program as input Works on statement by statement
Generates an intermediate code - object code Does not generate an intermediate code
Memory requirement is more since object More memory efficient
code is generated
Executes control/logical statements like if, else Executes control/logical statements slower
faster than compiler
Takes more time to execute source code but Takes less time to execute source code but
overall execution time is comparatively faster overall execution time is comparatively slower
Once compiled can run any time Programs interpreted line by line every time
when run
Errors are reported after entire program is Error is reported at once when an error is
checked encountered
Debugging is difficult Easier to debug since errors are reported
when encountered
Structured Program
• Structured Programming (modular programming): Is a
programming approach which is a disciplined and ordered
approach to develop a program
Keyword:
Ø Are reserved words with some predefined meaning
Ø Eg: int, if, else
Ø Assigned by compiler designer of the program
Ø All keywords have fixed meanings and these meanings cannot
be changed
Keywords in C
Example:
int a = 10;
float b = 10.3;
Keywords & Identifiers
In 'C' every word can be either a keyword or an identifier
Identifier:
Ø Identifier refers to name given to elements such as variables, functions, etc.
Ø Are user defined and may consists of sequence of letters & digits
Ø Identifiers must be unique
Example:
float marks;
float average;
Ø float – keyword
Ø marks, average - identifiers
Rules for Identifies
1. Must begin with an alphabet (or underscore)
2. Must consist of only letters, digits or underscore
3. Only first 31 characters are significant
4. Cannot use a keyword
5. Must not contain white space
6. Upper case & lower case letters are distinct
Constants
Constants: Refer to fixed values that do not change during the execution
of a program
Integer Constants
Integer Constants:
An integer constant refers to a sequence of digits
Three types of integers:
1. Decimal integer
2. Octal integer
3. Hexadecimal integer
Integer Constants
Decimal integers (base 10)
§ Consist of a set of digits, 0 through 9, preceded by an optional – or + sign
§ Eg: 123, -465
if (condition)
• If the result of condition is true – statement 1
{
Statement 1; • If the result of condition is false – statement 2
}
else
{
Statement 2;
}
If – else Statements
*
**
***
****
*****
j
1 2 3 4 5
i 1 *
2 * *
3 * * *
4 * * * *
5 * * * * *
§ Outer loop – number of rows j
1 2 3 4 5
i 1 *
2 * *
3 * * *
4 * * * *
5 * * * * *
§ Outer loop – number of rows j
1 2 3 4 5
i 1 *
2 * *
3 * * *
4 * * * *
5 * * * * *
§ Outer loop – number of rows j
§ Inner loop – number of ‘*’ in one row 1 2 3 4 5
i 1 *
2 * *
3 * * *
4 * * * *
5 * * * * *
§ Outer loop – number of rows j
§ Inner loop – number of ‘*’ in one row 1 2 3 4 5
i 1 *
2 * *
3 * * *
4 * * * *
5 * * * * *
§ Outer loop – number of rows j
§ Inner loop – number of ‘*’ in one row 1 2 3 4 5
i 1 *
void main ()
{ 2 * *
int i,j; 3 * * *
for (i=1; i<=5; i++)
4 * * * *
{
for (j=1; j<=i; j++) 5 * * * * *
{
printf(“*”); i =1 , j loop – one *
} i =2 , j loop – two **
printf(“\n”); i =3 , j loop – three ***
}
Nested loops
1
12
123
1234
12345
§ Outer loop – number of rows j
§ Inner loop – number of ‘*’ in one row 1 2 3 4 5
i 1 1
void main ()
{ 2 1 2
int i,j; 3 1 2 3
for (i=1; i<=5; i++)
4 1 2 3 4
{
for (j=1; j<=i; j++) 5 1 2 3 4 5
{
printf(“%d”,j); i =1 , j loop – one *
} i =2 , j loop – two **
printf(“\n”); i =3 , j loop – three ***
}
INPUT OUTPUT
FUNCTIONS
Input Output Functions
Input/Output function in C
ØVarious input/output functions are available in C language
ØThey are classified into two broad categories
1. Console Input/Output Functions – These functions receive
input from keyboard and write them on the VDU (Visual
Display Unit) - Monitor
2. File Input/Output Functions – These functions perform
input/output operations on a hard disk or other storage
devices
Input/Output function in C
Console I/O functions further classified into
1. Formatted Input/Output Functions
2. Unformatted Input/Output Functions
Type Input function Output function
Formatted scanf() printf()
Unformatted getchar() putchar()
gets() puts()
Formatted I/O functions enable the user to specify the type of data, and
the way it should be read in or written out. This user specification is not
possible with unformatted I/O functions
Input/Output function in C
Input function Output function Purpose
scanf() printf() Input & Output of single characters,
strings, numerical values
getchar() putchar() Input & Output of single characters
gets() puts() Input & Output of strings
getchar() & putchar()
getchar() function:
Reads a character from keyboard Example:
Header file – <stdio.h> main()
{
char letter;
letter = getchar ()
char letter: }
Declares that ‘letter’ is a character-type variable
letter = getchar ():
Reads a single character entered from the keyboard and assign to ‘letter’
getchar() & putchar()
putchar() function:
Prints a character on the screen Example:
Header file – <stdio.h> main()
{
char letter;
letter = getchar ();
putchar (letter);
}
getchar() & putchar()
• The getchar function can also be used to read multi-character strings, by
reading one character at a time within a loop
• The putchar function can be used with loops to output a string.
gets() & puts()
• The gets() function reads strings from keyboard until ENTER key is pressed
• The puts () function prints a string of characters on the screen
#include<stdio.h>
void main()
{
char message [20];
printf(“ Enter message:\n”);
gets(message);
puts(message);
}
printf() & scanf()
functions
scanf() function
• scanf() function can be used to enter any combination of numerical values
or characters or strings
Syntax
scanf(“control string”, arguments list);
scanf(“control string”, arg1, arg2, arg3);
Control string:
• Specifies the field format in which the data is to be entered
• It is a sequence of one or more character groups
• Starts with a % and followed by a conversion character indicating the
type of data
Arguments list:
• Specify the address of locations where the data is stored
scanf() function
scanf(“control string”, arg1, arg2, arg3);
scanf(“%3d”, &number);
• Can input integer with 3 digits
Syntax
printf(“control string”, arguments list);
printf() function
Syntax
printf(“control string”, arguments list);
Example:
printf (“Hello World”);
printf (“%d”, number);
printf (“%f %d ”, x1, x2); when x1 is float type and x2 is interger
type
printf (“Sum of two numbers = %d”, sum);
printf() function
a = 123.456 printf (“%f”, a); 123.456000
a = 123.456 printf (“%.3f”, a); 123.456
a = 123.456 printf (“%.1f”, a); 123.5
b = 678 printf (“%d”, b); 678
b = 678 printf (“%5d”, b); 678
b = 678 printf (“%05d”, b); 00678
OPERATORS
EXPRESSIONS
Contents
• Operators & types
• Expressions
• Statements
• Precedence of operators
OPERATORS &
EXPRESSIONS
OPERATORS
Operator: is a symbol that tells the compiler to perform specific
mathematical or logical functions
• Arithmetic Operators
• Unary operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
Arithmetic Operators
§ An arithmetic operator performs mathematical
operations on numerical values
§ The operands must be numerical values
UNARY OPERATORS
• Operators that act upon a single operand to produce a
new value
1. ++ : Increment operator
• Increments the value of operand by 1
• A++ means A=A+1
2. -- : Decrement operator
• Decrements the value of operand by 1
• A-- means A=A-1
UNARY OPERATORS
UNARY OPERATORS
• Pre-fix increment ++A First the increment/decrement
action will be done and then the
• Pre-fix decrement - -A value of operand (A) will be used
Equality Operator
Logical Operators
Relational & Logical Operators
• Statements which use relational or logical operations yield
either true or false as outcome
• Relational or logical operations return
• 0 for false int a=7 Expression Interpretation Value
• 1 for true int b=5
a<b false 0
float f = 6.5
char k =‘w’ f>4 true 1
k ==119 true 1
k != ‘s’ true 1
(a+f) <= 10 false 0
Bitwise Operator
• All data items are stored in a computer memory as a sequence of bits
(0 and 1)
• There are several applications which need manipulation of these bits
• To perform this C provides six bitwise operations
• They work with int & char type
• Cannot work with float
Bitwise Operator - Results
Bitwise AND & : Bitwise XOR ^:
• 1 if both bits are 1 • 1 if both bits are different
• Otherwise 0 • Otherwise 0
Bitwise complement ~:
Bitwise OR | is: • Reverses state of each bit
• 1 if one of bits is 1
• Otherwise 0
Bitwise Operator
• Assume A = 60 and B = 13 in binary format, they will be as follows −
• A = 0011 1100
• B = 0000 1101
A 0 0 1 1 1 1 0 0
B 0 0 0 0 1 1 0 1
A&B 0 0 0 0 1 1 0 0
A|B 0 0 1 1 1 1 0 1
A^B 0 0 1 1 0 0 0 1
Bitwise Operator
Bitwise complement ~ operator
A 0 0 1 1 1 1 0 0
~A 1 1 0 0 0 0 1 1
Bitwise Operator
Left shift operator:
• Represented by <<
• Two operands, Eg: A<<2
• Bits of first operand will be shifted to left by number specified by
second operand
A 0 0 1 1 1 1 0 0
1 1 1 1 0 0
A<<2
1 1 1 1 0 0 0 0
Bitwise Operator
Right shift operator:
• Represented by >>
• Two operands, Eg: A>>2
• Bits of first operand will be shifted to right by number specified
by second operand
A 0 0 1 1 1 1 0 0
0 0 1 1 1 1
A>>2
0 0 0 0 1 1 1 1
Assignment Operator
• Assignment operators are used to assign value of an expression
to one or more identifiers
• Eg: x = y + 3;
• = Assignment operator
Assignment Operator
Conditional Operator
• Conditional operators are used to test the relationship between variables
• Used along with relational operators
• An expression that makes use of the conditional operator is called a
conditional expression
• Takes 3 inputs as operands. Evaluate 2nd or 3rd expression based on the first
conditional expression
Associativity
• The order in which consecutive operations within the same
precedence group are carried out is known as associativity
Precedence & Associativity
STRUCTURE OF C
Structure of C Program
The basic format of a C program:
Structure of C Program
Documentation section:
• Is the part of the program where the programmer gives the details associated
with the program
• Usually the name of the program, the details of the author, time of coding etc.
• These comment lines include the details the user would like to use later
Declaration
Execution
Structure of C Program
Link Section
• This part of the code is used to declare all the header files that will be used in the
program
• Link section provides instructions to compiler to link functions to system library
• Eg: #include<stdio.h> : For standard input & output functions
main ()
{
printf (“ Hello”);
}
Structure of C Program
Link Section
• This part of the code is used to declare all the header files that will be used in the
program
• Link section provides instructions to compiler to link functions to system library
• Eg: #include<stdio.h> : For standard input & output functions
Declaration
Execution
Structure of C Program
Definition Section
Section which defines values of all symbolic constants
Eg: #define PI=3.14, #define X = 20
Structure of C Program
Global declaration Section
• There are some variables that are used in more than one function
• Such variables are called global variables
• These are declared in the global declaration section that is outside of all
the functions
• Global variables hold their values throughout the program and they can
be accessed inside any of the functions defined for the program
• This section also declares all the user-defined functions
• Eg: int age;
Structure of C Program
Main Function Section
• Every C-programs must have one main ()
function main()
{
• Execution of C program starts with main () Declaration
int a=10;
• Contains two parts, printf (" %d", a);
Executable
1. Declaration part }
2. Executable part
• These two parts comes between set of
opening & closing curly braces
• Closing curly brace indicate end of function
Documentation
Link
Declaration
Execution
Structure of C Program
Sub Program Sections
• All the user-defined functions are
defined in this section of the
program
• User defined functions are generally
placed immediately after main
function, although they may appear
in any order
Structure of C Program
ARRAY
MODULE 3
ARRAY
Array is an ordered list of homogeneous data elements
that share a common name
ARRAY
Array is an ordered list of homogeneous data elements
that share a common name
• Eg: int number [5]
• number represents an array which can hold 5 elements
• All elements must be integer data-type (in this example)
• Computer reserves five storage locations:
number [0] -------- Indicate 1st element in the array
number [0]
number [1] -------- Indicate 2nd element in the array
number [1]
number [2] -------- Indicate 3rd element in the array
number [2] number [3] -------- Indicate 4th element in the array
number [3] number [4] -------- Indicate 5th element in the array
number [4]
ARRAY
§ Each element in an array is referenced by a subscript OR index
enclosed in a pair of square brackets
§ This subscript indicates the position of an individual element in an
array
Example: To store marks of 5 subjects in an array
(21.5,22.0,23.5,24.5,25.0)
float mark [5];
mark [0] = 21.5
mark [1] = 22.0
mark [2] = 23.5
mark [3] = 24.5
mark [4] = 25.0
Classification of Array
Arrays are classified into two types:
1. One dimensional arrays
2. Multi dimensional arrays
• Two-dimensional, Three-dimensional, ………. n-dimensional
array
• The dimensionality of an array is determined by the number of
subscripts present in an array
• If there is only one subscript it is called one dimensional array
• ARRAY [ ]
• If there are two subscripts, then it is called two dimensional array
• ARRAY [ ][ ]
Declaration of Array
§ An array must be declared before they are used in the program
Syntax for declaring one-dimensional array:
datatype Array_name[size];
Datatype: Type of element contained in array - int, float, char etc.
Size: Number of elements that can be stored in an array
Eg1: int age [20];
§ Declares age as an array to contain maximum of 20 integers
Declaration of Array
Eg2: char name [10]; ‘W’
§ Declares name as a character array (string) to ‘E’
contain maximum of 10 characters ‘L’
§ Reading string “WELL DONE” to array name ‘L’
‘’
§ Each character of the string is treated as an element
‘D’
of array and stored as:
‘O’
§A character string will be terminated with an ‘N’
additional null character ‘\0’ ‘E’
‘\0’
§Hence while declaring character arrays, we must
allow one extra element space for null terminator
Declaration of Array
Rules for subscript:
1. Each subscript must be an unsigned positive
integer or expression
2. Subscript of subscript is not allowed
3. C does not perform bounds checking. Therefore
the maximum subscript appearing should not
exceed the declared
4. In C, subscript value ranges from 0 to (size - 1). i.e,
if the size is 10, first subscript is 0, second is 1
and last is 9.
Initialising One Dimensional
Initialising is the process ofArray
assigning value to a variable
§ After array is declared, its elements can be initialised
§ An array can be initialised at:
§ Compile time & Run time
Compile time initialisation
datatype Array_name[size] = { List of values};
Eg: int number [5] = { 11, 12, 13, 14, 15};
§ Number of elements initialised may be less than declared size.
§ In such cases, remaining elements will be initialised to zero
Run time initialisation
Can use read function scanf to initialise an array
One Dimensional Array
How to accept n integers and store them in an array
int n, i, number[20];
printf (“Enter the size of Array\n”);
scanf(“%d”,&n);
printf (“Enter the elements one by one\n”);
for(i=0, i<n; i++)
{
scanf(“%d”, &number[i]);
}
One Dimensional Array
How to print n integers stored in an array
G O O D \0 \0 \0 \0 \0 \0
Reading & Writing Strings
Strings can be entered and displayed using following functions:
• scanf()
• gets()
• getchar()
• printf()
• puts()
• putchar()
Reading String
scanf function
scanf function can be used with %s format specifier
Example: char message[10];
scanf(“%s”, message);
• While using scanf for strings & is not required before variable
name
• scanf function terminates its input on the first white space (blank,
tab, newline etc.)
• Eg: If we enter “WELL DONE”, only “WELL” will be read to the
array address
Reading String
getchar function
• Can be used to read a single character
• Can be used repeatedly to read successive single characters
from input and place them in a character array
• Thus an entire line of text can be read and stored in an array
• No parameter required
char ch;
ch = getchar();
Reading String
getchar function char line[30], ch;
To enter a line of text int i = 0;
printf("Enter line: ");
while(ch != '\n') // terminates entry with newline
{
ch = getchar();
line[i] = ch;
i++;
}
line[i] = '\0'; // inserting null character at end
printf("Line is: %s", line);
Reading String
gets function
• Another convenient method to input string with white spaces
• Reads characters from keyboard until a newline is encountered
and then adds a null character
char line [10];
gets (line);
Writing String
printf function
• %s format specifier to be used
• printf(“%s”, name);
putchar function
• To output values of character variables
• putchar (ch) ----------- requires one parameter
puts function
• char line [10];
• gets (line);
• puts (line);
/*Program to enter a string and count number of characters*/
void main () Index ch count
{ 0 G 1
char text[20]; 1 O 2
int count =0, i; 2 O 3
printf("Enter the text\n"); 3 D 4
gets(text); 4 \0
Function Action
strcat() Concatenates (join) two strings
strcmp() Compares two strings
strcpy() Copies one string over another
strlen() Finds length of a string
strcat() Function
strcat function joins two strings together
Syntax: strcat (string1, string2);
• When this function is executed, string2 will be added to string1
• Done by removing the null character at the end of string1 and
placing string2 from that location
• Text in string2 will remain unchanged
• Size of string1 must be large enough to accommodate final string
strcat() Function
strcat function joins two strings together
Syntax: strcat (string1, string2);
• Function can also join a string constant to a string variable
• strcat(string1, “GOOD”);
• Nesting of strcat functions is also possible
• strcat((strcat(string1, string2), string3)
strcmp() Function
• strcmp function compares the strings in arguments
• Stntax: strcmp(string1, string2);
• If are equal give value 0
• If not equal give the numeric difference between first non-
matching character
• string1 & string2 may represent string variables or string
constants
• strcmp(text1, text2);
• strcmp(text1, “good”);
• strcmp(“well”, “done”);
strcmp() Function
• strcmp function compares the strings in arguments
• Stntax: strcmp(string1, string2);
• Example:
• strcmp(“there”, “there”); ------- return value 0
• strcmp (“their”, “there”); -------return -9, ASCII value difference
between “i” and”r”
• If the return value is negative, string1 is alphabetically above
string2
strcpy() Function
• strcpy is a string assignment operator
• Stntax: strcpy (string1, string2);
• Assigns contents of string2 to string1
• string1 & string2 may represent string variables or string
constants
• Sixe of string1 should be large enough to copy contents of
string2
strlen() Function
• strlen function counts and returns number of characters in a
string
• N= strlen (string);
• N is an integer variable, will be assigned with length of string
• Counting ends at the first null character
• Example: strlen (“well done”) ---------- 9
strstr() Function
• strstr function locates a substring in a string
• Syntax: strstr (s1,s2);
• Searches string s1 to check whether s2 is contained in it
• If yes, will return location of first occurrence
• If no, will return null pointer
• Example:
if(strstr(s1,s2) == null)
printf(“substring is not found”);
else
printf(“s2 is a substring of s1”);
Other string handling
functions
• strncat (s1, s2, n) joins first n characters of s2 to the end of s1
• strncpy (s1, s2, n) ---- copies first n characters of s2 into s1
• Null character(\0) should be supplied at the end
• strncmp (s1, s2, n) compares leftmost n characters of s1 to s2
• Return 0 if equal, -ve if s1 substring is less than s2
FUNCTION IN
C
MODULE 4
Contents
1. Modular programming
2. Functions
3. Recursion
4. Structure
5. Union
6. Storage classes
Modular Programming
Modular Programming is the process of subdividing
a computer program into separate sub-programs
C functions classifications
1. Library functions
2. User-defined functions
Library Functions
• Each library function performs a predefined operation
compilers
User-defined functions
• These are written by the programmer for carrying out certain
tasks
Elements of user-defined function
1. Function declaration
2. Function call
3. Function definition
Need of Functions
§Large and difficult program can be divided in to sub
programs and solved
§Task which has to be performed repeatedly at different
locations in a program
§Function avoids this repetition or rewriting over and
over
Function Elements
In 'C' programming functions are divided into three
components :
1. Function definition
2. Function call
3. Function declaration
1. Function Declaration
§Function declaration means: we specify the name of a
function (the sub-program) that we are going to use in the
program - like a variable declaration
• All functions in a C program must be declared, before they
are called
§A function declaration is also called “Function Prototype”
1. Function Declaration
Format of function declaration:
Return-datatype Function-name (Parameter list) ;
Function declaration (function prototype) consists of four
parts:
1. Function type (return type): data type of the value function
returned back to the calling function
2. Function name
3. Parameter list
4. Terminating semicolon
1. Function Declaration
1. Function Declaration
Examples of function declaration
§int add (int a, int b);
§int add (int, int);
§add (int, int);
§void add (int, int);
1. Function Declaration
Parameter list:
1. Parameter list must be separated by commas
2. The type of parameter must be same in the function definition, in
number and order
3. If the function has no formal parameters, the list is written as void
4. The return type must be void if no value is returned
5. The return type is optional, when the function returns int type
data
2. Function Call
• A function call means calling a function when it is required
in a program
• When a function is called, it performs an operation for
which it was designed
• Example: add(4,5);
2. Function Call
• A function is called by using the function name followed by list of
parameters (or arguments)
Example:
main ()
{
int s;
s = add (3,5); ---------- function call (sends two values 3 & 5 to function)
printf(“ sum = %d”, s);
}
3. Function Definition
The changes made to the dummy Any modifications made to the values in the
variables in the called function called function, original values will get changed
3 have no effect on the values of with in calling function
actual variables in the calling
function
/* pass by value*/
void main()
{
void pass_value (int, int);
int n1, n2;
n1 = 5;
n2 = 10;
pass_value(n1, n2);
printf(" n1=%d, n2=%d\n",n1, n2); a = 7, b = 12
}
void pass_value(int a, int b) n1 = 5, n2 = 10
{
a=a+2;
b = b+2;
printf(" a=%d, b=%d\n", a,b);
}
Recursion
• In ‘C’ Recursion is the programming technique by which a
function calls itself
Here, st1 & st2 are structure variables having four fields for student
Similarly, s[0], s[1],…s[9]
DECLARING STRUCTURE
Method 1 : VARIABLES
Method 2:
struct student struct student
{
char name [20]; {
int roll_no.; char name [20];
char branch [10]; int roll_no.;
float total_mark;
}; char branch [10];
void main() float total_mark;
{ } st1, st2;
struct student st1, st2;
}
Here, st1 & st2 are structure variables having four fields for student
STRUCTURE -
• A structureINITIALISATION
variable can also be initialized in the way as any
other data type in C
struct student
Structure: Student 1
{
name abc
char name [20];
roll_no 10
int roll_no.;
branch Civil
char branch [10];
float total_mark; total_mark 400
} st1 = {“abc”, 10, “civil”, 400};
OR struct student st1 = { “abc”, 10, “Civil”, 400} ;
ACCESSING A STRUCTURE
• Each member of the structure is accessed with the dot operator (.)
• To access a particular member, dot operator must be placed
between the name of structure and name of structure member
struct student Example:
{
st1.name
char name [20];
int roll_no.; st2.name
char branch [10]; st1.roll_no.
float total_mark; st2.roll_no
} st1, st2;
void main()
{
struct book
{
int num;
char author[20];
float price;
};
struct book b1;
printf("Enter the book number\n");
scanf("%d",&b1.num);
printf("Enter the name of author\n");
scanf("%s",b1.author);
printf("Enter the price of book\n");
scanf("%f",&b1.price);
printf(“\n Book no. :%d",b1.num);
printf(“\n Author :%s\n",b1.author);
printf(“\nPrice :%f\n",b1.price);
ARRAY OF STRUCTURES
§ An array of structures in C can be defined as the collection of
multiple structure variables where each variable contains
information about different entities
§ The array of structures can be considered as a collection of
structures
§ Consider the case, where we need to store the data of 10
students
ARRAY OF STRUCTURES
struct student
{
char name [20];
int roll_no.;
char branch [10];
float total_mark;
} s[10];
PASSING STRUCTURES TO
FUNCTIONS
• Structures can be passed as an argument to a function
Method 1
• Individual elements of structures can be passed to functions as
actual arguments
Method 2
• Entire structure can be passed by passing a copy to the function
Method 3
• Concept of pointers can be used to pass the structure
Method
/* structure passed to function: method 1, passing individual elements*/
void main()
{
1
void output (int, char[], float); // function declaration
struct book // structure declaration
{
int number;
char author [10];
float price;
} b1 = {11, “abc",100}; // structure variable declaration
output (b1.number, b1.author, b1.price); //passing variables
}
void output (int n, char a[],float p )
{ printf("%d %s %f", n, a, p);
}
void main()
Method
{
struct emp
{
// structure declaration 2
char name[10];
int id;
float salary;
}e1;
void display (struct emp); // function declaration
printf("Enter name, id and salary of employee1\n");
scanf("%s %d %f",e1.name, &e1.id, &e1.salary);
display (e1);
}
void display(struct emp e1)
{
printf("Employee name: %s", e1.name);
printf("Employee id: %d", e1.id);
printf("Employee salary: %f",e1.salary);
}
UNION
UNION
• Union is also a collection of heterogeneous items
• Union is a concept similar to structure and follow the same syntax
as structure
• But differ from structure in terms of storage
• In structures, each member has its own storage location,
whereas all the members of a union use the same location
• A union can store only one member at a time
• Unions, hence can be used to save memory, as only one of its
members can be accessed at a time
UNION
Syntax: Example:
union data
union union_name {
{ int i;
float f;
datatype1 member1;
char str[20];
datatype2 member2; };
… void main ()
… {
}; union data data1, data2;
}
UNION
• When a union is created, the compiler allocates a storage space
that is large enough to hold the largest variable type in the union
union data
• In this case, float requires more space than
{
others (4 bytes) Hence four bytes is allocated to
int i; union data.
float f; • We can store either an integer, a float or a
char c; character at any one time, but not all of them
}; together.
• This declares a variable code of type union data. The union contains
three members, each with different data type
• However, we can use only one of them at a time
#include<stdio.h>
#include<conio.h>
void main()
{
union number // union declaration
{
int n;
char c;
float f;
};
union number x; // variable declaration
x.n = 11;
x.c = 's';
x.f = 1.1;
printf("Value of n = %d\n",x.n);
printf("value of c = %c\n",x.c);
printf("value of f = %.1f\n",x.f);
}
STORAGE CLASS
STORAGE CLASS
In C language, each variable has a storage class which decides
the following things:
• Scope – over what region of a program the value of variable
would be available
• Default initial value - if we do not explicitly initialize that
variable, what will be its default initial value
• Lifetime of that variable - for how long will that variable
exist
STORAGE CLASS
The following variable storage classes are most relevant to
functions:
1. Automatic Variables
2. External or Global Variables
3. Static Variables
4. Register Variables
AUTOMATIC VARIABLES
§ Automatic variables are declared inside a function in which they are
to be utilized
§ They are created when the function is called and destroyed
automatically when the function is exited, hence the name
automatic
§ Automatic variables are therefore private or local to the function in
which they are declared
§ Since these are local to a function, are also referred to as local or
internal variables
AUTOMATIC VARIABLES
§ We may also use keyword auto to declare automatic variables
§ Eg: auto int number
• A variable declared inside a function without storage class
specification is, by default, an automatic variable
Scope: Variable defined with auto storage class are local to the
function block inside which they are defined
Life time: Till the end of the function block where the variable is
defined
Example: Automatic
void main()
variable
{
int a=10, b=5;
int s = a + b;
} // a,b,s are variables declared in main function – automatic
variables, local variables in main function
EXTERNAL VARIABLES
§ External variables are those which are both alive and active
throughout the entire program
• They are also known as global variables
• Global variables can be accessed by any function in the
program
• External variables are declared outside a function
Example: External
variable
#include<stdio.h>
int a=10;
void main()
{ • a is a global variable
void display (void);
available to all functions
clrscr();
int s = a+10; • s is a variable local to main
printf("s = %d\n",s); function
display();
}
void display(void)
{
printf("a from function named display = %d", a);
}
STATIC VARIABLES
• The value of static variables persists until the end of the program
• A variable can be declared static using the keyword static
• Eg: static int x; static float y;
• A static variable can either be internal or external depending
upon the place of declaration.
–Scope of internal static variable remains inside the function in
which it is defined
–Scope of external static variables remain restricted to the scope
of file in which they are declared
void add(void) Example: Static
variable
main ()
{ int i;
for (i=1;i<=3;i++)
add(); output
} x=1
void add() x=2
{ x=3
static int x = 1;
printf (“%d\n”,x);
x++;
}
REGISTER VARIABLES
• Register variables inform the compiler to store the variable in CPU
register instead of memory
• Register variables have faster accessibility than a normal variable
• If frequently used variables are kept in register – will lead to faster
execution
• But only a few variables can be placed inside registers
• One application of register storage class can be in using loops,
where the variable gets used a number of times in the program,
in a very short span of time
Syntax :
• register int number;
REGISTER VARIABLES
• Since only a few variables can be places in the register, it is
important to carefully select register variables
• However, C will automatically convert register variables into non
register variable once limit is reached
FILE OPERATIONS
FILE
A file is a space in a memory where data is stored.
1. Text files
2. Binary files
FILE management in C
§All files should be declared as FILE datatype
§To process a file, it should be opened
§Once opened – the data in the file can be read, added, or
fresh data can be written
§While opening the file ---- the purpose also must be
specified
§For reading, writing or appending
OPENING A FILE
General format for declaring and opening a file:
FILE *fp;
fp = fopen(“filename”, “mode”);
§1st statement: declares variable fp as a pointer to datatype FILE
§2nd statement:
§ Opens a file named filename and assigns to FILE type pointer fp
§ Specifies the purpose of opening this file
OPENING A FILE
General format for declaring and opening a file:
FILE *fp;
fp = fopen(“filename”, “mode”);
Value Meaning
SEEK_SET or 0 Beginning of file
SEEK_CUR or 1 Current position
SEEK_END or 2 End of file
fseek()
ftell ()
§ftell() function returns the current position of file position
indicator relative to the beginning of file
§Will return the number of bytes from the beginning of the
file
Format: ftell(fx) ----fx is the file pointer
FILE *fx
int a[10]
fread (a, sizeof(int), 5, fx);
• Would read first 5 integers from the file and stores in variable a
fread ()
Read a structure variable
struct student
{
char name[10];
int roll;
float marks;
};
struct student student1;
fread(&student1, sizeof(student1), 1, fp);
fwrite ()
fwrite( ptr, int size, int n, FILE *fp );
Example:
int quantity, *p, n;
quantity = 100;
p = & quantity;
n = *p
POINTERS AND 1D ARRAYS
Elements X[0] X[1] X[2] X[3] X[4]
Value 1 2 3 4 5
Address 1000 1002 1004 1006 1008
• p = x ------If p is declared as a pointer to point to array X
• Therefore, p = &x[0]
p = &x[0] = 1000 *(p + i) OR *(x + i)
p + 1 = &x[1] = 1002
represents
p + 2 = &x[2] = 1004
p + 3 = &x[3] = 1006 element x[i]
p + 4 = &x[4] = 1008
void main()
{
Read & print a
int n, arr[20], i, *p; 1D array
p = arr; // p assigned address of first element
printf("Enter size of array\n");
scanf("%d", &n);
printf("Enter elements of array\n");
for (i=0;i<n;i++)
scanf("%d",(p+i)); // (p+i) equivalent to &arr[0]…
printf("Printing array elements using pointer\n");
for(i=0;i<n;i++)
{
printf("\n%d",*p);
p++;
}
}
2D
Arrays
}
}
for (i=0;i<row;i++) // PRINTING SUM
{
for(j=0;j<col;j++)
{
printf("%4d", *(*(s+i)+j) );
}
printf("\n");
int a; // Variable declaration
int *p; // Pointer variable declaration
p = &a; // Pointer initialization---- stores address of a in pointer p
POINTERS AND 1D ARRAYS
Elements X[0] X[1] X[2] X[3] X[4]
Value 1 2 3 4 5
Address 1000 1002 1004 1006 1008
• p = x ------If p is declared as a pointer to point to array X
• Therefore, p = &x[0]
p = &x[0] = 1000 *(p + i) OR *(x + i)
p + 1 = &x[1] = 1002
represents
p + 2 = &x[2] = 1004
p + 3 = &x[3] = 1006 element x[i]
p + 4 = &x[4] = 1008
POINTERS AND 2D ARRAYS
An element in a two dimensional array can be represented by:
*( * (p +i ) + j) OR *( * (a +i ) + j)
Address of the element:
* (a +i ) + j
Pointers and Strings
§Strings are character arrays and are declared and
initialised as:
§char str [6] = “hello”; ------ other formats discussed in module 3
Element str[0] str[1] str[2] str[3] str[4] str[5]
Value h e l l o \0
Address 1000 1001 1002 1003 1004 1005