Programming in C: Unit I &ii
Programming in C: Unit I &ii
PROGRAMMING IN C
UNIT I &II
INTRODUCTION
Computer Basically it is a fast calculating machine which is now a days used for
variety of uses ranging from house hold works to space technology. The credit of invention of
this machine goes to the English Mathematician Charles Babbage.
Types of Computers:
Based on nature, computers are classified into Analog computers and Digital
computers. The former one deals with measuring physical quantities ( concerned with
continuous variables ) which are of late rarely used. The digital computer operates by
counting and it deals with the discrete variables. There is a combined form called Hybrid
computer, which has both features. Based on application computers are classified as special
purpose computers and general computers. As the name tells special computers are designed
to perform certain specific tasks where as the other category is designed to cater the needs of
variety of users.
Languages:. These programs facilitate the users to make their own programs. User’s
programs are converted to machine oriented and the computer does the rest of works.
Application Programs :
Computer Languages:
Machine language depends on the hard ware and comprises of 0 and 1 .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 over come 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
2
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 a stretch
where as Interpreter translates the program by reading it line by line. C and BASIC are an
Interpreter where as FORTRAN is a
PROGRAMMING METHODOLOGY
Steps
Example:
Step2: sum=x + y
Algorithm
3
C Fundamentals
A brief history of C C evolved from a language called B, written by Ken Thompson at Bell
Labs in 1970. 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 C has now become a widely used professional language for various reasons.
Easy to learn
Structured language
C tokens:
C tokens are the basic buildings blocks in C language which are constructed together
to write a C program.
Each and every smallest individual units in a C program are known as C tokens.
4
Identifiers in C language:
Keywords in C language:
CONSTANTS
C Constants are also like normal variables. But, only difference is, their values can
not be modified by the program once they are defined.
Constants refer to fixed values. They are also called as literals
Constants may be belonging to any of the data type.
Syntax:
Types of C constant:
5
1. Integer constants
2. Real or Floating point constants
3. Octal & Hexadecimal constants
4. Character constants
5. String constants
6. Backslash character constants
1. Integer Constants in C:
2. Real constants in C:
Backslash_character Meaning
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\” Double quote
6
\’ Single quote
\\ Backslash
\v Vertical tab
\a Alert or bell
\? Question mark
\N Octal constant (N is an octal constant)
\XN Hexadecimal constant (N – hex.dcml cnst)
1. By “const” keyword
2. By “#define” preprocessor directive
Please note that when you try to change constant values after defining in C program, it
will through error.
VARIABLE
C variable is a named location in a memory where a program can manipulate the data.
This location is used to hold the value of the variable.
The value of the C variable may get change in the program.
C variable might be belonging to any of the data type like int, float, char etc.
The symbols which are used to perform logical and mathematical operations in a C
program are called C operators.
These C operators join individual constants and variables to form expressions.
Operators, functions, constants and variables are combined together to form
expressions.
Consider the expression A + B * 5. where, +, * are operators, A, B are variables, 5 is
constant and A + B * 5 is an expression.
Types of C operators:
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators
1.Arithmetic Operators in C:
In this example program, two values “40″ and “20″ are used to perform arithmetic
operations such as addition, subtraction, multiplication, division, modulus and output
is displayed for each operation.
#include <stdio.h>
int main()
{
int a=40,b=20, add,sub,mul,div,mod;
add = a+b;
sub = a-b;
mul = a*b;
div = a/b;
mod = a%b;
printf(“Addition of a, b is : %d\n”, add);
printf(“Subtraction of a, b is : %d\n”, sub);
printf(“Multiplication of a, b is : %d\n”, mul);
printf(“Division of a, b is : %d\n”, div);
printf(“Modulus of a, b is : %d\n”, mod);
}
Output:
Addition of a, b is : 60
Subtraction of a, b is : 20
Multiplication of a, b is : 800
9
Division of a, b is : 2
Modulus of a, b is : 0
2.Assignment operators in C:
In C programs, values for the variables are assigned using assignment operators.
For example, if the value “10″ is to be assigned for the variable “sum”, it can be
assigned as “sum = 10;”
Other assignment operators in C language are given below.
In this program, values from 0 – 9 are summed up and total “45″ is displayed as
output.
Assignment operators such as “=” and “+=” are used in this program to assign the
values and to sum up the values.
# include <stdio.h>
int main()
{
int Total=0,i;
for(i=0;i<10;i++)
{
Total+=i; // This is same as Total = Toatal+i
}
printf(“Total = %d”, Total);
}
10
Output:
Total = 45
3.Relational operators in C:
Relational operators are used to find the relation between two variables. i.e. to
compare the values of two variables in a C program.
In this program, relational operator (==) is used to compare 2 values whether they are
equal are not.
If both values are equal, output is displayed as ” values are equal”. Else, output is
displayed as “values are not equal”.
Note : double equal sign (==) should be used to compare 2 values. We should not
single equal sign (=).
#include <stdio.h>
int main()
{
int m=40,n=20;
if (m == n)
{
printf(“m and n are equal”);
}
else
{
printf(“m and n are not equal”);
}
}
Output:
4.Logical operators in C:
11
These operators are used to perform logical operations on the given expressions.
There are 3 logical operators in C language. They are, logical AND (&&), logical OR
(||) and logical NOT (!).
#include <stdio.h>
int main()
{
int m=40,n=20;
int o=20,p=30;
if (m>n && m !=0)
{
printf(“&& Operator : Both conditions are true\n”);
}
if (o>p || p!=20)
{
printf(“|| Operator : Only one condition is true\n”);
}
if (!(m>n && m !=0))
{
printf(“! Operator : Both conditions are true\n”);
}
else
{
printf(“! Operator : Both conditions are true. ” \
“But, status is inverted as false\n”);
}
}
Output:
These operators are used to perform bit operations. Decimal values are converted into
binary values which are the sequence of bits and bit wise operators work on these bits.
Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise
OR), ^ (XOR), << (left shift) and >> (right shift).
Consider x=40 and y=80. Binary form of these values are given below.
x = 00101000
y= 01010000
Increment operators are used to increase the value of the variable by one and
decrement operators are used to decrease the value of the variable by one in C
programs.
Syntax:
…Example:
IncrementOperator: ++i; i++;
Decrement operator : - – i ; i – - ;
…
13
In this program, value of “i” is incremented one by one from 1 up to 9 using “i++”
operator and output is displayed as “1 2 3 4 5 6 7 8 9”.
#include <stdio.h>
int main()
{
int i=1;
while(i<10)
{
printf("%d ",i);
i++;
}
}
Output:
123456789
In this program, value of “I” is decremented one by one from 20 up to 11 using “i–”
operator and output is displayed as “20 19 18 17 16 15 14 13 12 11”.
#include <stdio.h>
int main()
{
int i=20;
while(i>10)
{
printf("%d ",i);
i--;
}
}
Output:
20 19 18 17 16 15 14 13 12 11
Below table will explain the difference between pre/post increment and decrement
operators in C.
14
#include <stdio.h>
int main()
{
int i=0;
while(++i < 5 )
{
printf("%d ",i);
}
return 0;
}
Output:
1234
#include <stdio.h>
int main()
{
int i=0;
while(i++ < 5 )
{
printf("%d ",i);
}
return 0;
}
15
Output:
12345
#include <stdio.h>
int main()
{
int i=10;
while(--i > 5 )
{
printf("%d ",i);
}
return 0;
}
Output:
9876
#include <stdio.h>
int main()
{
int i=10;
while(i-- > 5 )
{
printf("%d ",i);
}
return 0;
}
Output:
16
98765
7.Special Operators in C:
In this program, “&” symbol is used to get the address of the variable and “*” symbol
is used to get the value of the variable that the pointer is pointing to. Please refer C –
pointer topic to know more about pointers.
#include <stdio.h>
int main()
{
int *ptr, q;
q = 50;
/* address of q is assigned to ptr */
ptr = &q;
/* display q’s value using ptr variable */
printf(“%d”, *ptr);
return 0;
}
Output:
50
sizeof() operator is used to find the memory space allocated for each C data types.
#include <stdio.h>
#include <limits.h>
int main()
{
int a;
char b;
float c;
double d;
printf(“Storage size for int data type:%d \n”,sizeof(a));
printf(“Storage size for char data type:%d \n”,sizeof(b));
printf(“Storage size for float data type:%d \n”,sizeof(c));
printf(“Storage size for double data type:%d\n”,sizeof(d));
return 0;
}
Output:
Conditional operators return one value if condition is true and returns another value is
condition is false.
This operator is also called as ternary operator.
#include <stdio.h>
int main()
{
int x=1, y ;
y = ( x ==1 ? 2 : 0 ) ;
printf(“x value is %d\n”, x);
printf(“y value is %d”, y);
}
Output:
18
x value is 1
y value is 2
Library functions
Library functions in C language are inbuilt functions which are grouped together and
placed in a common place called library.
Each library function in C performs specific operation.
We can make use of these library functions to get the pre-defined output instead of
writing our own code to get those outputs.
These library functions are created by the persons who designed and created C
compilers.
All C standard library functions are declared in many header files which are saved as
file_name.h.
Actually, function declaration, definition for macros are given in all header files.
We are including these header files in our C program using “#include<file_name.h>”
command to make use of the functions those are declared in the header files.
When we include header files in our C program using “#include<filename.h>”
command, all C code of the header files are included in C program. Then, this C
program is compiled by compiler and executed.
UNIT II
scanf ()
The format string must be a text enclosed in double quotes. It contains the
information for interpreting the entire data for connecting it into internal representation in
memory.
Printf
The usually used output statement is printf (). It is one of the library functions.
Escape sequence:
\n New line
\t Tab
\b Back space
\a Bell
\o Null character
\\ To print slash
Example
#include< stdio.h>
#include< conio.h>
void main()
int i;
printf("Enter a value");
scanf("%d",&i);
getch();
getchar():
getchar function will accept a character from the console or from a file, displays
immediately while typing and we need to press Enter key for proceeding.
Syntax of getchar() is
int getchar(void);
It returns the unsigned char that they read.If end-of-file or an error is encountered
getchar() functions return EOF.
For example:
char a;
a= getchar();
The function "getchar()" reads a single character from the standard input device,
the keyboard being assumed because that is the standard input device, and assigns it to the
variable "a".
22
putchar():
Example:
void main( )
int c;
printf("Enter a character");
c=getchar();
putchar(c);
getch();
gets():
It is used to scan a line of text from a standard input device. The gets() function
will be terminated by a newline character. The newline character won't be included as part of
the string. The string may include white space characters.
gets() function is declared in the header file stdio.h. It takes a single argument. The
argument must be a data item representing a string. On successful completion, gets() shall
return a pointer to string s.
puts():
Example:
23
#include< stdio.h>
#include< conio.h>
void main()
char str[100];
printf("Enter a string");
gets( str );
puts( str );
getch();
In decision control statements (C if else and nested if), group of statements are
executed when condition is true. If condition is false, then else part statements are
executed.
There are 3 types of decision making control statements in C language. They are,
1. if statements
2. if else statements
3. nested if statements
Syntax for each C decision control statements are given in below table with
description.
In “if” control statement, respective block of code is executed when condition is true.
int main()
{
int m=40,n=40;
if (m == n)
{
printf("m and n are equal");
}
}
Output:
In C if else control statement, group of statements are executed when condition is true. If
condition is false, then else part statements are executed.
#include <stdio.h>
int main()
{
int m=40,n=20;
if (m == n)
{
printf("m and n are equal");
}
else
{
printf("m and n are not equal");
}
Output:
25
#include <stdio.h>
int main()
{
int m=40,n=20;
if (m>n) {
printf("m is greater than n");
}
else if(m<n) {
printf("m is less than n");
}
else {
printf("m is equal to n");
}
}
Output:
m is greater than n
Loop control statements in C are used to perform looping operations until the given
condition is true. Control comes out of the loop statements once condition becomes false.
1. for
2. while
3. do-while
Syntax for each C loop control statements are given in below table with description.
k=3 )
exp2 – condition
checking
( Example: i>5, j<3,
k=3 )
exp3 –
increment/decrement
( Example: ++i, j–, ++k
)
2 while while (condition) where,
{ statements; } condition might be a>5,
i<10
3 do while do { statements; } where,
while (condition); condition might be a>5,
i<10
In for loop control statement, loop is executed until condition becomes false.
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
printf("%d ",i);
}
Output:
0123456789
In while loop control statement, loop is executed until condition becomes false.
#include <stdio.h>
int main()
{
int i=3;
while(i<10)
27
{
printf("%d\n",i);
i++;
}
Output:
3456789
#include <stdio.h>
int main()
{
int i=1;
do
{
printf("Value of i is %d\n",i);
i++;
}while(i<=4 && i>=2);
Output:
Value of i is 1
Value of i is 2
Value of i is 3
Value of i is 4
The statements which are used to execute only specific block of statements in a series of
blocks are called case control statements.
1. switch
2. break
3. continue
4. goto
Switch case statements are used to execute only specific case statements based on the
switch expression.
Below is the syntax for switch case statement.
switch (expression)
{
case label1: statements;
break;
case label2: statements;
break;
default: statements;
break;
}
#include <stdio.h>
int main ()
{
int value = 3;
switch(value)
{
case 1:
printf(“Value is 1 \n” );
break;
case 2:
printf(“Value is 2 \n” );
break;
case 3:
printf(“Value is 3 \n” );
break;
case 4:
printf(“Value is 4 \n” );
break;
default :
printf(“Value is other than 1,2,3,4 \n” );
29
}
return 0;
}
Output:
Value is 3
2. break statement in C:
Break statement is used to terminate the while loops, switch case loops and for loops
from the subsequent execution.
Syntax: break;
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
printf(“\nComing out of for loop when i = 5″);
break;
}
printf(“%d “,i);
}
}
Output:
01234
Coming out of for loop when i = 5
3. Continue statement in C:
Continue statement is used to continue the next iteration of for loop, while loop and
do-while loops. So, the remaining statements are skipped within the loop for that
particular iteration.
Syntax : continue;
#include <stdio.h>
int main()
{
30
int i;
for(i=0;i<10;i++)
{
if(i==5 || i==6)
{
printf(“\nSkipping %d from display using ” \
“continue statement \n”,i);
continue;
}
printf(“%d “,i);
}
}
Output:
01234
Skipping 5 from display using continue statement
Skipping 6 from display using continue statement
789
4. goto statement in C:
goto statements is used to transfer the normal flow of a program to the specified label
in the program.
Below is the syntax for goto statement in C.
{
…….
go to label;
…….
…….
LABEL:
statements;
}
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
printf(“\nWe are using goto statement when i = 5″);
goto HAI;
}
printf(“%d “,i);
31
}
HAI : printf(“\nNow, we are inside label name \”hai\” \n”);
}
Output:
01234
We are using goto statement when i = 5
Now, we are inside label name “hai”
Flowchart of For Loop
We will get better idea after looking at above for loop flowchart.
Note :
For Single Line of Code – Opening and Closing braces are not needed.
while(1) is used for Infinite Loop
Initialization , Incrementation and Condition steps are on different Line.
While Loop is also Entry Controlled Loop.[i.e conditions are checked if found true then
and then only code is executed ]
Do-While Loop Syntax :
initialization;
do
{
--------------
--------------
--------------
--------------
33
incrementation;
}while(condition);
Note :
It is Exit Controlled Loop.
Initialization , Incrementation and Condition steps are on different Line.
It is also called Bottom Tested [i.e Condition is tested at bottom and Body has to execute
at least once ]