C Programming Unit-I - Introduntion
C Programming Unit-I - Introduntion
C Programming Unit-I - Introduntion
UNIT-I ---INTRODUNTION
INTRODUCTION:
The system unit is the cabinet that contains many of the computer’s working
components. One of the most important of these components is the central
processing unit (normally referred to as the CPU). The CPU, a small electronic
circuit chip, is the heart of the computer system and is the device that allows the
machine to perform its complex mathematical and logic functions. The CPU is
considered the “brains” of the computer system.
Floppy disk drives can hold 3.5” floppy disks. The floppy drive is generally referred
to as drive A:. Since most new computers have omitted the floppy drive as a storage
medium option, those computers do not contain an A: drive. High-capacity Zip
drives holds 750 MB of data. A CD (compact disk) provides 650-700 MB of storage.
A DVD (digital video disk or digital versatile disk) has a capacity of 4.7 GB. CDs
and DVDs are durable storage and have a higher tolerance for temperature
fluctuations then hard disk, floppy disks, and tapes. They are unaffected by magnetic
fields and dust and dirt can be cleaned off easily.
Printers
A printer is used to produce a “hard” or printed copy of the information
stored in the
computer system. Ink-jet printers produce characters by spraying ink onto the
paper. The print head is a matrix of fine spray nozzles. Color ink-jet printers have
excellent resolution and print at a respectable rate. Ink-jet printers provide low-cost,
high-quality print on plain paper.
Operating System
An operating system controls the resources and components of the computer. It
consists of
many specialized programs, each of which performs a special task. One task
controlled by the operating system is the allocation of the computer’s RAM to
application programs. The operating system is also responsible for the
synchronization of hardware components such as the monitor, printer, and disk
drives.
Applications Software
Application software refers to the programs written to perform useful functions.
The most
popular application programs are described below:
• Word processing software, such as Microsoft Word, is used for producing reports,
letters, papers, and manuscripts.
• Desktop publishing software, such as Adobe In-Design, helps you use graphic
design techniques to enhance the format and appearance of documents such as
newsletters, brochures, newspapers, and magazines.
• Web authoring software, such as Microsoft FrontPage or Macromedia
Dreamweaver, helps you design and develop customized Web pages.
• Spreadsheet software, such as Microsoft Excel, helps you create worksheets to
perform calculations, create “what-if” analyses, and graph data.
• Database software, such as Microsoft Access, helps you keep track of related data
and records. Other functions include finding, organizing, updating, and reporting
information stored in more than one file.
• Presentation software, such as Microsoft PowerPoint, helps you to combine text,
graphics, animation, and sound into a series of electronic slides.
• E-mail software, such as Microsoft Outlook, helps you to send and receive e-mail
messages over the Internet.
ALGORITHM
An Algorithm is a step by step procedure to solve a given problem
Example 14) Algorithm to find the sum of digits of a given integer number
Step 1 : Read N Step 2: Sum = 0
Step 3 : Digit = N % 10
Step 4 : Sum = Sum + Digit
Step 5 : N = N / 10
Step 6 : If N > 0 then Goto step 3
Step 7 : Print Sum
Step 8 : Stop
Example 15) Algorithm to find LCM of two given numbers
Step 1: Read M, N
Step 2: A = M, B = N Step 3: Temp = M % N Step 4: M = N
Step 5: N = Temp
Step 6: if N > 0 then goto Step 2
Step 7: GCD = M
Step8: LCM = A*B/GCD Step 9: Print LCM
Step 10: Stop
Example 16) Algorithm to find total marks, average and result of a student
Step 1 : Read stno,m1,m2,m3
Step 2: Tot=m1+m2+m3
Step 3 : Avg=tot/3
Step 4 : if m1<35 or m2<35 or m3<35 then
Result = Fail
Else
Result = pass
Step 5 : Print Tot,Avg,Result
Step 6 : Stop
FLOWCHART
The most difficult and important task within programming is the systematic and
careful analysis of a whole problem. Therefore, before going to actual
programming, a programmer should always go through the following steps in a
sequential order.
The most difficult and important task within programming is the systematic and
careful analysis of a whole problem. Therefore, before going to actual
programming, a programmer should always go through the following steps in a
sequential order.
The oval represents any terminal point in a program and generally contains such
words as BEGIN, START, END or STOP.
ii) Input/Output:
The parallelogram represents the Input/Output function i.e. making data availiable for
processing (input) or recording of the processed information (output). This step
implies obtaining a number from an Input device (say, the keyboard and storing it in the
storage location names ‘A’).
Big b Big a
Display
sum
A diamond shaped box is used to show a comparison. If the answer is “yes” the
path named with yes will be chosen otherwise the path named with “no” will be
chosen.
Start
Read a, b, c
Big a
Is b>big T
F Big
Is c>big
T
Large
Big c
F
T
Display big
Stop
Is
Count< n
Stop
Big 0
X=1
Count 0 Y=1
Print X,Y
Read
I=2
Is
num > big T
Z=X+Y
F Big
Print Z
Count X=YY=Z
Is
T I=I+1
Count <n
Yes
I <= N
F
No
Display
STOP
Stop
History of C:
C was originally developed in the 1970’s by Dennis Ritchie at Bell Telephone
Laboratories, Inc. It is an outgrowth of two earlier languages, called BCPL and B, which
were also developed at Bell Laboratories.
When editing is over, the file is saved on disk which can be referred later by its name. the
program that is entered into the file is known as the source program.
Linking the program: Linking is the process of putting together other program files and
functions that are required by the program. The compiled and linked program is called the
executable object code
Some times the program may request for some data to be entered through the keyboard.
When there is wrong with the program logic or data, then it is necessary to correct the source
program or data.
In case the source program is modified the entire process of compiling, linking and executing the
program should be repeated.
STRUCTURE OF A C PROGRAM:
Every C program consists of one or more functions, one of, which must be called main().
The program will always begin by executing the main() function. Additional
function definitions may precede or follow main.
Documentation Section:
The Documentation Section consists of a set of comment lines giving the name of the
program, the author and other details, which the programmer would like to use later.
Link Section:
The link Section provides instructions to the compiler to link functions from the system
library.
Definition section:
The definition section defines all symbolic constants.
Global Declaration Section:
The Global declaration section declares all the global variables that are used in more than one
function. This section also declares all the user-defined functions.
Every C Program must have one main() function section. This Section consists of two parts.
1. Declaration part
2. 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 appear between the opening brace and
closing braces.
The program execution begins at the opening brace and ends at the closing brace. The closing
brace of the main function is the logical end of the program. All Statements in the declaration and
executable parts end with a semicolon (;).
The sub program section contains all the user-defined functions that are called in the main
function. User defined functions are generally placed immediately after the main function,
although they may appear in any order.
All functions except the main function may be absent when they are not required. Sample C
Program:
KEYWORDS:
Every c word is classified as either a keyword or an identifier. All keywords have a fixed
meanings and these meanings cannot be changed. All keywords must be written in lower
case. The list of all keywords in ANSI C are listed below
IDENTIFIERS:
Identifiers are names given to various program elements, such as variables, functions and
arrays. Identifiers consist of letters and digits, in any order, except that the first character must be
a letter. Both uppercase and lowercase are permitted. Upper and lowercase letters are not
interchangeable. i.e. upper case letter is not equivalent to the corresponding lowercase letter.
The under score character ( _ ) can also be included, and is considered to be a letter. An
underscore is often used in the middle of an identifier.
Valid Identifiers:
x y12 sum
sum area name
TABLE tax_rate
Invalid Identifiers:
4th “x”
St no
DATA TYPES: C supports several different types of data, each of which may be
represented differently within the computer’s memory.
int integer
char single character
float floating-point number
double double precision floating point number
Number containing a decimal point and/or an exponent. Exponent which may be larger in
magnitude.
Qualifiers: Short Long Signed Unsigned
Integer quantities can be defined as
Short int
long int or unsigned int
Short integer may require less memory than an ordinary int. Similarly long int may require
more memory but it will never be less than an ordinary int.
RANGE
Signed -32,768 +32,767
Unsigned 0 65,535
Character type is used to represent individual characters requires 1 byte of memory.
CONSTANTS:
C has 4 basic types of constants. They are
1. Integer constants
2. Real or Floating-point constants
3. Single Character constants
4. String constants
Integer constant:--
0 1 456 5467
Floating constants:--
0. 1. 0.2 345.602 2E-8 0.06E-3
5
3*10 can be represented as follows
300000. 3E5 3E+5 3.0E+5 .3E+6 30E4
-17
5.026*10 can be represented as follows
5.026E-17
Character constants:
A character constant is a single character enclosed in apostrophes.
‘A’ , ‘X’ , ‘3’ , ‘$’
String constants:
A string constant of any number of consecutive characters enclosed in double quotations.
“green”
“C programming language”
VARIABLE: A variable is an identifier that is used to represent some specified type of
information
int a, b, c;
char d;
a = 4;
b = 3;
d = ‘a’;
All variables must be declared before they can appear in executable statements. int a,b,c;
float root1, root2; Char flag;
Symbolic Constants:
A symbolic Constant is a name that substitutes for a sequence of characters. The characters
may represent a numeric constant, a character constant or a string constant.
# define name text
Where name represents a symbolic name, typically written in uppercase letters, and text
represents the sequence of characters associated with the symbolic name. Note that text does not
end with a semicolon.
OPERATORS
C supports rich set of operators. An operator is a symbol that tells the computer to perform
certain mathematical or logical manipulations.
C operators can be classified into a number of categories. They include
1) Arithmetic operators
2) Relational operators
3) Logical operators
4) Assignment operators
5) Increment and decrement operators
6) Conditional operators
7) Cast operators
8) Bitwise operators
9) Special operators
1)Arithmeticoperators : C provides all basic arithmetic operators. Operator used with only one
operand is called unary operator. For example -5. The number preceded by a minus sign changes
its sign.
Operator Purpose/Meaning
+ Addition
- Subtraction or unary minus
* Multiplication
/ Division
% Modulo division. Reminder after integer division
Integer division truncates any fractional part. The modulo division produces the remainder of an
integer division. The modulo division operator % cannot be used on floating point data. C does not
have an operator for exponentiation.
If an expression has both integer operands then the result is an integer. An arithmetic
operation involving only integer operands is called integer arithmetic.
Example 1) Suppose a and b are integer variables such as a=10 and b=3
Expression Value a+b 13
a-b 7 a*b 30
a/b 3 (decimal part truncated)
a%b 1 (remainder of division)
An arithmetic operation involving only real operands is called real arithmetic. Example 2) v1 v2
are floating points variables whose values are 12.5 and 2.0
Expression Value
v1+v2 14.5
v1-v2 10.5
v1*v2 25.0
v1/v2 6.25
When one of the operands is real and the other is integer, the expression is called a mixed
mode arithmetic expression. For example
15 / 10.0 = 1.5 where as
15 / 10 =1
2)Relational Operators: We often compare two quantities, and depending on their relation, take
certain decisions. For example we may compare the age of two persons, or price of two items and
so on. These comparisons can be done with the help of relational operators.
Operator Purpose/Meaning
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
!= Not equal to
3) Logical Operators: The logical operators are used when we want to test more than one
condition and make decisions.
Operator Purpose/Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Example 1)
if ((m1>=40)&&(m2>=40)&&(m3>=40))
printf(“pass”);
else
printf(“fail”);
Example 2)
if ((m1<40)||(m2<40)||(m3<40))
printf(“Fail”);
else
printf(“pass”);
4.ASSIGNMENT OPERATORS:
identifier = expression a=3
x=y sum=a+b
Are used to assign the result of an expression to a variable in addition to = c has a set of short
assignment operators.
v op=exp;
Where v is a variable. exp is expression op is a c binary operator. op = is known as Shorthand
assignment operator.
v op = exp;
is equivalent to v = v op(exp);
a = a+1; a+=1 a=a-1 a-=1 a=a * (n+1) a*=n+1 a = a/(n+1) a/=n+1 a
= a%b a%=b
C has two very useful operators not generally found in other languages. Theses 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.
++m; or m++;
--m; or m--;
++m; is equivalent to m=m+1 or m+=1;
--m, is equivalent to m=m-1 or m-=1;
m++ and ++m mean the same thing when they form statements independently.
They behave differently when they are used in expressions on the right hand side of an
assignment statement.
m = 5;
y = ++m;
The value of y and m would be 6.
uppose if we rewrite the above statements as m = 5;
y = m ++;
The value of y would be 5 and m would be 6. A prefix operator first adds 1 to the operand and
then the result is assigned to the variable on left. On the other hand, a postfix operator first
assigns the value to the variable on the left and then increments the operand.
The conditional expression is evaluated first. If the result is non zero exp1 is evaluated
and returned as the value of conditional expression. Otherwise expression2 is evaluated and
its value is returned.
For example:
if (x<0) Flag=0;
else
Flag=1; Can be written as
Flag= (x<0) ? 0: 1;
Ex 2) Finding largest from two integers: int n1,n2,big; scanf(“%d%d”,&n1,&n2); big=(n1>n2) ?
n1 : n2;
Ex 3 ) evaluate
Y=1.5x+3 for x<=2
Y=2x+5 for x>2
Y=(x>2) ? (2*x + 5) : (1.5*x + 3);
Ex 4)
4x+100 for x<40
Salary y = 300 for x=40
4.5x+150 for x>40
7. Cast operator (Type Conversions)
The value of an expression can be converted to a different data type if desired. To do so
the expression must be preceded by the name of the desired data type enclosed in parentheses.
(data type)Expression
int a=10;
int b=3;
a/b becomes 3
(float)a/(float)b becomes 3.33 int 10+15.5 becomes 25
2. a = (int)21.3/(int)4.5
= 21/4 5
One’s complement:
/* program complementing a number */ main()
#include <stdio.h> {
showbits(n) int a=25,b;
int n; clrscr();
{
int a,m,i,andmask; printf("decimal number %d is same as ",a);
for (i=15;i>=0;i--) showbits(a);
{ b=~a;
m=1<<i; andmask=m&n; a=(andmask==0 printf("ones complement ");
? 0 : 1); printf("%d",a); showbits(b);
} getch();
printf("\n"); }
}
Right shift:
/* program for right shifting a decimal main()
integer number */ {
#include <stdio.h> int i=25,j,k;
showbits(n) clrscr();
int n; printf("decimal number %d is same as ",i);
{ showbits(i);
int a,m,i,andmask; for(j=0;j<=5;j++)
for (i=15;i>=0;i--) {
{ k=i>>j;
m=1<<i; andmask=m&n; a=(andmask==0 ? 0 printf("%d right shift %d gives ",i,j);
: 1); printf("%d",a); showbits(k);
} }
printf("\n"); getch();
}
}
int n, k; 64 >>1 …. 32 n=5; 64 >> 2
…. 16 k=n>>1 64 >> 3 …. 8
27 >> 1 … 13
49 >> 1 … 24
Left shift: K = i << j
Value i is shifted left j No of positions
64 << 1 128
64 << 2 256
/* program for left shifting a decimal integer number */
#include <stdio.h> main()
showbits(n) {
int n; int i=25,j,k;
{ printf("decimal number %d is same as ",i);
int a,m,i,andmask; showbits(i);
for (i=15;i>=0;i--) for(j=0;j<=5;j++)
{ {
m=1<<i; andmask=m&n; a=(andmask==0 ? k=i<<j;
0 : 1); printf("%d",a); printf("%d left shift %d gives ",i,j);
} showbits(k);
printf("\n"); }
} /* end of showbits() function */ getch();
}
Bitwise And: This operator is different from logical And (&&). & operates on two operands.
While operating upon these two operands they are compared on a bit by bit basis. Hence both the
operands must be of the same type. The second operand is often called AND MASK. The
& operator operates on a pair of bits to yield a resultant bit.
n3= n1 & n2 Ex: 3 ------- 0011 n1
5 ------- 0101 n2
0001
/* program to explain bitwise ANDing two integer numbers */
#include <stdio.h> main()
showbits(n) {
int n; int a,b,c; a=25; b=15; clrscr();
{ printf("decimal number %d is same as ",a);
int a,m,i,andmask; showbits(a);
for (i=15;i>=0;i--) printf("decimal number %d is same as ",b);
{ showbits(b);
m=1<<i; andmask=m&n; a=(andmask==0 ? c=a&b;
0 : 1); printf("%d",a); printf("%d and %d is ",a,b);
} showbits(c);
printf("\n"); getch();
} /* end of showbits() function */ }
Bitwise Or:- 3 ------- 0011 3|5
5 ------- 0101
0111
Bitwise xor:- 3 ------ 0011 3^5
5 ------ 0101
0110
9. Special Operators: -
C supports some special operators of interest such as comma operator, size of operator,
pointer operators (& and *) and number selection operators ( . and )
The comma permits two different expressions to appear in situations where only one
expression would ordinarily be used
a,b,c
c=(a=10, b=20, a+b);
printf(“%d”,c);
first 10 is assigned to a.
20 is assigned to b.
10+20 is assigned to c.
sizeof () operator returns the number of bytes the operand occupies in memory. The operand
may be a variable, a constant or a data type qualifier
Sizeof (int); ---------------- 2 bytes
Sizeof (float); ------------- 4 bytes Sizeof (sum); -------------- 2 bytes Sizeof (2345); ------------- 4
bytes Sizeof (‘A’); --------------- 1 bytes
READING A CHARACTER:
getchar( ): Reading a single character can be done by using the function getchar( );
varname = getchar( );
Ex: Where varname is a valid C identifier. When this statement is encountered, the computer
waits until a key is pressed and then assigns this character as a value to getchar function.
Since getchar() is used on the right hand side of an assignment statement, the character is assign to
the variable.
char ch; ch=getchar( ); putchar(ch); putchar(‘\n’);
putchar (var-name)
is used to write character on the terminal. Where var-name is a character var or char
constant.
putchar (‘\n’); would cause the cursor on the screen to move to the beginning of the next line. char c= ‘a’;
putchar(c);
scanf( ) Function :
Input data can be entered into the computer from a standard input device by means of the
C library function scanf(). This function can be used to enter any combination of
numerical values, single characters and strings.
scanf (control_string, &arg1, &arg2,……&argn);
Where control string refers to a string containing certain required formatting information and
arg1, arg2,…. argn are arguments that represent the individual input data items.
%c single character
%d decimal integer
%e floating point value
%f floating point value
%s string
%x Hexa decimal
%o Octal integer
%u unsigned decimal integer
Each variable name must be preceded by an ampersand (&). The arguments are actually
pointers, which indicate where the data items are stored in the computer memory.
int a;
float b; char name[20]
char c; scanf(“%s”, name);
scanf(“%d%f%c”,&a,&b,&c);
printf( ) Function
Output data can be written from the computer on to a standard output device using the
library printf(). This function can be used to output any combination of numerical values,
single characters and strings.
printf (control-string, arg1, arg2,……..);
Where control string refers to a string that contains formatting information, and arg1, arg2 are
arguments that represent individual output data items.
%c single character
%d decimal integer
%e floating point value
%f floating point value
%s string
%x Hexa decimal
%o Octal
int x;
x=20; output printf (“%d”,x);
20 printf (“x=%d”,x);
x=20
printf(“value of x=%d”,x) value of x=20
The basic evaluation procedure includes two passes from left to right through the expression.
During the first pass the high priority operators (if any) are applied as they are encountered.
During the second pass the low priority operators (if any) are applied as they are encountered.
float a,b,c,x,y,z;
a=9; b=12; c=3;
x = a-b / 3+c * 2 – 1;
y = a-b / (3+c) * (2-1); z = a-(b/ (3+c) * 2) –1; printf (“x = %f\n”,x); printf(“y = %f\n”,y);
printf(“z = %f\n”,z);
…………
Whenever parenthesis are used the expressions within parenthesis assume highest priority. If two
or more sets of parenthesis appear one after the another as 9-12/(3+3)*(2-1). The expression
contained in the left most set is evaluated first and the right most in the last.
9-12/(3+3)*(2-1)
9-12/6*(2-1)
9-12/6*1
9-2*1
9-2
7.
Parenthesis may be nested, and in such cases, evaluation of the expression will proceed outward
from the innermost set of parenthesis.
9-(12/(3+3)*2)-1 9-((12/3)+3*2)-1
9-(12/6*2)-1 9-(4+3*2)-1
9-(2*2)-1 9-(4+6)-1
9-4-1 9-10-1
4. -2.
PRECEDENCE AND ASSOCIATIVITY
Each operator in C has precedence associated with it. This precedence is used to determine how
an expression involving more than one operator is evaluated. The operators at the higher level of
precedence are evaluated first. The operators of same precedence are evaluated either from left to
right or from right to left depending on the level. This is known as associativity property of an
operator.
The next step is to determine whether x is equal to 25 and y is less than 10. Assume x as 20 and y
as 5 then
x = = 25 is false y<10 is true.
The operator < has higher priority compared to = =, y<10 is tested first and then x = =25 is tested.
Similarly we get if (false && true) because one of the condition is false the compare condition is
false.
SIMPLE PROGRAMS
/* -------------------------Temperature conversion Centigrade to Fahrenheat C=(F-32)/1.8 */
#include <stdio.h>
#include <conio.h>
void main()
{
float c,f;
clrscr();
printf("enter temperature in centigrade ");
scanf("%f",&c);
f = c * 1.8 +32.0;
printf("Fahrenheat temperature =%f\n",f);
getch();
}
/* --------------Program to find Area of a Triangle when base and height are given*/
#include <stdio.h>
#include <conio.h>
#include <math.h>
void main()
{
float b,h,area;
clrscr();
printf("enter the base and height of a triangle ");
scanf("%f%f",&b,&h);
area=b*h/2;
printf("Area of a Triangle = %f\n",area);
getch();
}
clrscr();
printf("enter principle amount "); scanf("%f",&principle); printf("enter rate of interest ");
scanf("%d",&rate);
printf("enter number of years ");
scanf("%d",&n);