C Program Note

Download as pdf or txt
Download as pdf or txt
You are on page 1of 77

Subject Name: Programming In C

Module-1
BASIC ORGANIZATION OF COMPUTER
The system concept: A system is a group of integrated parts, which have the common purpose of achieving
some objectives. Some properties of system are-
→A system has more than one element.
→All the elements of a system are logically related.
→All the elements of a system are controlled in a manner to achieve the system goal.

A complete computer system consists of four parts:


→ Hardware
→Software
→One or more user
→Data
Hardware:
The physical devices that make op the computer are called hardware. Hardware is any part of the computer
you can touch. The tern device refers to any piece of hardware.
Hardware has many parts and the critical components fall into one of four categories.
o Processor
o Memory
o Input and Output device
o Storage
The Processor:
The procedure that transforms raw data into information is called processor. The processor is like the brain of
the computer; it organizes and carries out instructions that come from either the user or the software. In a
personal computer, the processor usually consists of one or more microprocessors (sometimes called
chips). The motherboard is a rigid rectangular card containing the circuitry that connects the processor to
the other hardware. The term central processing unit (CPU) refers to a computer’s processor.

Memory:
Memory is like an electronic scratch pad inside the computer. When you launch a program, it is loaded into and
run from memory. Data used by the program is also loaded into memory for fast access. As new data is
entered into the computer, it is also stored in memory-but only temporarily. The most common type of
memory is called random access memory, or RAM. As a result, the term memory is commonly used to
mean to RAM. Data is both written to and read from this memory. For this reason RAM is also sometimes
called read / write memory.
Input and Output Devices:

Input Devices:
The most common input device is the keyboard which accepts letters, numbers and commands from the user.
Another important type of input device is the mouse, which let you select options from on-screen menus.
Other popular input devices are trackballs, touchpads, joysticks, scanners, digital cameras and microphones.

Output Device:
The most common Output devices are the monitor and the printer. Just as computers can accepts sound as input,
they can use stereo speakers or headphones as output devices to produce a sound. Some types of hardware
can act as both input and output devices. A touch screen, for example, is a type of monitor that displays text
or icons you can touch. Communications devices are the most common types of devices that can perform
both input and output.

Storage:
The purpose of storage is to hold data permanently.
There are three major distinctions between storage and memory-
(i) There is more room in storage than in memory, just as there is more room in a file cabinet that there
is on a tabletop.
(ii) Contents are retained in storage when the computer is turned off, whereas the programs or the data
you put into memory disappear when you shut down the computer.
(iii) Storage is very slow compared to memory, but it is much cheaper that memory.
There are many types storage devices, including tape drives, optical drives, and removable hard drives. The
most common storage medium is the magnetic disk. A disk is a round, flat object that spins around its
center. The device that holds a disk is caked a disk drive.
The CD-ROM drive is another common type of storage device. Compact disks (CDs) are s type of optical
storage device, identical to audio CDs. Until recently, a standard CD could store 74 minutes of audio or
650 MB of data. A newer breed of CDs can hold 80 minutes of audio or 700-MB of data. They type used
in computers is called Compact Disk-Read- Only Memory (CD-ROM). If you purchase a CD-
Recordable (CD_R) drive, you have the option of creating your own CDs. A CD-R drive can write data to
and read data from a compact disk. To create your own compact disks, you must use special CD-R disks,
which can be written on only once, or CD-Rewritable (CD-RW)disks, which can be written to multiple
times, like a floppy disk.
Another increasingly popular data storage technology is the Digital Video Disk (DVD), which is revolutionizing
home entertainment. Using sophisticated compression technologies, a single DVD can store an entire full-
length movie. DVDs can hold a minimum of 4.7 GB of data and as much as 17 GB.
Software: Software is a set of instructions that makes the computer perform tasks. The term program refers to
any piece of software. In another word, the ingredient that enables a computer to perform a special task is
software, which consists of electronic instructions.

Most Software falls into two major categories:


System Software
Application Software

System Software are of two types:


o Operating System
o Network Operating System

Operating System: It tells the computer how to use its own components.

Network Operating System: It allows computers to communicate and share data across a Network.
Application Software: It tells the computer how to accomplish specific tasks, such as word processing or
drawing, for user.

Users
People are the computer operators, also known as users.

Data
Data consists of individual facts or bits of information which by themselves may not make much sense to person.

Input Unit:
The following functions are performed by an Input unit:
(i) It accepts (reads) the instructions and data from the outside world.
(ii) It converts these instructions and data in computer acceptable form.
(iii) It supplies the converted instructions and data to the computer system for further processing.

Output Unit:
The following functions are performed by an Output unit:
(i) It accepts the results produced by the computer, which are in coded form and hence, cannot be
easily understood by us.
(ii) It converts these coded results to human acceptable (readable) form.
(iii) It supplies the converted results to the Outside world.

Storage Unit:
The specific functions of the storage unit are to hold (store)
(i) The data and instructions required for processing (received from input devices).
(ii) Intermediate results of processing.
(iii) Final results of processing, before these results are released to an output device.
The storage unit of all computers is comprised of the following two types of storage.

Primary Storage: The primary storage, also known as main memory, is used to hold pieces of program
instructions and data, intermediate results of processing, and recently produced results of processing, of the
Jobs, which the computer system is currently working on. The primary memory can hold information only
whole the computer system is on. As soon as the computer system is switched off or reset, the information
held in the primary storage disappears.

Secondary Storage: The Secondary Storage, also known as auxiliary storage, is used to take care of the
limitations of the primary storage. That is, it is used to supplement the limited storage capacity and the
volatile characteristic of primary memory. This is because secondary storage is much cheaper than primary
storage, and it can retain information ever when the computer system is switched off or reset. The secondary
storage is normally used to hold the program instructions, data, and information of those Jobs, on which the
computer system is not working on currently, but needs to hold them for processing later.

Arithmetic Logic Unit:


The Arithmetic Logic Unit (ALU) of a computer system is the place, where the actual execution of the
instructions takes place during the processing operation. To be more precise, calculations are performed,
and all comparisons (decisions) are made in the ALU. Almost all ALUs are designed to performed the four
basic arithmetic operations (add subtract, multiply and divide), and logic operations or comparisons, such
as less than, equal to, and greater than.

Control Unit:
How does the input device know that it is time for it to feed data into the storage unit? How does the ALU know
what should be done with the data once they are received? Moreover, how is it that only the final results
are sent to the output device, and not the intermediate results? All this is possible due to the control unit of
the computer system. Although, it does not perform any actual processing on the data, the control unit acts
as a central nervous system, for the other components of the computer system. It manages and co-ordinates
the entire computer system. It obtains instructions from the program stored in main memory, interprets the
instructions and issues signals, which cause other units of the system to execute them.

Central Processing Unit:


The control unit and arithmetic logic unit of a computer system are jointly known as the Central Processing
Unit (CPU)
Computer - Number System

When we type some letters or words, the computer translates them in numbers as computers can understand
only numbers. A computer can understand positional number system where there are only a few symbols called
digits and these symbols represent different values depending on the position they occupy in the number.

A value of each digit in a number can be determined using

• The digit

• The position of the digit in the number

• The base of the number system (where base is defined as the total number of digits available in the
number system).

Decimal Number System


The number system that we use in our day-to-day life is the decimal number system. Decimal number system
has base 10 as it uses 10 digits from 0 to 9. In decimal number system, the successive positions to the left of
the decimal point represent units, tens, hundreds, thousands and so on.

Each position represents a specific power of the base (10). For example, the decimal
number 1234 consists of the digit 4 in the units position, 3 in the tens position, 2 in the
hundreds position, and 1 in the thousands position, and its value can be written as

(1x1000)+ (2x100)+ (3x10)+ (4xl)


(1x103)+ (2x102)+ (3x101)+ (4xl00)
1000 + 200 + 30 + 4
1234

As a computer programmer or an IT professional, you should understand the following number systems which
are frequently used in computers.

S.N. Number System and Description

1
Binary Number System

Base 2. Digits used : 0, 1

2
Octal Number System

Base 8. Digits used : 0 to 7


3
Hexa Decimal Number System

Base 16. Digits used : 0 to 9, Letters used : A- F

Binary Number System


Characteristics of binary number system are as follows:
• Uses two digits, 0 and 1.

• Also called base 2 number system

• Each position in a binary number represents a 0 power of the base (2). Example 20

• Last position in a binary number represents a x power of the base (2). Example 2x where x represents
the last position - 1.

Example
Binary Number : 101012

Calculating Decimal Equivalent:

Step Binary Number Decimal Number

Step 1 101012 ((1 x 24) + (0 x 23) + (1 x 22) + (0 x 21) + (1 x 20))10

Step 2 101012 (16 + 0 + 4 + 0 + 1)10

Step 3 101012 2110

Note : 101012 is normally written as 10101.

Octal Number System


Characteristics of octal number system are as follows:
• Uses eight digits, 0,1,2,3,4,5,6,7.

• Also called base 8 number system

• Each position in an octal number represents a 0 power of the base (8). Example 80

• Last position in an octal number represents a x power of the base (8). Example 8 x where x represents
the last position - 1.

Example
Octal Number : 125708

Calculating Decimal Equivalent:


Step Octal Number Decimal Number

Step 1 125708 ((1 x 84) + (2 x 83) + (5 x 82) + (7 x 81) + (0 x 80))10

Step 2 125708 (4096 + 1024 + 320 + 56 + 0)10

Step 3 125708 549610

Note : 125708 is normally written as 12570.

Hexadecimal Number System


Characteristics of hexadecimal number system are as follows:
• Uses 10 digits and 6 letters, 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F.

• Letters represents numbers starting from 10. A = 10. B = 11, C = 12, D = 13, E = 14, F = 15.

• Also called base 16 number system

• Each position in a hexadecimal number represents a 0 power of the base (16). Example 160

• Last position in a hexadecimal number represents a x power of the base (16). Example 16 x where x
represents the last position - 1.

Example
Hexadecimal Number : 19FDE16

Calculating Decimal Equivalent:

Step Binary Number Decimal Number

Step 1 19FDE16 ((1 x 164) + (9 x 163) + (F x 162) + (D x 161) + (E x 160))10

Step 2 19FDE16 ((1 x 164) + (9 x 163) + (15 x 162) + (13 x 161) + (14 x
160))10

Step 3 19FDE16 (65536+ 36864 + 3840 + 208 + 14)10

Step 4 19FDE16 10646210

Note : 19FDE16 is normally written as 19FDE.


Computer - Number Conversion

Advertisements

Previous Page
Next Page

There are many methods or techniques which can be used to convert numbers from one base to another. We'll
demonstrate here the following:

• Decimal to Other Base System


• Other Base System to Decimal
• Other Base System to Non-Decimal
• Shortcut method - Binary to Octal
• Shortcut method - Octal to Binary
• Shortcut method - Binary to Hexadecimal
• Shortcut method - Hexadecimal to Binary
Decimal to Other Base System
steps

• Step 1 - Divide the decimal number to be converted by the value of the new base.

• Step 2 - Get the remainder from Step 1 as the rightmost digit (least significant digit) of new base number.

• Step 3 - Divide the quotient of the previous divide by the new base.

• Step 4 - Record the remainder from Step 3 as the next digit (to the left) of the new base number.

Repeat Steps 3 and 4, getting remainders from right to left, until the quotient becomes zero in Step 3.

The last remainder thus obtained will be the most significant digit (MSD) of the new base number.

Example
Decimal Number : 2910

Calculating Binary Equivalent:

Step Operation Result Remainder

Step 1 29 / 2 14 1
Step 2 14 / 2 7 0

Step 3 7/2 3 1

Step 4 3/2 1 1

Step 5 1/2 0 1

As mentioned in Steps 2 and 4, the remainders have to be arranged in the reverse order so that the first remainder
becomes the least significant digit (LSD) and the last remainder becomes the most significant digit (MSD).

Decimal Number : 2910 = Binary Number : 111012.

Other base system to Decimal System


Steps

• Step 1 - Determine the column (positional) value of each digit (this depends on the position of the digit
and the base of the number system).

• Step 2 - Multiply the obtained column values (in Step 1) by the digits in the corresponding columns.

• Step 3 - Sum the products calculated in Step 2. The total is the equivalent value in decimal.

Example
Binary Number : 111012

Calculating Decimal Equivalent:

Step Binary Number Decimal Number

Step 1 111012 ((1 x 24) + (1 x 23) + (1 x 22) + (0 x 21) + (1 x 20))10

Step 2 111012 (16 + 8 + 4 + 0 + 1)10

Step 3 111012 2910

Binary Number : 111012 = Decimal Number : 2910

Other Base System to Non-Decimal System


Steps

• Step 1 - Convert the original number to a decimal number (base 10).


• Step 2 - Convert the decimal number so obtained to the new base number.

Example
Octal Number : 258

Calculating Binary Equivalent:

Step 1 : Convert to Decimal


Step Octal Number Decimal Number

Step 1 258 ((2 x 81) + (5 x 80))10

Step 2 258 (16 + 5 )10

Step 3 258 2110

Octal Number : 258 = Decimal Number : 2110

Step 2 : Convert Decimal to Binary


Step Operation Result Remainder

Step 1 21 / 2 10 1

Step 2 10 / 2 5 0

Step 3 5/2 2 1

Step 4 2/2 1 0

Step 5 1/2 0 1

Decimal Number : 2110 = Binary Number : 101012

Octal Number : 258 = Binary Number : 101012

Shortcut method - Binary to Octal


Steps

• Step 1 - Divide the binary digits into groups of three (starting from the right).

• Step 2 - Convert each group of three binary digits to one octal digit.
Example
Binary Number : 101012

Calculating Octal Equivalent:

Step Binary Number Octal Number

Step 1 101012 010 101

Step 2 101012 28 58

Step 3 101012 258

Binary Number : 101012 = Octal Number : 258

Shortcut method - Octal to Binary


Steps

• Step 1 - Convert each octal digit to a 3 digit binary number (the octal digits may be treated as decimal
for this conversion).

• Step 2 - Combine all the resulting binary groups (of 3 digits each) into a single binary number.

Example
Octal Number : 258

Calculating Binary Equivalent:

Step Octal Number Binary Number

Step 1 258 210 510

Step 2 258 0102 1012

Step 3 258 0101012

Octal Number : 258 = Binary Number : 101012

Shortcut method - Binary to Hexadecimal


Steps

• Step 1 - Divide the binary digits into groups of four (starting from the right).
• Step 2 - Convert each group of four binary digits to one hexadecimal symbol.

Example
Binary Number : 101012

Calculating hexadecimal Equivalent:

Step Binary Number Hexadecimal Number

Step 1 101012 0001 0101

Step 2 101012 110 510

Step 3 101012 1516

Binary Number : 101012 = Hexadecimal Number : 1516

Shortcut method - Hexadecimal to Binary


steps

• Step 1 - Convert each hexadecimal digit to a 4 digit binary number (the hexadecimal digits may be
treated as decimal for this conversion).

• Step 2 - Combine all the resulting binary groups (of 4 digits each) into a single binary number.

Example
Hexadecimal Number : 1516

Calculating Binary Equivalent:

Step Hexadecimal Number Binary Number

Step 1 1516 110 510

Step 2 1516 00012 01012

Step 3 1516 000101012

Hexadecimal Number : 1516 = Binary Number : 101012


Computer Languages
They are of three types –

1 Machine Language ( Low level language )


2 Assembly language ( Middle level language )
3 User Oriented language ( Higher level language )

Machine language depends on the hard ware and comprises of 0 and1 .This is tough to write as one must
know the internal structure of the computer. At the same time assembly language makes use of English
like words and symbols. With the help of special programs called Assembler, assembly language is
converted to machine oriented language. Here also a
programmer faces practical difficulties. To overcome this hurdles user depends on Higher level
languages, which are far easier to learn and use. To write programs in higher level language, programmer
need not know the characteristics of a computer. Here he uses English alphabets, numerals and some
special characters.

Some of the Higher level languages are FORTRAN, BASIC, COBOL,PASCAL, C, C++, ADA etc. We
use C to write programs. Note that Higher-level languages can not directly be followed by a computer.
It requires the help of certain soft wares to convert it into machine coded instructions. These soft wares
are called Compiler, Interpreter, and Assembler. The major difference between a compiler and an
interpreter is that compiler compiles the user’s program into machine coded by reading the whole
program at stretch where as Interpreter translates the program by reading it line by line.
PROGRAMMING METHODOLOGY
A computer is used to a solve a problem. Steps
1 Analyze the problem
2 Identify the variables involved
3 Design the solution
4 Write the program
5 Enter it into a computer
6 Compile the program and correct errors
7 Correct the logical errors if any
8 Test the program with data
9 Document the program
Algorithms
Step by step procedure for solving a problem is called algorithm.

Example
To make a coffee
Step1: Take proper quantity of water in a cooking pan
Step2: Place the pan on a gas stow and light it
Step3: Add Coffee powder when it boils
Step4: Put out the light and add sufficient quantity of sugar and milk
Step5: Pour into cup and have it.
To add two numbers
Step1: Input the numbers as x, y
Step2: sum=x + y
Step3: print sum
For a better understanding of an algorithm, it is represented pictorially.
The pictorial representation of an algorithm is called a Flow Chart.
Consider a problem of multiplying two numbers
Algorithm
Step1: Input the numbers as a and b
Step2: find the product a x b
Step3: Print the result

To find the highest of three numbers


Algorithm
Step 1: read the numbers as x ,y and z
Step 2: compare x and y
Step 3: if x > y then compare x with z and find the greater
Step 4: Otherwise compare y with z and find the greater
Flowchart
Flowchart is a diagrammatic representation of an algorithm. Flowchart are very helpful in writing
program and explaining program to others.

Symbols Used In Flowchart

Different symbols are used for different states in flowchart, For example: Input/output and decision
making has different symbols. The table below describes all the symbols that are used in making
flowchart

Examples of flowcharts in programming

Draw a flowchart to add two numbers entered by user.

Draw flowchart to find the largest among three different numbers entered by user.
Draw a flowchart to find all the roots of a quadratic equation ax2+bx+c=0

Draw a flowchart to find the Fibonacci series till term≤1000.


C Fundamentals
A brief history of C

C evolved from a language called B, written by Ken Thompson at Bell Labs in1970. Ken used B to write
one of the first implementations of UNIX. B in turn was a descendant of the language BCPL (developed
at Cambridge (UK) in 1967), with most of its instructions removed. So many instructions were removed
in going from BCPL to B, that Dennis Ritchie of Bell Labs put some back in (in 1972), and called the
language C.
The famous book The C Programming Language was written by Kernighan and Ritchie in 1978, and
was the definitive reference book on C for almost a decade. The original C was still too limiting, and not
standardized, and so in 1983 an ANSI committee was established to formalise the language definition.

Structure of a program
Every C program consists of one or more modules called functions. One of these functions is called
main. The program begins by executing main function and accesses other functions, if any. Functions
are written after or before main function separately. A function has (1) heading consists of name with
list of arguments ( optional ) enclosed in parenthesis, (2) argument declaration (if any) and(3)
compound statement enclosed in two braces { } such that each statement ends with a semicolon.
Comments, which are not executable statement, of necessary can be placed in between /* and */.
Example
/* program to find the area pf a circle */
#include<stdio.h>
#include<conio.h>
main( )
{
float r, a;
printf(“radius”);
scanf(“%f”, &r);
a=3.145*r*r;
printf(“area of circle=%f”, area);
}
The character set
C used the upper cases A,B,…….,Z, the lower cases a ,b,…..,z and certain special characters like + - *
/ = % & # ! ? ^ “ ‘ ~ \ <> ( ) = [ ]{ } ; : . , _ blank space @ $ . also certain combinations of these
characters like\b, \n, \t, etc…
Identities and key words
Identities are names given to various program elements like variables, arrays and functions. The name
should begin with a letter and other charact4rs canbe letters and digits and also can contain underscore
character ( _ )
Example: area, average, x12 , name_of_place etc………
Key words are reserved words in C language. They have predicted meanings and are used for the
intended purpose.
Standard keywords are
auto,break, case, char, const, continue, default, do, double, else enum, extern, float, for, goto, if,
int, long, register, return, short, signed, sizeof, static, struct,switch, typedef, union, unsigned,
void, volatile, while.
Data type
The variables and arrays are classified based on two aspects.Firstis the data type it stores and the second
is the type of storage. The basic data types in C language are int, char, float and double. They are
respectively concerned with integer quantity, single character, numbers, with decimal point or exponent
number and double precision floating point numbers ( ie; of larger magnitude ).These basic data types
can be augmented by using quantities like short, long, signed and unsigned. ( ie; long int, short int, long
double etc.....).
Constants
There are 4 basic types of constants . they are int4ger constants, floating-point constants, character
constants and string constants.
(a) Integer constants: It is an integer valued numbers, written in three different number system, decimal
(base 10) , octal(base8), and hexadecimal(base 16).
A decimal integer constant consists of 0,1,…..,9..
Example : 75 6,0,32, etc…..
An octal integer constant consists of digits 0,1,…,7. with 1st digit 0 to indicate that its an octal integer.
Example : 0, 01, 0756, 032, etc…..
A hexadecimal integer constant consists of 0,1, …,9,A, B, C, D, E, F. It begins with
0x.
Example: 0x7AA2, 0xAB, etc……
(b)Floating point constants : It is a decimal number (ie: base 10) with a decimal point or an exponent
or both. Ex; 32.65, 0.654, 0.2E-3, 2.65E10 etc. These numbers have greater range than integer constants.
(c) Character constants : It is a single character enclosed in single quotes like ‘a’.‘3’, ‘?’, ‘A’ etc. each
character has an ASCII to identify. For example ‘A’ has the ASCII code 65, ‘3’ has the code 51 and so
on.
(d) Escape sequences: An escape sequence is used to express non printing character like a new line, tab
etc. it begin with the backslash ( \ ) followed by letter like a, n, b, t, v, r, etc. the commonly used escape
sequence are\a : for alert \n : new line \0 : null\b : backspace \f : form feed \? : Question mark
\f : horizontal tab \r : carriage return \’ : single quote\v : vertical tab \” : quotation mark
(e) String constants : it consists of any number of consecutive characters enclosed in double quotes .Ex
: “ C program” , “mathematics” etc……
Variables and arrays
A variable is an identifier that is used to represent some specified type of information. Only a single data
can be stored in a variable. The data stored in the variable is accessed by its name. before using a variable
in a program, the data typeit has to store is to be declared.
Example : int a, b, c,
a=3; b=4;
c=a+b

Note : A statement to declare the data types of the identifier is called declaration statement. An array is
an identifier which is used to store a collection of data of the same type with the same name. The data
stored is an array are distinguished by the subscript. The maximum size of the array represented by the
identifier must be mentioned.

Example : int mark[100] .


With this declaration n, mark is an array of size 100, they are identified by
mark[0],mark[1],……….,mark[99].

Note : along with the declaration of variable, it can be initialized too. For example int x=10;with this the
integer variable x is assigned the value 10, before it is used. Also note that C is a case sensitive language.
i.e. the variables d and D are different.
DECLARATIONS
This is for specifying data type. All the variables, functions etc must be declared before they are used. A
declaration tells the compiler the name and type of variable you'll be using in your program. In its
simplest form, a declaration consists of the type, the name of the variable, and a terminating semicolon:
Example : int a,b,c;
Float mark, x[100], average;
char name[30];
char c;
int i;
float f;
There are two reasons for declaring variables:
1. It makes things somewhat easier on the compiler; it knows right away what kind of storage to allocate
and what code to emit to store and manipulate each variable; it doesn't have to try to intuit the
programmer's intentions.
2. It forces a bit of useful discipline on the programmer.
EXPRESSION
This consists of a single entity like a constant, a variable, an array or a function name. it also consists of
some combinations of such entities interconnected by operators.
Example : a, a+b, x=y, c=a+b, x<=y etc……..

STATEMENTS
Statements are the ``steps'' of a program. Most statements compute and assign values or call functions,
but we will eventually meet several other kinds of statements as well. By default, statements are executed
in sequence, one after another.
A statement causes the compiler to carry out some action. There are 3 different
types of statements – expression statements compound statements and control
statements. Every statement ends with a semicolon.
Example: (1) c=a + b;
(2) {
a=3;
b=4;
c=a+b;
}
(3) if (a<b)
{
printf(“\n a is less than b”);
}
Statement may be single or compound (a set of statements ).Most of the statements in a C program are
expression statements. An expression statement is simply an expression followed by a semicolon. The
lines:-
i = 0;
i = i + 1;
and printf("Hello, world!\n");are all expression statements.
SYMBOLIC CONSTANTS
A symbolic constant is a name that substitutes for a sequence of characters, which represent a numeric,
character or string constant. A symbolic constant is defined in the beginning of a program by using
#define, without: at the end.
Example :
#define pi 3.1459
#define INTEREST P*N*R/100
With this definition it is a program the values of p, n ,r are assigned the value of INTEREST is computed.

OPERATORS AND EXPRESSIONS

→ARITHMETIC OPERATORS

The basic operators for performing arithmetic are the same in many computer languages:
+ addition
- subtraction
* multiplication
/ division
% modulus (remainder)
For exponentiations we use the library function pow. The order of precedence of these operators is % /
* + - . it can be overruled by parenthesis.

Integer division :

Division of an integer quantity by another is referred to integer division. This operation results in
truncation. i.e. When applied to integers, the division operator /discards any remainder, so 1 / 2 is 0 and
7 / 4 is 1. But when either operand is a floating-point quantity (type float or double), the division operator
yields a floating-point result, with a potentially nonzero fractional part. So 1 / 2.0 is 0.5,
and 7.0 / 4.0 is 1.75.
.
Example : int a, b, c;
a=5;
b=2;
c=a/b;
Here the value of c will be 2
Actual value will be resulted only if a or b or a and b are declared floating type. The value of an arithmetic
expression can be converted to different data type by the statement ( data type) expression.
Example : int a, b;
float c;a=5;b=2;
c=(float) a/b
Here c=2.5

Order of Precedence

Multiplication, division, and modulus all have higher precedence than addition and subtraction. The term
``precedence'' refers to how ``tightly'' operators bind to their operands (that is, to the things they operate
on). In mathematics, multiplication has higher precedence than addition, so 1 + 2 * 3 is 7, not 9. In other
words, 1 + 2 * 3 is equivalent to 1 + (2 * 3). C is the same way.
16
→UNARY OPERATORS

A operator acts up on a single operand to produce a new value is called a unary operator.
(1) The decrement and increment operators - ++ and -- are unary operators. They increase and
decrease the value by 1. if x=3 ++x produces 4 and –x produces 2.
Note: In the place of ++x , x++ can be used, but there is a slight variation. In both case x is
incremented by 1, but in the latter case x is considered before increment.
(2) Sizeof is another unary operator
int x, y;
y=sizeof(x);
The value of y is 2 . the sizeof an integer type data is 2 that of float is 4, that of double is 8, that of char
is1.
→RELATIONAL AND LOGICAL OPERATORS

< ( less than ),


<= (less than or equal to ),
> (greater than ),
>= ( greater than or equal to ),
= = ( equal to ) and != (not equal to ) are relational operators.
A logical expression is expression connected with a relational operator.
For example ‘b*b – 4*a*c< 0 is a logical expression. Its value is either true or false.
int i, j, k ;
i=2;
j=3 ;
k=i+j ;
k>4 has the value true k<=3 has the value false.
→LOGICAL OERATORS

The relational operators work with arbitrary numbers and generate true/false values. You can also
combine true/false values by using the Boolean operators, which take true/false values as operands and
compute new true/false values. The three Boolean operators are:
&& and
|| or
! not (takes one operand; ``unary'')
The && (``and'') operator takes two true/false values and produces true (1) result if both operands are
true (that is, if the left hand side is true and the right-hand side is true). The || (``or'')operator takes two
true/false values and produces a true (1) result17
if either operand is true. The ! (``not'') operator takes a single true/false value and negates it, turning false
to true and true to false (0 to 1 and nonzero to 0).&& (and ) and || (or) are logical operators which are
used to connect logical expressions. Where as ! ( not) is unary operator, acts on a single logical
expression.
For example, 1. (a<5) && (a>-2)
2. (a<=3) || (b>2)
In the first example if a= -3 or a=6 the logical expression returns true.
→ASSIGNMENT OPERATORS
These operators are used for assigning a value of expression to another identifier.
=, + =, - = , * =, /= and %= are assignment operators.
a = b+c results in storing the value of b+c in ‘a’.
a += 5 results in increasing the value of a by 5
a /= 3 results in storing the value a/3 in a and it is equivalent a=a/3
Note : 1. if a floating point number is assigned to a integer type data variable, the value will be truncated.
Example : float a=5.36;
int b;
b=a
It results in storing 5 to b.
Similarly if an integer value is a assigned to a float type like float x=3 the value of x stored is 3.0.
→CONDITIONAL OPERATOR
The operator ?: is the conditional operator. It is used as variable 1 = expression 1 ? expression 2 :
expression 3.
Here expression 1 is a logical expression and expression 2 and expression 3 are expressions having
numerical values. If expression 1 is true, value of expression 2is assigned to variable 1 and otherwise
expression3 is assigned.
Example :
int a,b,c,d,e
a=3;b=5;c=8;
d=(a<b)? a : b;
e=(b>c) ? b : c;
Then d=3 and e=8
18
LIBRARY FUNCTIONS
They are built in programs readily available with the C compiler. These function perform certain
operations or calculations. Some of these functions return values when they are accessed and some carry
out certain operations like input, output. library functions accessed in a used written program by referring
its name with values assigned to necessary arguments.
Some of these library functions are :
abs(i), ceil(d), cos(d), cosh(d), exp(d), fabs(d),floor(d), getchar( ), log(d),pow(d,d’),printf( ),
putchar(c), rand( ), sin(d), sqrt(d), scanf( ), tan(d), toascii(c),toupper(c), tolower(c).
Note : The arguments i, c, d are respectively integer, char and double type.
Example:
#include<math.h>
#include<stdio.h>
#<conio.h>
main( )
{
float x, s;
printf(“ \n input the values of x :”);
scanf(“%f ”, &x);
s=sqrt(x);
printf(“\n the square root is %f ”,s);
}
Note that C language is case sensitive, which means ‘a’ and ‘A’ are different. Before the main program
there are statements begin with # symbol. They are called pre-processor statements. Within the main
program “ float r, a;” is declaration statement. ‘include’ is a pre-processor statement. The syntax is
#include<file name>. it is to tell the compiler looking for library functions, which are used in the
program, included in the file, file name ( like stdio.h, conio.h,math.h, etc…).

DATA INPUT OUTPUT


For inputting and outputting data we use library function .the important of these functions are getch( ),
putchar( ), scanf( ), printf( ), gets( ), puts( ). For using these functions in a C-program there should be a
pre-processor statement #include<stdio.h>.[A pre-processor statement is a statement before the main
program, whichbegins with # symbol.]
stdio.h is a header file that contains the built in program of these standard input output function.
getchar function
It is used to read a single character (char type) from keyboard. The syntax is
char variable name = getchar( );
Example:
char c;
c = getchar( );
For reading an array of characters or a string we can use getchar( ) function.
Example:
#include<stdio.h>
main( )
{
char place[80];
int i;
for(i = 0;( place [i] = getchar( ))! = ‘\n’, ++i);
}
This program reads a line of text.
putchar function
It is used to display single character. The syntax is
putchar(char c);
Example:
char c;
c = ‘a’;
putchar(c);
Using these two functions, we can write a very basic program to copy the input, a
character at a time, to the output:
#include <stdio.h>
/* copy input to output */
main()
{
int c;
c = getchar();
while(c != EOF)
{
putchar(c);
c = getchar();
}
return 0;
}
scanf function
This function is generally used to read any data type- int, char, double, float,string.
The syntax is
scanf (control string, list of arguments);
The control string consists of group of characters, each group beginning % sign and a conversion
character indicating the data type of the data item. The conversion characters are c,d,e,f,o,s,u,x indicating
the type resp. char decimal integer, floating-point value in exponent form, floating point value with
decimal point, octal integer, string, unsigned integer, hexadecimal integer. ie, “%s”, “%d” etc are such
group of characters.
An example of reading a data:
#include<stdio.h>
main( )
{
char name[30], line;
int x;
float y;
………
…….…
scanf(“%s%d%f”, name, &x, &y);
scanf(“%c”,line);
}
NOTE: 1) In the list of arguments, every argument is followed by & (ampersand symbol) except
string variable.
2) s-type conversion applied to a string is terminated by a blank space characters string having blank
space like “Govt. Victoria College” cannot be read in this manner. For reading such a string constant we
use the conversion string as “%[^\n]” in place of “%s”.
Example:
char place[80];
…………….
scanf(“%[^\n]”, place);
……………..
with these statements a line of text (until carriage return) can be input the variable ‘place’.
printf function
This is the most commonly used function for outputting a data of any type. The syntax is
printf(control string, list of arguments)
Here also control string consists of group of characters, each group having %symbol and conversion
characters like c, d, o, f, x etc.
Example:
#include<stdio.h>
` main()
{
int x;
scanf(“%d”,&x);
x*=x;
printf(“The square of the number is %d”,x);
}
Note that in this list of arguments the variable names are without &symbol unlike in the case of scanf( )
function. In the conversion string one can include the message to bedisplayed. In the above example
“The square of the number is” is displayed and is followed by the value of x. For writing a line of text
(which include blank spaces) the conversion string is “%s” unlike in scanf function. (There it is “[^\n]”).
More about printf statement
There are quite a number of format specifies for printf. Here are the basic ones :
%d print an int argument in decimal
%ld print a long int argument in decimal
%c print a character
%s print a string
%f print a float or double argument
%e same as %f, but use exponential notation
%g use %e or %f, whichever is better

%o print an int argument in octal (base 8)


%x print an int argument in hexadecimal (base 16)
%% print a single %
To illustrate with a few more examples: the call
printf("%c %d %f %e %s %d%%\n", '1', 2, 3.14, 56000000.,
"eight", 9);
would print
1 2 3.140000 5.600000e+07 eight 9%
The call
printf("%d %o %x\n", 100, 100, 100);
would print
100 144 64
Successive calls to printf just build up the output a piece at a time, so the calls
printf("Hello, ");
printf("world!\n");
would also print Hello, world! (on one line of output).

While inputting or outputting data field width can also be specified. This is included in the conversion
string.(if we want to display a floating point number convert to 3 decimal places the conversion string is
“%.3f”).For assigning field width, width is placed before the conversion character
like“%10f”,”%8d”,”%12e” and so on…Also we can display data making correct to a fixed no of decimal
places.
For example if we want to display x=30.2356 as 30.24specification may be “%5.2f” or simply “%.2f”.

CONTROL STATEMENTS

When we run a program, the statements are executed in the order in which they appear in the program.
Also each statement is executed only once. But in many cases we may need a statement or a set of
statements to be executed a fixed no of times or until a condition is satisfied. Also we may want to skip
some statements based on testing a condition. For all these we use control statements .
Control statements are of two types – branching and looping.

BRANCHING
It is to execute one of several possible options depending on the outcome of a logical test ,which is
carried at some particular point within a program.
LOOPING
It is to execute a group of instructions repeatedly, a fixed no of times or until a specified condition is
satisfied.

BRANCHING
1. if else statement
It is used to carry out one of the two possible actions depending on the outcome of a logical test. The
else portion is optional.
The syntax is
If (expression) statement1 [if there is no else part]
Or
If (expression)
Statement 1
else
Statement 2
Here expression is a logical expression enclosed in parenthesis. If expression is true ,statement 1 or
statement 2 is a group of statements, they are written as a block using the braces { }.
Example: 1. if(x<0) printf(“\n x is negative”);
2. if(x<0)
printf(“\n x is negative”);
else
printf(“\n x is non negative”);
3.if(x<0)
{
x=-x;
s=sqrt(x);
}
else
s=sqrt(x);
2. Nested if statement
Within an if block or else block another if – else statement can come. Such statements are called nested
if statements.
The syntax is
If (e1)
s1
if (e2)
s2

else
s3
else
3. Ladder if statement
In order to create a situation in which one of several courses of action is executed we use ladder – if
statements.
The syntax is
If (e1) s1
else if (e2) s2
else if (e3) s3
……………….
else sn
Example: if(mark>=90) printf(“\n excellent”);
else if(mark>=80) printf(“\n very good”);
else if(mark>=70) printf(“\n good”);
else if(mark>=60) printf(“\n average”);
else
printf(“\n to be improved”);
SWITCH STATEMENT
It is used to execute a particular group of statements to be chosen from several available options. The
selection is based on the current value of an expression with the switch statement.
The syntax is:
switch(expression)
{
case value1:
s1
break;
case value 2:
s2
break;
…….
……..
default:
sn
}

All the option are embedded in the two braces { }.Within the block each group is written after the label
case followed by the value of the expression and a colon. Each group ends with ‘break’ statement. The
last may be labelled ‘default’. This is to avoid error and to execute the group of statements in default if
the value of the expression does not match value1, value2,……..

LOOPING
1. The while statement
This is to carry out a set of statements to be executed repeatedly until some condition is satisfied.
The syntax is:
While (expression) statement
The statement is executed so long as the expression is true. Statement can be simple or compound.

Example 1: #include<stdio.h>
while(n > 0)
{
printf("\n");
n = n - 1;
}
Example 2:
#include<stdio.h>
main()
{
int i=1;
while(x<=10)
{
printf(“%d”,i);
++i;
}
}
2. do while statement
This is also to carry out a set of statements to be executed repeatedly so long as a condition is true.
The syntax is:
do statement while(expression)

Example: #include<stdio.h>
main()
{
int i=1;
do
{
printf(“%d”,i);
++i;
}while(i<=10);
}
THE DIFFERENCE BETWEEN while loop AND do – while loop1) In the while loop the condition is
tested in the beginning whereas in the other case it is done at the end.2) In while loop the statements in
the loop are executed only if the condition is true. Whereas in do – while loop even if the condition is
not true the statements are executed at least once.

3. for loop
It is the most commonly used looping statement in C. The general
form is
For(expression1;expression2;expression3)statement
Here expression1 is to initialize some parameter that controls the loopingaction.expression2 is a
condition and it must be true to carry out theaction.expression3 is a unary expression or an assignment
expression.
Example: #include<stdio.h>
main()
{
int i;
for(i=1;i<=10;++i)
printf(“%d”,i);
}
Here the program prints i starting from 1 to 10.First i is assigned the value 1and than it checks whether
i<=10 If so i is printed and then i is increased by one. It continues until i<=10.
An example for finding the average of 10 numbers;

#include<stdio.h>
main()
{
int i;
float x,avg=0;
for(i=1;i<=10;++i)
{
scanf(“%f”,&x);
avg += x;
}
avg /= 10;
printf(“\n average=%f”,avg);
}
Note: Within a loop another for loop can come
Example : for(i=1;i<=10;++i)
for(j=1;j<=10;++j);
The break statement
The break statement is used to terminate4 loop or to exit from a switch. It is used in for, while, do-
while and switch statement.
The syntax is break;
Example 1: A program to read the sum of positive numbers only
#include<stdio.h>
27
main()
{
int x, sum=0;
int n=1;
while(n<=10)
{
scanf(“%d”,&x);
if(x<0) break;
sum+=x;
}
printf(“%d”,sum);
}
Example 2 :A program for printing prime numbers between 1 and 100:
#include <stdio.h>
#include <math.h>
main()
{
int i, j;
printf("%d\n", 2);
for(i = 3; i <= 100; i = i + 1)
{
for(j = 2; j < i; j = j + 1)
{
if(i % j == 0)
break;
if(j > sqrt(i))
{
printf("%d\n", i);
break;
}
}
}
return 0;
}
Here while loop breaks if the input for x is –ve.
The continue statement
It is used to bypass the remainder of the current pass through a loop. The loop does not terminate when
continue statement is encountered, but statements after continue are skipped and proceeds to the next
pass through the loop.
Example : #include<stdio.h>

main()
{
int x, sum=0, n=0;
while(n<10)
{
scanf(“%d”,x);
if(x<0) continue;
sum+=x;
++n;
}
printf(“%d”,sum);
}
GO TO statement
It is used to alter the normal sequence of program execution by transferring control to some other part
of the program .The syntax is goto label ;
Example :
#include<stdio.h>
main( )
{
int n=1,x,sum=0;
while(n<=10)
{
scanf(“%d” ,&x);
if(x<0)goto error;
sum+=x;
++n;
}
Error:
printf(“\n the number is non negative”);
}
Module-2
FUNCTIONS

Functions are programs .There are two types of functions- library functions and programmer written
functions. We are familiarised with library functions and how they are accessed in a C program.
The advantage of function programs are many
1) A large program can be broken into a number of smaller modules.
2) If a set of instruction is frequently used in program and written as function program, it can be used in
any program as library function.
Defining a function.
Generally a function is an independent program that carries out some specific well defined task. It is
written after or before the main function. A function has two components-definition of the function and
body of the function.
Generally it looks like
datatype function name(list of arguments with type)
{
statements
return;
}
If the function does not return any value to the calling point (where the function is accessed) .The syntax
looks like
function name(list of arguments with type)
{
statements
return;
}
If a value is returned to the calling point, usually the return statement looks like return(value).In that case
data type of the function is executed. Note that if a function returns no value the keyword void can be
used before the function name
Example:
(1)
writecaption(char x[] );
{
printf(“%s”,x);
return;
}
(2)
int maximum(int x, int y)
{
int z ;
z=(x>=y)? x : y ;
return(z);
}
(3)
maximum( int x,int y)
{
int z;
z=(x>=y) ? x : y ;
printf(“\n maximum =%d”,z);
return ;
}
Note: In example (1) and (2) the function does not return anything.
Advantages of functions
1. It appeared in the main program several times, such that by making it a function, it can be written just
once, and the several places where it used to appear can be replaced with calls to the new function.
2. The main program was getting too big, so it could be made (presumably) smaller and more manageable
by lopping part of it off and making it a function.
3. It does just one well-defined task, and does it well.
4. Its interface to the rest of the program is clean and narrow
5. Compilation of the program can be made easier.
Accessing a function
A function is accessed in the program (known as calling program)by specifying its name with optional
list of arguments enclosed in parenthesis. If arguments are not required then only with empty parenthesis.
The arguments should be of the same data type defined in the function definition.
Example:
1) int a,b,y;
y=maximum(a,b);
2) char name[50] ;
writecaption(name);
3) arrange();

If a function is to be accessed in the main program it is to be defined and written before the main function
after the pre-processor statements.
Example:
#include<stdio.h>
int maximum (int x,int y)
{
int z ;
z=(x>=y) ? x : y ;
return (z);
}
main( )
{
int a,b,c;
scanf(“%d%d”,&a,&b);
c=maximum(a,b);
printf(“\n maximum number=%d”,c);
}
Function prototype

It is a common practice that all the function programs are written after the main( ) function .when they
are accessed in the main program, an error of prototype function is shown by the compiler. It means the
computer has no reference about the programmer defined functions, as they are accessed before the
definition .To overcome this, i.e to make the compiler aware that the declarations the function referred
at the calling point follow, a declaration is done in the beginning of the program immediately after the
pre-processor statements. Such a declaration of function is called prototype declaration and the
corresponding functions are called function prototypes.
Example 1:
1)
#include<stdio.h>
int maximum(int x,int y);
main( )
{
int a,b,c;
scanf(“%d%d”,&a,&b);
c=maximum(a,b);
printf(“\n maximum number is : %d”,c);
}
int maximum(int x, int y)
{
int z;
z=(x>=y) ? x : y ;
return(z);
}
32
Example 2:
#include<stdio.h>
void int factorial(int m);
main( )
{
int n;
scanf(“%d”,&n);
factorial(n);
}
void int factorial(int m)
{
int i,p=1;
for(i=1;i<=m;++i)
p*=i;
printf(“\n factorial of %d is %d “,m,p);
return( );
}
Note: In the prototype declaration of function, if it return no value, in the place of data-type we use void.
Eg: void maximum(int x,int y);
Passing arguments to a function
The values are passed to the function program through the arguments. When a value is passed to a
function via an argument in the calling statement, the value is copied into the formal argument of the
function (may have the same name of the actual argument of the calling function).This procedure of
passing the value is called passing by value. Even if formal argument changes in the function program,
the value of the actual argument does not change.

Example:
#include<stdio.h>
void square (int x);
main( )
{
int x;
scanf(“%d”,&x);
square(x):
}
void square(int x)
{
x*=x ;
printf(“\n the square is %d”,x);
return;
}
In this program the value of x in the program is unaltered.
Recursion
It is the process of calling a function by itself ,until some specifiedcondition is satisfied. It is used for
repetitive computation ( like finding factorial ofa number) in which each action is stated in term of
previous result.
Example:
#include<stdio.h>
long int factorial(int n);
main( )
{
int n;
long int m;
scanf(“%d”,&n);
m=factorial(n);
printf(“\n factorial is : %d”, m);
}
long int factorial(int n)
{
if (n<=1)
return(1);
else
return(n*factorial(n-1));
}
In the program when n is passed the function, it repeatedly executes calling the same function for n, n-
1, n-2,………………..1.

Arrays
An array is an identifier to store a set of data with common name. Note that a variable can store only a
single data. Arrays may be one-dimensional or multi dimensional.
Defining an array one dimensional arrays
Definition: Arrays are defined like the variables with an exception that each array name must be
accompanied by the size (i.e. the max number of data it can store).For a one dimensional array the size
is specified in a square bracket immediately after the name of the array.
The syntax is
data-type array name[size];
So far, we've been declaring simple variables: the declaration
int i;
declares a single variable, named i, of type int. It is also possible to declare an array of several elements.
The declaration
int a[10];declares an array, named a, consisting of ten elements, each of type int. Simply speaking, an
array is a variable that can hold more than one value.
Eg:
int x[100];
float mark[50];
char name[30];
Note: With the declaration int x[100],computer creates 100 memory cells with name
x[0],x[1],x[2],………,x[99].Here the same identifier x is used but various data are distinguished by the
subscripts inside the square bracket.
Array Initialization
Although it is not possible to assign to all elements of an array at once using an assignment expression,
it is possible to initialize some or all elements of an array when the array is defined. The syntax looks
like this:
int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

The list of values, enclosed in braces {}, separated by commas, provides the initial values for successive
elements of the array.
If there are fewer initializers than elements in the array, the remaining elements are automatically
initialized to 0. For example,
int a[10] = {0, 1, 2, 3, 4, 5, 6};
would initialize a[7], a[8], and a[9] to 0. When an array definition includes an initializer, the array
dimension may be omitted, and the compiler will infer the dimension from the number of initialisers.
For example,
int b[] = {10, 11, 12, 13, 14};
Example :
int x[ ] ={0,1,2,3,4,5}; or
int x[6]={0,1,2,3,4,5};
Even if the size is not mentioned (former case) the values0,1,2,3,4 are stored in
x[0],x[1],x[2],x[3],x[4],x[5].If thestatement is likeint x[3]={0,1,2,3,4,5};then x[0],x[1],x[2] are assigned
the values 0,1,2.
Note: If the statement is likeint x[6]={0,1,2};then the values are stored like x[0]=0, x[1]=1, x[2]=2,
x[3]=0, x[4]=0 and x[5]=0.
Processing one dimensional array
1) Reading arrays: For this normally we use for- loop.
If we want to read n values to an array name called ‘mark’ , the statements looklike
int mark[200],i,n;
for(i=1;i<=n;++i)
scanf(“%d”,&x[i]);
Note: Here the size of array declared should be more than the number of values that are intended to store.
2) Storing array in another:
To store an array to another array. Suppose a and b are two arrays and we want to store that values of
array a to array b. The statements look like
float a[100],b[100];
int I;
for(i=1;i<=100;++i)
b[i]=a[i];
36
Problem: To find the average of a set of values.
#include<stdio.h>
main( )
{
int x,i;
float x[100],avg=0;
printf(“\n the no: of values “);
scanf(“%d”,&n);
printf(“\n Input the numbers”);
for(i=1;i<=n;++i)
{
scanf(“%f”,&x[i]);
avg=avg+x[i];
}
avg=avg/n;
printf(“\n Average=%f”,avg);
}
PASSING ARRAYS TO FUNCTION
Remember to pass a value to a function we include the name of the variable as an argument of the
function. Similarly an array can be passed to a function by including array name(without brackets) and
size of the array as arguments. In the function defined the array name together with empty square
brackets is an argument.
Ex:
(calling function)-avg=average(n,x); where n is the size of the data stored in the array x[].(function
defined)- float average(int n,float x[]);
Now let us see to use a function program to calculate the average of a set of values.
#include<stdio.h>
float average(int n,float y[]);
main()
{
int n;
float x[100],avg;
printf(“\n Input the no: of values”);
scanf(“%d”,&n);
printf(“\n Input the values”);
for(i=1;i<=n;++i)
scanf(“%f”,&x[i]);
avg=average(n,x);
printf(“\n The average is %f”,avg);
}
float average(int n, float y[]);
{
float sum=0;
int i;
for(i=1;i<=n;++i)
sum=sum+y[i];
sum=sum/n;
return(sum);
}
Note:
1) In the function definition the array name together with square brackets is the argument. Similarly in
the prototype declaration of this function too, the array name with square brackets is the argument
2) We know that changes happened in the variables and arrays that are in function will not be reflected
in the main (calling) program even if the same names are usual. If we wish otherwise the arrays and
variables should be declared globally. This is done by declaring them before the main program.
Ex:
#include<stdio.h>
void arrange(int n,float x[]);
main();
{
………..
arrange(n,x);
…………..
}
arrange(int n,float x[]);
{
……….
return;
}
MULTI-DIMENSIONAL ARRAYS
Multi-dimensional arrays are defined in the same manner as one dimensional arrays except that a separate
pairof square brackets is required to each subscript.
Example: float matrix[20][20] (two dimensional)
Int x[10][10][5] (3-dimensional)
Initiating a two dimensional array we do as int x[3][4]={1,2,3,4,5,6,7,8,9,10,11,12}
Or
int x[3][4]={
{1,2,3,4};
{5,6,7,8};
{89,10,11,12};
}
NOTE: The size of the subscripts is not essential for initialization. For reading atwo dimensional array
we use two for-loop.
Example:
for(i=1;i<=2;++i)
for(j=1;j<=3;++j)
scanf(“%f”,&A[i][j]);

NOTE: If x[2][3] is a two dimensional array, the memory cells are identified withname
x[0][0],x[0][1],x[0][2],x[1][0],x[1][1] and x[1][2].
ARRAYS AND STRINGS.
A string is represented as a one dimensional array of character type.
Example : char name[20];
Here name is an array that can store a string of size 20.
If we want to store many strings(like many names or places) two dimensional arrayis used. Suppose we
want to store names of 25 persons, then declare name as char name[25][ ]. Note that the second square
bracket is kept empty if the length of string is not specified.
If the declaration is char name[25][30], 25 names of maximum size 30 can bestored. The various names
are identified by name[0], name[1], name[2],……..,name[24]. These names are read by the command
For( i=0; i<25,++i)
scanf( “%[^\n]”, name(i));
PROGRAM STRUCTURE
STORAGE CLASS

Earlier we mentioned that variables are characterized by their data type like integer, floating point type,
character type etc. Another characteristic of variables or arrays is done by storage class. It refers to the
permanence and scope of variables or arrays within a program. There are 4 different storage class
specification in C – automatic, external, static, and register. They are identified by the key words auto,
external, static, and register respectively.

AUTOMATIC VARIABLES
They are declared in a function. It is local and its scope is restricted to that function. They are called so
because such variables are created inside a function and destroyed automatically when the function is
exited. Any variable declared in function is interpreted as an automatic variable unless specified
otherwise. So the keyword auto is not required at the beginning of each declaration.

EXTERNAL VARIABLE (GLOBAL VARIABLE)

The variables which are alive and active throughout the entire program are called external variables. It
is not cantered to a single function alone, but its scope extends to any function having its reference. The
value of a global variable can be accessed in any program which uses it. For moving values forth and
back between the functions, the variables and arrays are declared globally i.e., before the main
program. The keyword external is not necessary for such declaration, but they should be mentioned
before the main program.
STATIC VARIABLES
It is, like automatic variable, local to functions is which it is defined. Unlike automatic variables static
variable retains values throughout the life of the program, i.e. if a function is exited and then re-entered
at a later time the static variables defined within the function will retain their former values. Thus this
feature of static variables allows functions to retain information permanently through out the execution
of the program. Static variable is declared by using the keyword static.
Example : static float a ;
Static int x ;
Consider the function program:
# include<stdio.h>
long int Fibonacci (int count )
main()
{
int i, m=20;
for (i =1 ; i < m ; ++i)
printf( “%ld\t”,fibonacci(i));
}
long int Fibonacci (int count )
{
static long int f1=1, f2=1 ;
long int f ;
f = (count < 3 ) ? 1 : f1 + f2 ;
f2 = f1
f1= f ;
return (f ) ;}
In this program during the first entry to the function f1 and f2 are assigned 1, later they are replaced by
successive values of f1 and f. as f1 and f2 are declared static storage class. When the function is exited
the latest values stored inf1 and f2 will be retained and used when the function is re-entered.
Module-3
Pointers
A pointer is a variable that represents the location or address of a variable or arrayelement.

Uses
1. They are used to pass information back and forth between a function and calling point.
2. They provide a way to return multiple date items.
3. They provide alternate way to access individual array elements.
When we declare a variable say x, the computer reserves a memory cell with name x. the data stored in
the variable is got through the name x. another way to access data is through the address or location of
the variable. This address of x is determined by the expression &x, where & is a unary operator (called
address operator). Assign this expression &x to another variable px(i.e. px=&x).this new variable px is
called a pointer to x (since it points to the location of x. the data stored in x is accessed by the expression
*px where * is a unary operator called the indirection operator.
Ex: if x=3 and px=&x then *px=3

Declaration and Initialisation


A pointer variable is to be declared initially. It is done by the syntax.
Data type *pointer variable
Int *p declares the variable p as pointer variable pointing to a an integer type data. Itis made point to a
variable q by p= &q. In p the address of the variable q is stored.
The value stored in q is got by *p.
If y is a pointer variable to x which is of type int, we declare y as int *y ;
Ex: float a;
float *b;
b=&a;
Note : here in ‘b’ address of ‘a’ is stored and in ‘*b’ the value of a is stored.
Passing pointers to a function

Pointers are also passed to function like variables and arrays are done. Pointers are normally used for
passing arguments by reference (unlike in the case if variable and arrays, they are passed by values).
When data are passed by values the alteration made to the data item with in the function are not carried
over to the calling point; however when data are passed by reference the case is otherwise. Here the
addressor data item is passed and hence whatever changes occur to this with in the function, it will be
retained through out the execution of the program. So generallypointers are used in the place of global
variables.
Ex: ):
#include<stdio.h>
void f(int*px, int *py
main()
{
int x = 1;
int y=2;
f(&X,&y);
printf(“\n %d%d”, x,y);
}
Void f(int *px, int *py);
*px=*px+1;
*py=*py+2;
return;
42
}
Note:
1. Here the values of x and y are increased by 1 and 2 respectively.
2. Arithmetic operations *, +, -, / etc can be applied to operator variable also.
Pointer and one dimensional arrays
An array name is really a pointer to the first element in the array i.e. if x is a one-dimensional array, the
name x is &x[0] and &x[i] are x + i for i= 1,2,……. So to read array of numbers we can also use the
following statements
int x[100],n;
for (i=1 ; i<=n; ++i)
scanf (‘%d”, x + i ) (in the place of scanf (“%d”,&x[i] ) )
Note : the values stored in the array are got by * ( x + i ) in the place x[i].
Dynamic memory allocation
Usually when we use an array in c program, its dimension should be more than enough or may not be
sufficient. To avoid this drawback we allocate the proper (sufficient) dimensions of an array during the
run time of the program with the helpof the library functions called memory management functions like
‘malloc’,‘calloc’, ‘realloc’ etc. The process of allocating memory at run time is known as
dynamic memory allocation.
Ex;
To assign sufficient memory for x we use the following statementx= (int *) malloc (n* sizeof (int) ) , for
in the place of initial declaration int x[n]Similarly in the place of float y [100] we use y = (float *) malloc
(m* sizeof(float) );

Example to read n numbers and find their sum


main()
{
int *x, n, i, sum=0;
printf(“\n Enter number of numbers”);
scanf(“%d”, &n);
x=(int *)malloc(n * sizeof(int));
for(i=1;i<=n,++i)
{
scanf(“%d”, x+i):
sum += *(x+i);
}
printf(“\nThe sum is %d ”, sum);
}
Passing function to other function
A pointer to a function can be passed to another pointer as an assignment. Here it allows one function to
be transferred as if the function were a variable.

Pointer Arithmetic in C Programming


We can perform arithmetic operations on pointer variable just as you can a numeric value. As we
know that, a pointer in C is a variable which is used to store the memory address which is a numeric
value. The arithmetic operations on pointer variable affects the memory address pointed by pointer.

Valid Pointer Arithmetic Operations


→Adding a number to pointer.
→Subtracting a number form a pointer.
→Incrementing a pointer.
→Decrementing a pointer.
→Subtracting two pointers.
→Comparison on two pointers.
Invalid Pointer Arithmetic Operations
→Addition of two pointers.
→Division of two pointers.
→Multiplication of two pointers.

Incrementing a Pointer
Let ptr be an integer pointer which points to the memory location 5000 and size of an integer variable
is 32-bit(4 bytes). Now, when we increment pointer ptr

ptr++;

it will point to memory location 5004 because it will jump to the next integer location which is 4 bytes
next to the current location. Incrementing a pointer is not same as incrementing an integer value. On
incrementing, a pointer will point to the memory location after skipping N bytes, where N is the size of
the data type(in this case it is 4).

ptr++ is equivalent to ptr + (sizeof(pointer_data_type)).

"Incrementing a pointer increases its value by the number of bytes of its data type"
A character(1 bytes) pointer on increment jumps 1 bytes.
An integer(4 bytes) pointer on increment jumps 4 bytes.
This is a very important feature of pointer arithmetic operations which we will use in array traversal
using pointers.

Decrementing a Pointer
Similarly, Decrementing a pointer will decrease its value by the number of bytes of its data type.
Hence, after

ptr--;

ptr will point to 4996.

ptr--; is equivalent to ptr - (sizeof(pointer_data_type)).

Adding Numbers to Pointers


Adding a number N to a pointer leads the pointer to a new location after skipping N times size of data
type.

ptr + N = ptr + (N * sizeof(pointer_data_ype))

For example, Let ptr be a 4-byte integer pointer, initially pointing to location 5000.
Then ptr + 5 = 5000 + 4*5 = 5020. Pointer ptr will now point at memory address 5020.
Subtracting Numbers from Pointers
Subtracting a number N from a pointers is similar to adding a number except in Subtraction the new
location will be before current location by N times size of data type.

ptr - N = ptr - (N * sizeof(pointer_data_ype))

For example, Let ptr be a 6-byte double pointer, initially pointing to location 5000.
Then ptr - 3 = 5000 - 6*3 = 4982. Pointer ptr will now point at memory address 4982.

Subtracting Pointers
We can take difference between two pointer which returns the number of bytes between the address
pointed by both the pointers.
For example, if a pointer 'ptr1' points at memory location 10000 and pointer 'ptr' points at memory
location 10008, the result of ptr2 - ptr1 is 8.
C program to show pointer arithmetic

#include<stdio.h>
#include<conio.h>

void main() {
int int_var = 10, *int_ptr;
char char_var = 'A', *char_ptr;
float float_val = 4.65, *float_ptr;

/* Initialize pointers */
int_ptr = &int_var;
char_ptr = &char_var;
float_ptr = &float_val;

printf("Address of int_var = %u\n", int_ptr);


printf("Address of char_var = %u\n", char_ptr);
printf("Address of float_var = %u\n\n", float_ptr);

/* Incrementing pointers */
int_ptr++;
char_ptr++;
float_ptr++;
printf("After increment address in int_ptr = %u\n", int_ptr);
printf("After increment address in char_ptr = %u\n", char_ptr);

printf("After increment address in float_ptr = %u\n\n", float_ptr);


/* Adding 2 to pointers */
int_ptr = int_ptr + 2;
char_ptr = char_ptr + 2;
float_ptr = float_ptr + 2;

printf("After addition address in int_ptr = %u\n", int_ptr);


printf("After addition address in char_ptr = %u\n", char_ptr);
printf("After addition address in float_ptr = %u\n\n", float_ptr);

getch();
return 0;
}

Program Output
Address of int_var = 2293300
Address of char_var = 2293299
Address of float_var = 2293292

After increment address in int_ptr = 2293304


After increment address in char_ptr = 2293300
After increment address in float_ptr = 2293296

After addition address in int_ptr = 2293312


After addition address in char_ptr = 2293302
After addition address in float_ptr = 2293304
Structures and Unions
We know an array is used to store a collection of data of the same type. But if we want to deal with a
collection of data of various type such as integer, string, float etc we use structures in C language. It is a
method of packing data of different types. It is a convenient tool for handling logically related data items
of bio-data people comprising of name, place, date etc. , salary details of staff comprising of
name, pay da, hra etc.
Defining a structure.
In general it is defined with the syntax name struct as follows
Struct structure_name
{
Data type variable1;
Data type variable2;
44

}
For example
1 Struct account
{
Int accountno
Char name[50];
Float balance;
}customer[20]
Note :1 here accountno, name and balance are called members of the structure.
2 struct date
{
Int month;
Int day;
Int year;
}dateofbirth;
In these examples customer is a structure array of type account and date of birth is a structural type of
date.
Within a structure members can be structures. In the following example of bio data structure date which
is a structure is a member.
For example
struct date
{
Int day;
Int month;
Int year;
}
Struct biodata
{
Name char[30];
Int age ;
Date birthdate;
}staff[30];
Here staff is an array of structure of type biodataNote: we can declare other variables also of biodata
type structure as follows.
Struct biodata customer[20]; , Struct biodata student; etc

Processing a structure
The members of a structure are themselves not variable. They should be linked to the structure variable
to make them meaningful members. The linking is done byperiod (.)
If staff[] is structure array then the details of first staff say staff[1] is got bystaff[1].name, staff[1].age,
staff[1].birthdate.day, staff[1].birthdate.month,staff[1].birthdate.year . we can assign name, age and
birthdate of staff[1] by
Staff[1].name=”Jayachandran”
staff[1].age=26
staff[1].birthdate.day=11
staff[1].birthdate.month=6
staff[1].birthdate.year=1980
If ‘employee’ is a structure variable of type biodata as mentioned above then thedetails of ‘employee’ is
got by declaring ‘employee as biodata type by thestatementbiodata employee;
The details of employee are got by employee.name, employee.age,employee.birthdate.year etc.
Note:
Structure initialisation
Like any other variable or array a structure variable can also be initalised.by using
syntax static
Struct record
{
Char name[30];
Int age;
Int weight;
}
Static struct record student1={“rajan”, 18, 62}
Here student1 is of record structure and the name,age and weight are initialised as“rajan”, 18 and 62
respectively.
1 Write a c program to read biodata of students showing name, place, pin,phone and grade
Solution
#include<stdio.h>
Main()
{
Struct biodata
{
Char name[30];
Char Place[40]
Int pin;
Long Int phone;
Char grade;
};
struct biodata student[50];
int n;
printf(“\n no of students”);
scanf(“%d”,n);
for(i=1;i<=n;++i)
{
scanf(“%s”,student[i].name);
scanf(“%s”,student[i].place);
scanf(“%d”,student[i].pin);
scanf(“%ld”,student[i].phone);
scanf(“%c”,student[i].grade);
}
}
User Defiined Data Type
This is to define new data type equivalent to existing data types. Once defined auser-defined data type
then new variables can be declared in terms of this new data type. For defining new data type we use the
syntax typedef as followstypedef type new-type.
Here type refers to existing data type
For example
Ex1:
typedef int integer;
Now integer is a new type and using this type variable, array etc can be defined as
Integer x;
Integer mark[100];
47
Ex2:
typedef struct
{
int accno;
char name[30];
float balance;
}record;
Now record is structure type using this type declare customer, staff as record type Record customer;
Record staff[100];
Passing structures to functions
Mainly there are two methods by which structures can be transferred to and from a function.
1 Transfer structure members individually
2 Passing structures as pointers (ie by reference)
Example 1
#include<stdio.h>
typedef struct
{
int accno;
char name[30];
float balance;
}record;
main()
{
…..
Record customer;
.....
Customer.balance=adjust(customer.name,customer.accno,balance)
.....
}
float adjust(char name[], int accnumber, float bal)
{
float x;
.....
X=
.....
return(x);
}
Example 2
#include<stdio.h>
typedef struct
{
int accno;
char name[30];
float balance;
}record;
main()
{
Record customer;
void adjust(record *cust)
......
Adjust(&customer);
printf(“\n %s\t%f”,coustomer.name,customer.balance)
}
void adjust(record *cust)
{
float x;
....
Cust->balance=...
....
Return;
}
In the first example structure members are passed individually where as in the second case customer is
passed entirely as a pointer named cust. The values of structure members are accessed by using -> symbol
like cust->.name, cust->balance etc.
Unions
Union is a concept similar to a structure with the major difference in terms of storage. In the case of
structures each member has its own storage location, but a union may contain many members of different
types but can handle only one at a time. Union is also defined as a structure is done but using the syntax
union.
union var
{
int m;
char c;
float a;
}
union var x;
Now x is a union containing three members m,c,a. But only one value can be storedeither in x.m, x.c or
x.a
Data Files
Data Files are to store data on the memory device permanently and to access whenever is required.
There are two types of data files
1 Stream Oriented data files
2 System Oriented data files
Stream oriented data files are either text files or unformatted files. System oriented data files are more
closely related to computer’s operating system and more complicated to work with. In this session we
go through stream oriented data files.

Opening and Closing data files


The first step is to create a buffer area where information is stored temporarily before passing to computer
memory. It is done by writing
File *fp;
Here fp is the pointer variable to indicate the beginning of the buffer area and called stream pointer .
The next step is to open a data file specifying the type i.e. read only file , write only file , read /write file.
This is done by using the library function fopen.
The syntax is
fp=fopen(filename,filetype)
The filetype can be
1 ‘r’ ( to open an existing file for reading only)
2 ‘w’ ( to open a new file for writing only. If file with filename exists, it will be destroyed and a new file
is created in its place)
3 ‘a’ ( to open an existing file for appending. If the file name does not exist a new file with that file name
will be created)
4 ‘r+’ ( to open an existing file for both reading and writing)
5 ‘w+’ ( to open a new file for reading and writing. If the file exists with that name, it will be destroyed
and a new one will be created with that name)
6 ‘a+’ ( to open an existing file for reading and writing. If the file does not exist a new file will be
created).
For writing formatted data to a file we use the function fprintf. The syntax is fprintf(fp,”conversion
string”, value);
For example to write the name “rajan” to the file named ‘st.dat’
File *fp;
fp=fopen(“st.dat”,’w’);
fprintf(fp,”%[^\n]”,”rajan”);
The last step is to close the file after the desired manipulation. This is done by thelibrary function fclose.
The syntax isfclose(fp);
Example
1 To create a file of biodata of students with name ‘st.dat’.
#include<stdio.h>
#include<string.h>
tpedef struct
{
int day;
int month;
int year;
}date;
typedef Struct
{
char name(30);
char place(30);
int age;
date birthdate;
}biodata;
main()
{
File *fp;
biodata student;
fp=fopen(“st.dat”,’w’);
printf(“Input data”);
scanf(“%[^\n]”,student.name);
scanf(“%[^\n]”,student.place);
scanf(“%d”,&student.age);
scanf(“%d”,&student.birthdate.day);
scanf(“%d”,&student.birthdate.month):
scanf(“%d”,&student.birthdate.year);
fprintf(fp,”%s%s%d%d%d%d”,student.name,student.place,student.age,student.birthdate.day,
student.birthdate.month,student.birthdate.year)
fclose(fp);
}
Example 2:
To write a set of numbers to a file.
#include<stdio.h>
main()
{
file *fp;
int n; float x
fp=fopen(“num.dat”,’w’);
printf(“Input the number of numbers”);
scanf(“%d”,&n);
for(i=1;i<=n;++i)
{
scanf(“%d”,&x);
fprintf(fp,”%f\n”,x);
}
fclose(fp);
}
Processing formatted data File
To read formatted data from a file we have to follow all the various steps that discussed above. The file
should be opened with read mode. To open the existing file ‘st.dat’ write the following syntax
file *fp;
fp=fopen(“st.dat”, ‘r+’);
For reading formatted data from a file we use the function fscanf.
Example:
typedef struct
{
int day;
int month;
int year;
}date;
typedef Struct
{
char name(30);
char place(30);
int age;
date birthdate;
}biodata;
main()
{
File *fp;
biodata student;
fp=fopen(“st.dat”,’r+’);
fscanf(fp,”%s”,student.name);
printf(“%s”,student.name);
fclose(fp);
}
C program to check odd or even

#include<stdio.h>
#include<conio.h>
void main()
{
int no;
clrscr();
printf("Enter any number: ");
scanf("%d",&no);
if(no%2==0)
printf("Even num");
else
printf("Odd num");
getch();
}

Prime number program in C

#include<stdio.h>
#include<conio.h>
void main()
{
int i,no;
clrscr();
printf("Enter any num: ");
scanf("%d",&no);
if(no==1)
printf("Smallest Prime no. is 2");
for(i=2;i<no;i++)
{
if(no%i==0)
{
printf("Not Prime no.");
break;
}
}
if(no==i)
printf("Prime no.");
getch();
}

Calculator program in C

#include<stdio.h>
#include<conio.h>
void main()
{
char choice;
int a,b,res=0;
clrscr();
printf("Enter First value: ");
scanf("%d",&a);
printf("\n Enter Operator: ");
choice=getch();
printf("\n Enter Second value: ");
scanf("%d",&b);
switch(choice)
{
case'+':
res=a+b;
printf("Sum: %d",res);
break;
case'-':
res=a-b;
printf("Difference: %d",res);
break;
case'*':
res=a*b;
printf("Product: %d",res);
break;
case'/':
res=a/b;
printf("Quotient: %d",res);
break;
default:
printf("Enter Valid Operator!!");
}
getch();
}

program factorial of number

#include<stdio.h>
#include<conio.h>
void main()
{
int i,no, fact=1;
clrscr();
printf("Enter the any no. : ");
scanf("%d",&no);
for(i=1;i<=no;i++)
{
fact=fact*i;
}
printf("Factorial =%d ",fact);
getch();
}

C Program to reverse any number using while loop

#include<stdio.h>
#include<conio.h>
void main()
{
intno,rev=0,r,a;
clrscr();
printf("Enter any num: ");
scanf("%d",&no);
a=no;
while(no>0)
{
r=no%10;
rev=rev*10+r;
no=no/10;
}
printf("Reverse of %d is: %d",a,rev);
getch();
}

Find number of digits from any numbers

#include<stdio.h>
#include<conio.h>
void main()
{
intno,a=0;
clrscr();
printf("Enter any number: ");
scanf("%d",&no);
while(no>0)
{
no=no/10;
a++;
}
printf("Number of digits in given number is: %d",a);
getch();
}

Print fibonacci series

#include<stdio.h>
#include<conio.h>
void main()
{
int i,no, first=0, second=1,next;
clrscr();
first=0;
second=1;
printf("Enter nubmer of terms for Series: ");
scanf("%d",&no);
printf("Fibonacci series are:\n");
for(i=0; i<no; i++)
{
printf("%d\n",first);
next= first + second;
first = second;
second =next;
}
getch();
}

Armstrong number program in C

#include<stdio.h>
#include<conio.h>
void main()
{
int arm=0,a,b,c,d,num;
clrscr();
printf("Enter any number: ");
scanf("%d",&num);
temp=num;
while(temp>0)
{
a=temp%10;
temp=temp/10;
arm=arm+a*a*a;
}
if(arm==num)
printf("%d is armstrong number",num);
else
printf("%d is not armstrong number", num);
getch();
}
program check palindrome number

#include<stdio.h>
#include<conio.h>
void main()
{
int a,no,b,temp=0;
clrscr();
printf("Enter any num: ");
scanf("%d",&no);
b=no;
for(;no>0;)
{
a=no%10;
no=no/10;
temp=temp*10+a;
}
if(temp==b)
printf("Palindrome number");
else
printf("Not Palindrome number");
getch();
}

program to find hcf of two numbers

#include<stdio.h>
#include<conio.h>
void gcd(int,int);
void main()
{
int a,b;
clrscr();
printf("Enter two numbers: ");
scanf("%d %d",&a,&b);
gcd(a,b);
getch();
// return 0;}
//function to calculate g.c.d
void gcd(int a,int b)
{
int m,n;
m=a;
n=b;
while(m!=n)
{
if(m>n)
m=m-n;
else
n=n-m;
}
printf("\nH.C.F of %d and %d is: %d",a,b,m);
}

program to reverse any string

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[100],temp;
int i,j=0;
clrscr();
printf("Enter any the string :");
gets(str);// gets function for input string
i=0;
j=strlen(str)-1;
while(i<j)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
i++;
j--;
}
printf("Reverse string is :%s",str);
getch();
}

Program to find frequency of characters

#include<stdio.h>
#include<conio.h>
void main()
{
int i,count=0;
char ch[20],c;
clrscr();
printf("Enter Any String: ");
gets(ch);
printf("Enter any Character form string: ");
scanf("%c",&c);
for(i=0;ch[i]!='\0';i++)
{
if(ch[i]==c)
count++;
}
if(count==0)
printf("Given character not found");
else
printf("Repetition of %c is %d times",c,count);
getch();
}

program to count number of consonants

#include<stdio.h>
#include<conio.h>
void main()
{
char line[150];
int i,v,c,ch,d,s,o;
o=v=c=ch=d=s=0;
clrscr();
printf("Enter a line of string:\n");
gets(line);
for(i=0;line[i]!='\0';++i)
{
if(line[i]=='a'|| line[i]=='e'|| line[i]=='i'|| line[i]=='o'|| line[i]=='u'|| line[i]=='A'|| line[i]=='E'|| line[i]=='I'||
line[i]=='O'|| line[i]=='U')
++v;
elseif((line[i]>='a'&& line[i]<='z')||(line[i]>='A'&& line[i]<='Z'))
++c;
elseif(line[i]>='0'&& line[i]<='9')
++d;
elseif(line[i]==' ')
++s;
}
printf("Vowels: %d",v);
printf("\nConsonants: %d",c);
printf("\nDigits: %d",d);
printf("\nWhite spaces: %d",s);
getch();
}

program to copy first string into second string

#include<stdio.h>
#include<conio.h>
void main()
{
char s1[100], s2[100], i;
clrscr();
printf("Enter string s1: ");
scanf("%s",s1);
for(i=0; s1[i]!='\0';++i)
{
s2[i]=s1[i];
}
s2[i]='\0';
printf("String s2: %s",s2);
getch();
}
Program to calculate sum of digits

#include<stdio.h>
#include<conio.h>
void main()
{
int a,no,sum=0;
clrscr();
printf("Enter any number: ");
scanf("%d",&no);
while(no>0)
{
a=no%10;
no=no/10;
sum=sum+a;
}
printf("\nSum of Digits: %d",sum);
getch();
}

Program to find ascii value of number

#include<stdio.h>
#include<conio.h>
void main()
{
int value;
clrscr();
printf("Enter any Character/Symbol/Digits: ");
value=getch();
printf("\n\Ascii value of %c is %d",value,value);
getch();
}
C Program to Swap two numbers using Pointers

Example

#include<stdio.h>
#include<conio.h>
int main()
{
int x,y,*b,*a,temp;
clrscr();
printf("Enter any two number : ");
scanf("%d%d",&x,&y);
printf("Before swapping : x= %d and y=%d\n",x,y);
a =&x;
b =&y;
temp =*a;
*a =*b;
*b = temp;
printf("After swapping : x= %d and y=%d\n",x,y);
getch();
}

Program to calculate grade of student

#include<stdio.h>
#include<conio.h>
void main()
{
int no, i;
float marks[10], per=0, total=0;
clrscr();
printf("Enter number of subject: ");
scanf("%d",&no);
printf("Enter marks of %d subject: ",no);
for(i=0; i<no; i++)
{
scanf("%f",&marks[i]);
}
for(i=0; i<no; i++)
{
total=total+marks[i];
}
per=total/no;
printf("Percentage: %f % \n",per);
if(per>85) {
printf("A grade");
}
else if(per<85 && per>=75)
{
printf("B grade");
}
else if(per<75 && per>=50)
{
printf("C grade");
}
else if(per<50 && per>=30)
{
printf("D grade");
}
else
{
printf("Fail");
}
getch();
}

Program to convert celsius to fahrenheit

#include<stdio.h>
#include<conio.h>
void main()
{
float cel, far;
clrscr();
printf("Enter temp. in Celsius: ");
scanf("%f",&cel);
far = cel * 9/5 + 32;
printf("Temp. in Fahrenheit: %f",far);
getch();
}

Find table of any number

#include<stdio.h>
#include<conio.h>
void main()
{
int i,no,table=1;
clrscr();
printf("Enter any number : ");
scanf("%d",&no);
printf("Table of %d \n",no);
for(i=1;i<=10;i++)
{
table=no*i;
printf("%d",table);
printf("\n");
}
getch();
}

You might also like