C Notes
C Notes
Introduction to Computers:
What is Computer?
The computer is an advanced electronic device used to process data that is supplied by the user
and gives result to the user. The word Computer came from the Greek word Compute. The Compute
means calculation.
Advantages of computers
1. Store the large amount of data.
2. Processing speed is very high
3. Excellent Data accuracy
4. Decision making capability.
Explain characteristics of Computer?
Characteristics of computer:
1. Speed: The computer is first treated as a high-speed calculator. I will carry out instructions
at a very high speed, since computer is an electronic device, all its operations can be
performed in terms of microseconds and nano seconds. A powerful computer can calculate 3
million calculations per second. Microsecond = 10 –6 seconds; nano second = 10 –9 seconds.
The speed of a computer is calculated in terms of micro and nano seconds.
2. Accuracy: Computers perform calculations with 100% accuracy. Errors may occur
due to data inconsistency or inaccuracy
3. Storage: Storage is nothing but memory of a computer. A computer has built-in
memory called primary memory where it stores data. Secondary storage are removable
devices such as CDs, pen drives, etc., which are also used to store data s. The
secondary memory is also known as auxiliary.
4. reliability: computer carry out instructions with high speed and reliability i.e., it will execute
all the statements very fast and without any errors. Computer will perform only its task. But it
will never do any mistake.
5. versatility: computer seem capable of performing any task, provided that the task can be
reduced that the task can be reduced to a series of logical steps i.e., nothing but writing a
program for the task.
6. Diligence: A computer does not suffer from tiredness and lack of concentration . A computer
can perform millions of tasks or calculations with the same consistency and accuracy It
shows the same accuracy and speed to perform millions instructions.
Define a Algorithm?
The stepwise description of problem solution is called algorithm.
Ex: Step1: start
Stept2: a=10
Step3: b=20
Step4 c=a+b
Step5: PRINT C
Step6: stop.
Define a Flow-chart?
Flow chart is a diagrammatical representation of problem solution. Illustrates the sequences of operation,
when the operation is mentioned on the boxes, that boxes will be connected with arrows.
Define a program?
Pure computer based solution. Program means set of instructions. EX:
Satyanarayana__________________________________________________________________________________ 1
Computer number system:
The technique to represent and work with numbers is called number system. Decimal number
system is the most common number system. Other popular number systems include binary number
system, octal number system, hexadecimal number system, etc.
1. Decimal Number System
Decimal number system is a base 10 number system having 10 digits from 0 to 9. This means that any
numerical quantity can be represented using these 10 digits. Decimal number system is also a positional
value system. This means that the value of digits will depend on its position. Let us take an example to
understand this.
Say we have three numbers – 734, 971 and 207. The value of 7 in all three numbers is different−
In digital systems, instructions are given through electric signals; variation is done by varying the
voltage of the signal. Having 10 different voltages to implement decimal number system in digital
equipment is difficult. So, many number systems that are easier to implement digitally have been
developed. Let’s look at them in detail.
Each binary digit is also called a bit. Binary number system is also positional value system, where each
digit has a value expressed in powers of 2, as displayed here.
In any binary number, the rightmost digit is called least significant bit (LSB) and leftmost digit is
called most significant bit (MSB).
Satyanarayana__________________________________________________________________________________ 2
And decimal equivalent of this number is sum of product of each digit with its positional value.
= 16 + 8 + 0 + 2 + 0
= 2610
3. Octal Number System
Octal number system has eight digits – 0, 1, 2, 3, 4, 5, 6 and 7. Octal number system is also a
positional value system with where each digit has its value expressed in powers of 8, as shown here −
Decimal equivalent of any octal number is sum of product of each digit with its positional value.
= 448 + 16 + 6
= 47010
4. Hexadecimal Number System
Octal number system has 16 symbols – 0 to 9 and A to F where A is equal to 10, B is equal to 11 and
so on till F. Hexadecimal number system is also a positional value system with where each digit has its
value expressed in powers of 16, as shown here −
Decimal equivalent of any hexadecimal number is sum of product of each digit with its positional value.
= 1023410
Satyanarayana__________________________________________________________________________________ 3
Binary arithmetic’s:
1. Binary Addition
There are four steps in binary addition, they are written below
0+0=0
0+1=1
1+0=1
example of binary arithmetic clearly explains the binary addition operation, the carried 1 is shown on the
upper side of the operands.
2. Binary Subtraction
0–0=0
1–0=1
1–1=0
3. Binary Multiplication
0×0=0
1×0=0
0×1=0
4. Binary Division
Binary division is an important but often overlooked part of binary arithmetic.
Rules followed by binary subtraction.
101)11010(101
Satyanarayana__________________________________________________________________________________ 4
-101
110
-101
1
How are signed and unsigned integers stored? With suitable examples .
Variables such as integers can be represent in two ways, i.e., signed and unsigned. Signed
numbers use sign flag or can be distinguish between negative values and positive values.
Whereas unsigned numbers stored only positive numbers but not negative numbers.
Number representation techniques like: Binary, Octal, Decimal and Hexadecimal number
representation techniques can represent numbers in both signed and unsigned ways.
In the Binary System, there are only two symbols or possible digit values, i.e., 0 and 1.
Represented by any device that only 2 operating states or possible conditions. Binary numbers
are indicated by the addition of either an 0b prefix or an 2 suffix.
1. Unsigned Numbers:
Unsigned numbers don’t have any sign, these can contain only magnitude of the number. So,
representation of unsigned binary numbers are all positive numbers only. For example,
representation of positive decimal numbers are positive by default. We always assume that
there is a positive sign symbol in front of every number.
Representation of Unsigned Binary Numbers:
Since there is no sign bit in this unsigned binary number, so N bit binary number represent its
magnitude only. Zero (0) is also unsigned number. This representation has only one zero (0),
which is always positive. Every number in unsigned number representation has only one unique
binary equivalent form, so this is unambiguous representation technique. The range of
unsigned binary number is from 0 to (2n-1).
92= (1x26+0x25+1x24+1x23+1x22+0x21+0x20)10
= (1011100)2
Satyanarayana__________________________________________________________________________________ 5
It’s 7 bit binary magnitude of the decimal number 92.
Example-2: Find range of 5 bit unsigned binary numbers. Also, find minimum and maximum
value in this range.
Since, range of unsigned binary number is from 0 to (2n-1). Therefore, range of 5 bit unsigned
binary number is from 0 to (25-1) which is equal from minimum value 0 (i.e., 00000) to
maximum value 31 (i.e., 11111).
2. Signed Numbers:
Signed numbers contain sign flag, this representation distinguish positive and negative
numbers. This technique contains both sign bit and magnitude of a number. For example, in
representation of negative decimal numbers, we need to put negative symbol in front of given
decimal number.
Representation of Signed Binary Numbers:
There are three types of representations for signed binary numbers. Because of extra signed
bit, binary number zero has two representation, either positive (0) or negative (1), so ambiguous
representation. But 2’s complementation representation is unambiguous representation
because of there is no double representation of number 0. These are: Sign-Magnitude form, 1’s
complement form, and 2’s complement form which are explained as following below.
2.(a) Sign-Magnitude form:
For n bit binary number, 1 bit is reserved for sign symbol. If the value of sign bit is 0, then the
given number will be positive, else if the value of sign bit is 1, then the given number will be
negative. Remaining (n-1) bits represent magnitude of the number. Since magnitude of number
zero (0) is always 0, so there can be two representation of number zero (0), positive (+0) and
negative (-0), which depends on value of sign bit. Hence these representations are ambiguous
generally because of two representation of number zero (0). Generally sign bit is a most
significant bit (MSB) of representation. The range of Sign-Magnitude form is from (2(n-1)-1) to
(2(n-1)-1).
1’s complement:
For example, range of 6 bit 1’s complement form binary number is from (25-1) to (25-1) which is
equal from minimum value -31 (i.e., 1 00000) to maximum value +31 (i.e., 0 11111). And zero
(0) has two representation, -0 (i.e., 1 11111) and +0 (i.e., 0 00000).
2’s complement:
For example, range of 6 bit 2’s complement form binary number is from (25) to (25-1) which is
equal from minimum value -32 (i.e., 1 00000) to maximum value +31 (i.e., 0 11111). And zero
(0) has two representation, -0 (i.e., 1 11111) and +0 (i.e., 0 00000).
Satyanarayana__________________________________________________________________________________ 7
Step 4: Click on Run or press Ctrl + F9 to run the code. Yes, C
programs are first compiled to generate the object code and then
that object code is Run.
Satyanarayana__________________________________________________________________________________ 8
Introduction to C language.
C is a most popular and powerful high level programming language. C was an offspring of the
Basic Combined Programming Language (BCPL) called B, developed in the 1960’s at Cambridge
university. B language was modified by Dennis Ritchie and implemented at Bell laboratories in 1972.
The new language was named C. since it was developed along with the UNIX operating system.
Importance of C.
1. Compiler
2. Robust
3. Efficient and Fast
4. Portable
5. Structured programming language
6. Middle level language
Compiler: Computer software that translates (source code) high-level language into
program into machine-language instructions that can be understood by computer.
The increasing popularity of c is probably due to its many desirable qualities. It is a robust language
whose rich set of built-in functions and operators cab be used to write any complex program.
Programs written in C are efficient and fast. This is due to its variety of data types and powerful
operators. It is many times faster than BASIC.
C is highly portable. This means that C programs written for one computer cab be run on another
with little or no modification. Portability is important if plan to use a new computer with a different
operating system.
Satyanarayana__________________________________________________________________________________ 9
C language is well suited for structured programming, thus requiring the user to think of a
problem in term of function modules or blocks. This modular structure makes program debugging ,
testing and maintenance easier.
Another important feature of C is its ability to extend itself. C is middle level language because it
will understand low level programs and high level language programs.
Documentation section
Linking section
Definition section
Main()
{
declaration part;
executable part;
subprogram section()
{
The documentation section consists of a set of comment lines giving the name the program.
The link section provides instructions to the compiler to link functions from the system
library. The definition section defines all symbolic constants.
There are some variables that are used in more than one function. Such variables are called
global variables and are declared in the global declaration section that is outside of all the functions.
Every C program must have one main() function section. This section contains two parts
declaration part and executable part. The declaration part declares all the variables used in the
executable part. There is at least one statement in the executable part. These two parts must
Satyanarayana__________________________________________________________________________________ 10
appear between the opening and the closing braces. The program execution begins at the opening
brace and ends at the closing brace.
The subprogram section contains all the user defined functions that are called in the main
function.
C Language is rich in its data types. The variety of data types available allow the programmer to
select the type appropriate to the needs of the application as well as the machine. ANSI C supports
four classes of data types
The primary data type means fundamental data types. They are
int
long int
float
double
long double
char
int:
int is a short form of integer. The Integer variable has a limited value. They range from –32768 to
32767
syntax:
Long int:
In order to provide some control over the range of numbers and storage space, C has three classes
of integer storage, namely short int, int and long int, in both signed and unsigned forms. We declare
long and unsigned integers to increase the range of values.
Character types:
A single character can be defined as a character(char) type data. Characters are usually stored in 8
bits of internal storage.
In a passage of text, individual words and punctuation marks are called tokens. Similarly, in a c
program the smallest individual units are known as c tokens. C has six types of tokens as shown
below
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Operators
6. Special Symbols.
Every C word is classified as either a keyword or an identifier. All key words have fixed meaning and
these meaning cannot be changed. Keywords serve as basic building blocks for program statements.
The ANSI C supports 32 keywords. ALL keywords must be written in lowercase.
Identifiers refer to the names of variables, functions and arrays. These are user defined names and
consist of a sequence of letters and digits, with a letter as a first character.
Constants in C refer to fixed values that do not change during the execution of a program. C
supports several types of constants as
Numeric constants like numbers as 44, 44.44,-66 etc
String constants like characters as name of the person and address of the person. Strings must be
used with in codes.
Satyanarayana__________________________________________________________________________________ 12
Example:
X=a*b-c
Y=b/c*a;
Satyanarayana__________________________________________________________________________________ 13
Category Operator Associativity
Implicit Conversion
Implicit conversion is the simplest type of conversion. This type of conversion is type-safe and no
loss of data happens during conversion. T
For Example, we can directly use implicit conversion if the value that needs to be stored in another
variable can fit directly without data loss. Let’s say we have an “integer” value and we want to pass
that value to a “long”.
int i = 75;
Satyanarayana__________________________________________________________________________________ 14
long j = i;
Explicit Conversion
Explicit conversion or cast is a process of passing information to the compiler that the program is
trying to perform conversion with the knowledge of possible data loss.
For Example, if we are converting a higher numeric value into a lower one.
double d = 75.25;
int i;
i = (int)d;
Example: int a;
Scanf(“%d”,&a);
getcha(): this input statement used read single character from keyboard. The general
form of getchar() as follows
Syntax: variable=getchar();
Example: char ch;
Ch=getchar():
gets(): this input statement read strings.example
Char str[10];
Gets(str)
Output statements:
Output statements means write data on screen or console. The following are output
statement in c they are
1. Printf()
2. Putchar()
3. Puts()
Printf() is a output statement in c. this statement write variable data on screen. The
form of the printf() statement as follows
Syntax: printf(“formatspecifier”,variable)l
Examples:
Satyanarayana__________________________________________________________________________________ 15
Int a=10;
Printf(“%d”,a);
If you want to pass command line arguments then you will have to define the main() function with two
arguments. The first argument defines the number of command line arguments and the second argument
is the list of command line arguments.
Example:
Int main(argC,argV)
argv[argc] is a null pointer.
argC means argument Counter
argV means argument Vector
Always passed to the main() function.
Command Line Arguments are passed by the user from the terminal.
argv[0] prints the name of the program.
UNIT-II:
An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations. Operators are used in programs to manipulate data and variables. they usually form
a part of the mathematical of logical expressions.
Arithmetic operators:
C provides all the basic arithmetic operators like addition, subtraction, multiplication, division and
remainder.
Symbols: + , -, *, /, %
Relational operators:
The <, >, <=, <= and == are Relational operators
We often compare two quantities, and depending on their relation take certain decisions. Example
we may compare the age of two persons or price of two item and so on. These comparisons cab be
done with the help of relational operators. We have already used the symbol ‘<’ meaning less than.
An expression such as
Ex:
a<b OR age>20
Logical operators:
In addition to the relational operators, C has the following three logical operators
The logical operators && and || are used when we want to test more than one condition and make
decisions. An example is
Assignment Operators:
Assignment operators are used to assign the result of an expression to a variable. We have seen
the usual assignment operator ‘=’. In addition, c has a set of shorthand assignment operators of the
form
syntax:
Variable Operator=exp:
Ex:
A += B this is a same as A = A+B
C has two very useful operators not generally found in other languages. These are the increment
and decrement operators
++ and --
the operator ++ adds 1 to the operand while – subtracts 1. Both are unary operators and take the
following form
Satyanarayana__________________________________________________________________________________ 17
pre decrement --a
post decrement a—
Conditional operators:
A ternary operator pair “?:” is available in C to construct conditional expressions of the form
if (a>b)
x = a;
else
x = b;
Bit wise operators:
C has a distinction of supporting special operators known as bit wise operators for manipulation
of data at bit level. These operators are used for testing the bits or shifting them right or left. Bit
wise operators may not be applied to float or double. They meaning as follows
The sizeof is a compile time operator and when used with an operand. It return the
Number of bytes the operand occupies.
Multiple IF or If Ladder:
There is another way of putting its together when multi path decisions are involved. A multi path
decision is a chain of its in which the statement associated with each else is an IF. It takes the
following general form.
Syntax:
IF (Condition-1)
Statement-1;
Else IF (Condition-2)
Statement-2;
Else IF(Condition-3)
Statement-3;
Else IF(Condition-4)
Statement-4;
Else
Statement-5;
This construct is known as the else if Ladder. The conditions are evaluated from the top, downwards.
As soon as a true condition is found, the statement associated with it is executed and the control
terminated from the condition.
Switch statement:
We have seen that when one of the many alternatives is to be selected, we can design a program
using if statements to control the selection. However, the complexity of such program increases
dramatically when the number of alternatives increases. The program becomes difficult to read and
follow. At times it may confuse even the person who designed it. Fortunately , c has a built-in multi
way decision statement tests the value of a given variable against a list of case values and when a
match is found , a block of statements associated with that case is executed. The general form of
the Switch statement is as shown below.
Switch(expression)
Satyanarayana__________________________________________________________________________________ 19
{
case value1:
block-1;
break;
Looping Control statement:
Loop refers to the repeated number of times until the condition will be true. The C language provides
for three loop constructs for performing loop operations. They are
1. While
2. For
3. Do.. While
The simplest of all the looping structures in C is the While statement. We have used while in
many of out earlier programs. The basic format of the while statement is
While (condition)
{
body of the loop;
}
The while is an entry controlled loop statement. The test-condition is evaluated and if the
condition is true, then the body of the loop is executed. After execution of the body, the test
condition is once again evaluated and if it is true. The body is executed once again. This process of
repeated execution of the body continues until the test condition finally becomes false and the
control is transferred out of the loop.
The body of the loop may have one or more statements. The braces are needed only if the
body contains two or more statements.
Ex: print 1 to 10 number through c program
Main()
{
Int i=1;
While (i<-10;i++)
{
Printf(“%d”,I;
I++;
}
}
Main()
{
Int i=1;
Do
{
Printf(“%d”,i);
I++;
}while(i<=10);
For Statement:
The For loop is another entry controlled loop that provides a more concise loop control structure.
Syntax
For(initialozation;test condtion;increment)
{
body of the loop
}
Initialization of the control variables is done first, using assignment statements such as I=1 and
count=0.
The value of control variable is tested using the test condition. When the body of the loop is
executed, the control is transferred back to the increment using an assignment statement such as
I=I+1.
Ex:
Main()
{
For(i=1;i<=10;i++)
Printf(“%d”,i);
}
jumps in Loops:
Loops perform a set of operations repeatedly until the control variable fails to satisfy the test. A
program loop written for reading and testing the names a 100 times must be terminated as soon as
the desired name is found. C permits a jump form one statement to another with in a loop as well as
a jump out of a loop.
Continue;
main()
{
for (int j=0; j<=8; j++)
{
if (j==4)
{
continue;
Satyanarayana__________________________________________________________________________________ 21
}
0 1 2 3 5 6 7 8
Value 4 is missing in the output, why? When the value of variable j is 4, the program
encountered a continue statement, which makes the control to jump at the beginning of
the for loop for next iteration, skipping the statements for current iteration (that’s the
reason printf didn’t execute when j is equal to 4).
Break statement:
A break statement terminates the execution of the loop and the control is transferred to the
statement immediately following the loop. During the discussion on the while loop, an example
average. C that finds the average of sequence of numbers entered by the user was illustrated. The
main part of that program is the following loop.
the break statement is encountered inside a loop, the loop is immediately exited and the program
continues with the statement immediately following the loop.
Ex : main()
{
Int i=1;
For(i=1;i<10;i++);
{
Printf(“%d”,i);
If(i==5)
Break;
}
}
Output : 1 2 3 4 5
Satyanarayana__________________________________________________________________________________ 22
Unit-III:
ARRAYS
An array is a group of (related) similar data items that share a common name. For instance we
can define an array name salary to represent a set of salaries of a group of employees. A particular
value is indicated by writing a number called index number or subscript in brackets after the array
name. For example
Salary[10]
Represents the salary of the 10 th employee. While the complete set of values is referred to as an
array, the individual values are called elements. Arrays can be of any variable type.
The ability to use a single name to represent a collection of items and to refer to an item by
specifying the item number enables us to develop concise and efficient programs. For example a
loop with the subscript as the control variable can be used to read the entire array, perform
calculations and print out the results.
To calculate the average of n values of x, the subscripted variable x i refers to the Ith element
of x. in c single subscripted variable xi can be expressed as
Satyanarayana__________________________________________________________________________________ 23
x[1],x[2], x[3]……… x[n]
The subscripted cab begin with number 0. That is
int number[5]
And the computer reserves five storage locations as shown below
Declaration of arrays:
Like any other variable, arrays must be declared before they are used. The general form of
array declaration is
Type variable name [size]
The type specifies the type of element that will be contained in the array such as int, float or
char and size indicates the maximum number of elements that cab be elements that cab be stored
inside the array. For example
Float height[50]
Int group[10]
Here, we haven't specified the size. However, the compiler knows its size is 5 as we are initializing it
with 5 elements.
Satyanarayana__________________________________________________________________________________ 24
Two Dimensional Arrays:
The two-dimensional array can be defined as an array of arrays. The 2D array is
organized as matrices which can be represented as the collection of rows and columns.
However, 2D arrays are created to implement a relational database lookalike data
structure.
data_type array_name[rows][columns];
example:
int a[3][3];
a is a two dimensional array its have 3 row and 3 columns
A multi-dimensional array
A multi-dimensional array is an array that has more than two dimension. It is an array of arrays;
an array that has multiple levels. The simplest multi-dimensional array is the 2D array, or two-
dimensional array. It's technically an array of arrays, as you will see in the code. A 2D array is also
called a matrix, or a table of rows and columns.
Declaring a multi-dimensional array is similar to 2 dimensions.
This example declares a 3D integer array:
1. int a[3][3][3];
Operation on Arrays in C
There are a number of operations that can be performed on an array which are:
1. Display or Traversal
2. Copying
3. Sorting
4. Insertion
5. Deletion
6. Searching
STRINGS
character strings are often used to build meaningful and readable programs. The common
operations performed on character strings are:
A string variable is any valid c variable name and is always declared as an array. The general form
of declaration of a string variable is
Char String-variable[size];
The size determines the number of characters in the string name. Some examples are:
Char city[10];
Char name[20];
When the compiler assigns a character string to a character array, it automatically supplies a Null
character(‘\0’) at a the end of the string.
The familiar input function scanf can be used with %s format specification to read in a string of
characters. Example
Char name[20];
Scanf(“%s”,name);
Note that unlike previous scanf calls, in the case of character arrays, the ampersand(&) is not
required before the variable name. The scanf function automatically terminates the string that is
read with a null character and therefore the character array should be large enough to hod the input
string plus the null character.
The Strcat function joins two strings together. It takes the following form:
Strcat(string1, string2);
String1 and string2 are character arrays. When the function strcat is executed, stirng2 is appended
to string1. It does so by removing the null character at the end of string1 and placing string2 from
there. The string at string2 remains unchanged. For consider the following three strings.
Part1:
V E R Y ‘\0’
Part2:
Satyanarayana__________________________________________________________________________________ 26
G O O D ‘\0’
Part3:
G R E A T ‘\0’
Will result in
Strcmp() function:
The strcmp funciton compares two strings identified by the arguments and has a value of 0 if they
are equal. If they are not, it has the numeric difference between the first non matching characters in
the strings. It takes the form:
Strcmp(string1, string2);
String1 and string2 may be string variables or string constants. Examples are
Strcmp(name1,name2)
For example
Strcmp(“their”, “there”)
Will return a value of –9 which is the numeric difference between ASCII “i” and ASCII “r”.
That is “i “ minus “r” in ASCII code is –9. If the value is negative, string1 is alphabetically above
string2.
Strcpy() function
The strcpy function works almost like a string assignment operator. It takes the form
Strcpy(string1, string2);
Strlen() function
This function counts and rutruns the number of characters in a string.
Strlen(string);
Where n is an integer variable which receives the value of the length of the string. The argument
may be a string constant. The counting ends at the first null character.
Structures
C supports a constructed data type known as structure, which is a method for packing data of
different types. A structure is a convenient tool for handling a group of logically related data items.
Structure help to organize complex data in a more meaningful way. It is a powerful concept that we
may often need to use in our program design.
Structures:
If you want to represent a collection of data items of difference types using a single name , then
we cannot use an array. Fortunately, C supports a constructed data type known as structure, which
is a method for packing data of different types. A structure is a convenient tool for handling a group
of logically related data items.
A structure means different types of data items it will represent a common name. Consider a book
database consisting of book name, author, number of pages, and price. We can define a structure to
hold this information as follows
struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
}
the keyword struct declares a structure to hold the details of four fields. Namely title, author,
pages and price. These fields are called structure elements or members. Each member may
belong to a different type of data. Book bank is the name of the structure and is called the
structured tag.
The tag name may be used subsequently to declare variables that have the tag’s structure.
Note that the above declaration has not declared any variables. It simply describes a format called
template to represent information as shown below.
Struct book_bank
{
Title: Array of 20 characters
Author:Array of 15 characters
Pages:
Integer
Price:
float
Satyanarayana__________________________________________________________________________________ 28
}
Struct tag_name
{
data type member1;
data type member2;
…
}
we can declare structure variable using the tag name anywhere in the program. For example, the
statement
Struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
} book1,book2,book3;
Book1.price
Is the variable presenting the price of book1 and can be treated like any other ordinary variable.
Here is how we would assign values to the members of book1.
Array of Structures:
We use structure to describe the format of a number of related variables. For example in analyzing
the marks obtained by a class of students, we may use a template to describe student name and
marks obtained in various subjects and then declare all the students as structure variables. In such
cases we may declare an array of structures, each element of the array representing a structure
variable. For example
Satyanarayana__________________________________________________________________________________ 29
Defines an array called student, that consists of 100 elements. Each element is defined to be of the
type struct class. Consider the following declaration
Structures with in structures means nesting structures. Nesting of strutures is permitted in c. let
us consider the following structure defined to store information about the salary of employees
Struct salary
{
char name[20];
char dept[10];
int basic,da,ta,hra;
}
employee;
This structure defines name, dept, basic salary and three kinds of allowances. We cab group all the
items related to allowance together and declare them under a substructure as follows
Struct salary
{
char name[20];
char dept[10];
int basic;
struct
{
int da;
int hra;
int ta;
}
allowance;
} employee;
The salary structure contains a member named allowance which itself is a structure with three
members. The members contained in the inner structure namely da, ta and hra can be referred to
as
Employee.allowance.da
Employee.allowance.ta
Employee.allowance.hra
Satyanarayana__________________________________________________________________________________ 30
Satyanarayana__________________________________________________________________________________ 31
A union is a user-defined type similar to structs in C except for one key difference.
Structures allocate enough space to store all their members, whereas unions can
only hold one member value at a time.
How to define a union?
We use the union keyword to define unions. Here's an example:
union car
{
char name[50];
int price;
};
union car
{
char name[50];
int price;
};
int main()
{
union car car1, car2, *car3;
return 0;
}
Satyanarayana__________________________________________________________________________________ 32
union car
{
char name[50];
int price;
} car1, car2, *car3;
There are two types of User defined data types. These are Enumerated and Typedef data type.
Enumerated data type can be defined as
Here enum is the reserve word and V1,V2,V3…. Vn all are the values which is also called
enumerated constants. Also variable cab be defined with the enumerated variable. For example,
some values can be assigned to the enumerated identifier and the variable as
typedef is used to represent the existing data type . i.e. by using this the new type can be used in
place of the old type anywhere in a C program. Typedef data type can be defined as;
Here data type may be int, float ,double and char . identifier gives us the information of new names
given to the data type. Notes that typedef cannot create a new type . for example some valid
typedef statements are as follows;
Here pay tells us the link with int and salary with the float and these can be used for the declaration
of the varibale as
Pay a,b;
Salary amount;
a=10;
b=20
Amount=4500.50;
Satyanarayana__________________________________________________________________________________ 33
Unit-IV:
Pointers
Pointers are another importance feature of C language. They are a powerful tool and handy to
use once they are mastered. There are many reasons for using pointers. Pointer advantages
The computer’s memory is a sequential collection of ‘Storage Cells’. Each cell, commonly known as a
byte, has a number called address associated with it. Typically the addresses are numbered
consecutively starting from zero. The last address depends on the memory size. A computer system
having 64K memory will have its last address as 65,535.
0
1
2
4
5
6
7
8
65535
Whenever we declare a variable the system allocates some where in the memory, an appropriate
location to hold the value of the variable. Since every byte has a unique address number , this
location will have its own address number. Consider the following statement
Int quntity=179
This statement instructs the system to find a location for the integer variable quantity and puts the
value 179 in that location. Let us assume that the system has chosen the address location 5000 of
quantity. During the execution of the program, the system always associates the name quantity
with the address 5000.
Remember, since a pointer is a variable, its value is also stored in the memory in another location.
Suppose we assign the address of quantity to a variable p. the link between the variable p and
quantity can be visualized as shown below. The address of p is 5048.
Since the value of the variable p is the address of the variable quantity, we may access the value
of quantity by using the value of p and therefore, we say that the variable p points to the variable
quantity. Thus p gets the name pointer. The & specifies the address of the variable. For example
P=&quantity
Satyanarayana__________________________________________________________________________________ 34
Pointer declaration:
In C, every variable must be declared for its type. Since pointer variables contain addresses that
belong to a separate data type, they must be declared as pointers before we use them. The
declaration of a pointer variable takes the following form.
Int *p;
This tells the compiler three things about the above variable
1. The asterisk(*) tells that the variable p is a pointer variable
2. P needs a memory location
3. P points to a variable of type integer
Remember that type int refers to the data type of the variable being pointed to by p and not the
type of the value of the pointer. Similarly the statement
Definition:
Pointer is a variable, its value is also stored in the memory in address of any other variable location.
Int quantity,*p,n;
quantity=179;
p=&quantity;
n=*p;
the first line declares quantity and n as integer variables and p as a pointer variable pointing to an
integer. The second line assigns the value 179 to quantity and the third line assigns the address of
quantity to the pointer variable p. the fourth line contains the indirection operator *. When the
operator * is placed before a pointer variable in an expression, the pointer returns the value of the
variable of which the pointer value is the address. In this case *p returns the value of the variable
quantity, because p is the address of quantity. The * can be remembered as ‘value at address’.
Thus the value of n would be 179. The two statements
p=&quantity;
n=*p;
are equivalent to
n= *quantity;
which is turn is equivalent to
n=quantity.
Character 1 byte
Integer 2 byte
Float 4 bytes
Long integer 4 bytes
Double 8 bytes
The number of bytes used to store various data types depends on the system and can be found by
making use of the sizeof operator.
When an array is declared, the compiler allocates a base address and sufficient amount of storage to
contain all the elements of the array in contiguous memory locations. The base address is the
location of the first element of the array.
Example
Static int x[5]
The name x is defined as a constant pointer pointing to the first element, x[0] and therefore the
value of x is 1000 the location where x[0] is stored. That is
X= &x[0]=1000
If we declare p as an integer pointer, then we can make the pointer p to the point to the array x by
the following assignment.
P=x;
This is equivalent to
P=&x[0];
Now we can access every value of x using p++ to move from one element to another. The
relationship between p and x is shown below
You may notice that the address of an element is calculated using its index and the scale factor of
the data type. For instance.
Address of x[3]=base address+(3*scale factor of int)
=1000*(3*2)=1006
when handing arrays, instead of using array indexing, we can use pointers to access array elements.
Note that *(p+3) gives the value of x[3]. The pointer accessing method is much faster than array
indexing.
Satyanarayana__________________________________________________________________________________ 36
Pointer with pointer :
Void main()
{
Int a,*p,**p1;
A=10;
P=&a;
P1=&p;
An lvalue (locator value) represents an object that occupies some identifiable location in
memory (i.e. has an address).
rvalues are defined by exclusion. Every expression is either an lvalue or an rvalue, so, an
rvalue is an expression that does not represent an object occupying some identifiable location
in memory.
For example, An assignment expects an lvalue as its left operand, so the following is valid:
int i = 10;
int i;
10 = i;
This is because i has an address in memory and is a lvalue. While 10 doesn't have an
identifiable memory location and hence is an rvalue. So assigning the value of i to 10 doesn't
make any sense.
Dynamic Memory Allocation:
C Dynamic Memory Allocation can be defined as a procedure in which the size of a
data structure (like Array) is changed during the runtime.
C provides some functions to achieve these tasks. There are 4 library functions
provided by C defined under <stdlib.h> header file to facilitate dynamic memory
allocation in C programming. They are:
1. malloc()
2. calloc()
3. free()
4. realloc()
Let’s look at each of them in greater detail.
Satyanarayana__________________________________________________________________________________ 37
C malloc() method
Syntax:
ptr = (cast-type*) malloc(byte-size)
For Example:
ptr = (int*) malloc(100 * sizeof(int));
Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And,
the pointer ptr holds the address of the first byte in the allocated memory.
C calloc() method
C free() method
Syntax:
free(ptr);
Satyanarayana__________________________________________________________________________________ 38
C realloc() method
Syntax:
ptr = realloc(ptr, newSize);
#define LINE 1
#include<stdio.h>
main ( ){
#ifdef LINE
#else
#endif
Satyanarayana__________________________________________________________________________________ 39
}
Output
When the above program is executed, it produces the following result −
This line number one
Unit-V:
Functions
Function means self contained block of statements it will perform a particular task. C functions are
easy to define and use. C functions can be classified into two categories, namely
1. library functions
2. and user defined functions.
main is a best example of user defined functions. The Printf and Scanf belong to the
category of library functions. We have also used other library functions such as sqrt, cos, …
etc. The main distinction between these two categories is that library functions are not
required to be written by us where as a user defined function has to be developed by the
user at the time of writing a program. However a user defined function can later become a
part of the C program library.
Argument list:
Satyanarayana__________________________________________________________________________________ 40
The argument list contains valid variable names separated by commas. the list must be
surrounded by parentheses. note that no semicolon follows the closing parenthesis. the argument
variables receive values form the calling function, thus providing a means for data communication
form the calling function to the called function. some examples of functions with arguments are
power(x,n);
square(y); calling function:
copy(name1, name2);
main()
{
All argument variables must be declared for their types after int p;
the function header and before the opening brace of the function body. example p=mult(10,5);
printf(“result=%d\n”,p);
}
mult(x,y)
int x,y;
{
int k;
k=x*y;
return(k);
}
Satyanarayana__________________________________________________________________________________ 41
Category of Functions:
A function, depending on whether arguments are present or not, may belong to one of the
following categories.
when a function has no arguments it does not receive any data from the calling function. similarly,
when it does not return a value, the calling function does not receive any data from the called
function. in effect, there is no data transfer between the calling function and the called function.
Function2()
no input
{
function-1() ……….
{ ……….
……… ……….
……….
}
function-2();
……….
……….
}
as pointed out earlier, a function that does not return any value cannot be used in an expression. It
can only be used as an independent statement.
function-1() Function2(p)
{ {
……… ……….
………. ……….
……….
function-2(a);
………. }
……….
}
Example:
Printline(ch)
Value(p,r,n)
The arguments ch,p,r and n are called formal arguments. The calling function can now send
values to these arguments using function calls containing appropriate arguments. For example
the function call
Value(500,0.12,5)
Would send the values 500,0.12 and 5 to the function
Value(p,r,n)
And assign 500 to p 0.12 to r and 5 to n. the values 500
,0.12 and 5 are the actual arguments which become the values of the formal arguments inside
the called function.
Satyanarayana__________________________________________________________________________________ 42
The actual and formal arguments should match in number, type and order. The values of actual
arguments are assigned to the formal arguments on a one to one basis, stating with the first
argument as follows.
Main()
{
……….
Function1(a1, a2, a3…..an);
/*arguments*/
………
}
Remember that when a function call is made, only a copy of the values of actual arguments is
passed into the called function. What occurs inside the function will have no effect on the
variable used in the actual argument list.
A self contained and independent function should be have like a black box that receives a
communication as follows
function-1() Function2()
{ {
……… ……….
………. ……….
……….
function-2(a); Return(p);
………. }
……….
}
Main()
{
printf(“this is example of recursion \n”);
main();
}
Execution is terminated abruptly; otherwise the execution will continue indefinitely.
Another useful example of recursion is the evaluation of factorials of a given number. The factorial
of a number n is expressed as series of repetitive multiplication’s as follows
Factorial of n= n(n-1)(n-2)…… 1
For example
Factorial of 4 = 4*3*2*1 = 24
A function of evaluate factorial of n is as follows
Satyanarayana__________________________________________________________________________________ 43
Factorial( int n)
{
if(n==1)
return(1)
else
return(n*factorial(n-1));
}
Let us see how the recursion works. Assume n=4. Since the value of n is not 1, then statement
Fact=4*factorial(3);
Will be executed with n =3 that is
Fact = 3 * factorial(2);
Will be evaluated. The expression on the right hand side includes a call to factorial with n=2. This
call will return the following value
2 * factorial(1)
once again factorial
We shall briefly discuss the Scope and Longevity of each of the above class of variable. The
scope of variable determines over what part(s) of the program a varibale is actually available for
use. Longevity refers to the period during execution of the program.
Satyanarayana__________________________________________________________________________________ 44
External variable:
variable that are both alive and active throughout the entire porgram are known as external
variable. They are also known as global variable. Unlike local variable , global variables can be
accessed by any function in the program. External variables are declared outside a function.
For example,
Int number;
Float lenth = 7.5;
Main()
{
Extern int a;
……
……
}
External declaration:
main()
{
extern int y;
}
Static varibales:
as the name suggests the value of static vartiables persits until the end of the program. A
variable can be declared static using the keyword static like.
Static int x=10;
Static float y=20;
Register variable:
We can tell the compiler that a variable should be dept in one of the machine register, instead
of keeping in the memory.
FILES
File is a major role in computers. File contains a group of contents. If we want to store data in a file
in the secondary memory, we must specify certain things about the file, To the operating system
they include
1. File-name
2. Data –structure
3. Purpose
File name is a string of characters that make up a valid filename for the operating system. It may
contain two parts, a primary name and an optional period with the extension. Ex
A.TXT
FIB.C
TEXT.DBF
Etc
Satyanarayana__________________________________________________________________________________ 45
Data structure of a file is define as FILE in the library of Standard I/O function definitions.
Therefore, all files should be declared as type File before they are used. File is a defined data
type.
FILE *fp;
Fp=fopen(“filename”, “mode”);
The first statement declares the variable fp as a pointer to the data type FILE. As stated earlier,
FILE is a structure that is defined in the I/O library. The second statement opens the file named
filename and assigns an identifier to the FILE type pointer fp.
The second statement also specifies the purpose of opening this file. The mode does this job,
mode can be one of the following
File *p1, *p2;
R open the file for reading only
W open the file for wrinting only
A open the file for appending data to it.
main()
{char source_file[]="x1.txt";
char target_file[]="x2.txt";
source = fopen(source_file, "r");
if (source == NULL) {
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
} target = fopen(target_file, "w");
if (target == NULL) {
fclose(source);
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
while ((ch = fgetc(source)) != EOF)
fputc(ch, target);
printf("File copied successfully.\n");
fclose(source);
Satyanarayana__________________________________________________________________________________ 46
fclose(target);
A stream is a logical entity that represents a file or device, that can accept input or output. All input and
output functions in standard C, operate on data streams. Streams can be divided into text, streams and binary
streams.
Satyanarayana__________________________________________________________________________________ 47