B Basic Combined Programming Language (BCPL) - "C"
B Basic Combined Programming Language (BCPL) - "C"
# include stdio.h
# include math.h Include Block
# include string.h
main ()
{ Main Block
}
Sample program: Printing a Message
main() Function name
{ start of the program
…………
………… Program statements
…………
} end of the program
main()
{
/* ……. Printing begins……..*/
printf(“I see, I remember”);
printf(“I see,\n I remember !”);
/* ……. Printing ends……..*/
}
Output: I see, I remember
I see
I remember !
Constants, Variables and Data Types
• The characters in C are grouped into the
following categories:
• Letters, Digits, Special characters and White
spaces.
Alphabets A,B,…….Y,Z
A,b,…….y,z
Digits 0,1,2,3,4,5,6,7,8,9
Array
Integer Constant
Pointer
Real Constant
Structure
Character Constant
Union
Enum etc.
Rules for constructing Integer Constraints
• An integer constant must have at least one digit.
• It must not have a decimal point.
• It could be either positive or negative.
• If no sign precedes an integer constant it is
assumed to be positive.
• No commas or blanks are allowed within an
integer constant.
• The allowable range for integer constant is
-32768 to +32767.
Rules for constructing Real Constraints
• A real constant must have at least one digit.
• It must have a decimal point.
• It could be either positive or negative.
• No commas or blanks are allowed within a real
constant.
• Default sign is positive.
Ex:
426.0
-32.76
-48.5792
Rules for constructing Character Constraints
• The mantissa part and the exponential part should
be separated by a letter e.
• The mantissa part may have a positive or negative
sign.
• Default sign of mantissa part is positive.
• The exponent must have at least one digit which
must be a positive or negative integer. Default sign
in positive.
• Range of real constants expresses in exponential
form is -3.4e38 to 3.4e38
Ex: +3.2e-5 4.1e8
C Keywords
printf(“%6d”, 9876) 9 8 7 6
printf(“%-6d”, 9876) 9 8 7 6
printf(“%06d”, 9876) 0 0 9 8 7 6
Output of Real Numbers:
y=98.7654
Format Output
printf(“%7.4f”, y) 9 8 . 7 6 5 4
printf(“%7.2f”, y) 9 8 . 7 7
printf(“%-7.2f”, y) 9 8 . 7 7
printf(“%f”, y) 9 8 . 7 6 5 4
Printf(“%10.2e”,y) 9 . 8 8 e + 0 1
Printf(“%-10.2e”,y) 9 . 8 8 e + 0 1
Printing of a Single Character:
for character print %c is used.
for string print %s is used.
main()
{
char x = ‘A’;
char name[20] = “ANIL KUMAR GUPTA”;
printf(“output of characters”);
printf(“%c\n%3c\n%5c\n”, x,x,x);
printf(“output of strings”);
printf(“%s\n”, name);
printf(“%20s\n”, name);
printf(“%20.10s\n”, name);
printf(“%.5s\n”, name);
printf(“%-20.10s\n”, name);
}
Operators and Expressions
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. Bitwise operators
8. Special operators
Arithmetic operators
Operator Meaning
Logical operators
&& Meaning logical AND
|| Meaning logical OR
! Meaning logical NOT
= += -=
*= /= %=
assignment binary 2 right-to-left
&= ^= |=
<<= >>=
Preced
Tokens Operator Class Associates
ence
names,
literals simple tokens primary n/a
indirection
* unary right-to-left
(dereference)
Casting Operator
Convert from one data type to another data type.
Ex: main()
{
int i=10;
float g=50.56;
i=g; /* i=(int)g here float value convert to integer*/
printf(“%d”, i);
}
Output: 50
(int), (float), (char), (double)
The Decision Control structure
The if statement :
If(this condition is true)
execute this statement;
Ex:
main()
{
int num;
printf(“ enter a number less than 10”);
scanf(“%d”, &num);
if(num <=10 )
printf(“ less than 10”); (single statement with in
if)
}
Multiple statements within if
/* Calculation of bonus*/
main()
{
int bonus, cy, yoj, yr_of_ser;
printf(“Enter current year and year of joining”);
scanf(“%d%d”, &cy, %yoj);
yr_of_ser = cy-yoj;
If(yr_of_ser > 3)
{
bonus = 2500; Multiple statements
printf(“ bonus = RS. %d”, bonus); within if
}
}
If –else statement
/* calculation of gross salary*/
main()
{
float bs, gs, da, hra;
printf(“Enter basic salary”);
scanf(“%f”, &bs);
if(bs<1500)
{
hra = bs * 10/100;
da = bs * 90/100;
}
else
{
hra = 500;
da = bs*98/100;
}
gs = bs+hra+da;
printf(“gross salary=Rs.%f”, gs);
}
/*Nested if elses */
main()
{
int i;
printf(“enter either 1 or 2”);
scanf(“%d”, &i);
if(i==1)
printf(“enter 1”);
else
{
if(i==2)
printf(“enter 2”);
else
printf(“HI”);
}
}
Forms of if
a. if (condition)
do this;
b. if(condition)
{
do this;
and this;
}
c. if(condition)
do this;
else
do this;
d. if(condition)
{
do this;
and this;
}
else
{
do this;
and this;
}
e.
if(condition)
do this;
else
{
if(condition)
do this;
else
{
do this;
and this;
}
}
Write a program to calculate the division obtained by the student.
main()
{
int m1,m2,m3,m4,m5,per;
printf(“enter marks in five subjects”);
scanf(“%d%d%d%d%d”, &m1,&m2,&m3,&m4,&m5);
per=(m1+m2+m3+m4+m5)/5;
if(per > = 60)
printf(“ first division”);
else
{
if(per >=50)
printf(“ second division”);
else
{
if(per >=40)
printf(“ third division”);
else
printf(“Fail”);
}
}
}
Using Logical operators
main()
{
int m1,m2,m3,m4,m5,per;
printf(“enter marks in five subjects”);
scanf(“%d%d%d%d%d”, &m1,&m2,&m3,&m4,&m5);
per=(m1+m2+m3+m4+m5)/5;
if(per > = 60)
printf(“ first division”);
if((per > = 50) && (per < 60) )
printf(“ second division”);
if((per > = 40) && (per < 50) )
printf(“ third division”);
if(per < 40)
printf(“Fail”);
}
The Loop Control Structure
1. While Loop
2. Do-While Loop
3. For Loop
4. Nested for Loop
}
}
a. main()
{
int i;
for(i=1; i<=10;)
{
printf(“%d”, i);
i=i+1;
}
}
• Here, the incrementation is done within the body of the
for loop and not in the for statement.
b. main()
{
int i = 1;
for(; i<=10; i=i+1)
{
printf(“%d”, i);
}
}
• Here, the initialisation is done in the declaration
statement itself, but still the semicolon before the
condition necessary.
c. main()
{
int i = 1;
for(; i<=10; )
{
printf(“%d”, i);
i=i+1;
}
}
• Here, neither the initialisation, nor the incrementation is
done in the for statement, but still the semicolon before
the condition necessary.
d. main()
{
int i;
for(i=0; i++<10; )
{
printf(“%d”, i);
}
}
• Here, the comparison as well as the incrementation
is done through the same statement, i++ < 10.
Nested for Loop
Program Example:
#include<stdio.h> output:
main()R=1 c=1 sum =2
{ R=1 c=2 sum =3
int r,c,sum; R=2 c=1 sum =3
for (r =1; r<=3; r++) R=2 c=1 sum =4
{ R=3 c=1 sum =4
for (c=1; c<=2; c++) R=3 c=2 sum =5
{
sum = r + c;
printf(“r=%d c=%d sum=%d”, r, c, sum);
}
}
}
• Multiple initialisations in the for loop
case ('b') :
case ('B') :
printf ("Pretty good.\n") ;
case ('c') :
case ('C') :
printf ("Better get to work.\n") ;
case ('d') :
case ('D') :
printf ("You are in trouble.\n") ;
default :
printf ("You are failing!!\n") ;
} /* End of switch-case structure */
} /* End of main program
/* The following results are produced when the user
enters an "A" as input to the program prompt. */
Good Job!
Pretty good.
Better get to work.
You are in trouble.
You are failing!
• The problems with the previous program can be
corrected by use of the break statement.
• It can be used in either a repetition structure or a
selection structure to break out of (that is, to exit
from) the structure.
• The syntax is:
break ;
• The following program is the previous one with the
addition of the break statements.
#include <stdio.h>
main ( )
{
int i=2;
switch(i)
{
case 1:
printf(“I am in case 1”);
break;
case 2:
printf(“I am in case 2”);
break;
case 3:
printf(“I am in case 3”);
break;
default:
printf(“I am in default”);
}
}
Output : I am in case 2
Functions
What is a Function?
•Function is a self contained block of statements that
perform a coherent task of some kind.
•Every C program can be a thought of the collection of
functions.
• main( ) is also a function.
• Any c program contains at least one function.
• If a program contains only one function, it must be
main().
• There is no limit on the number of functions that might be
present in a c program.
• Each function in a program is called in the sequence
specified by the function call in main().
Types of Functions
• Library functions.
• These are the in -built functions of ‘C’ library.
• These are already defined in header files.
e.g. printf( ); is a function which is used to print at
output. It is defined in ‘stdio.h’ file .
•User defined functions.
• Programmer can create their own function in C to
perform specific task.
User defined functions
#include<stdio.h>
main()
{
message();
printf(“cry, and you stop the monotony”);
}
message()
{
printf(“smile, and the world smiles with you”);
}
Output: smile, and the world smiles with you
cry, and you stop the monotony
Declaration of many functions
main( )
{ engg()
printf(“I am in main”); {
poly( ); printf( “I am in engineering ”);
engg( ); }
agri( ); agri()
} {
poly( ) printf( “I am inagri ”);
{ }
printf(“I am in polytechnic”);
}
main()
{
printf(“I am in main”);
italy();
printf(“ iam finally back in main”); output:
} I am In main
Italy() I am in italy
{ I am in brazil
printf(“I am in italy”); I am in argentina
brazil(); I am back in italy
printf(“I am back in italy”); iam finally back in main
}
brazil()
{
printf(“I am in brazil”);
argentina();
}
argentina()
{
printf(“I am in argentina ”);
}
Summarization
• C Program is a collection of one or more functions.
• A function gets called when its name is followed by a
semicolon.
e.g. main( )
{
fun( );
}
fun( )
{
Statement1; statement2; statement3;
}
• A function is defined when function name is
followed by a pair of braces in which one or more
statements present.
fun( )
{
statement1;
statement2;
statement3;
}
• Any function can be called by any other function.
main( )
{
printf(“II am in main”);
fun( );
}
fun( )
{
Printf(“I am in fun”);
main( );
}
This will run in infinity.
A function can be called by number of times.
e.g.
main( )
{
printf(“I am in main”);
fun( );
fun( );
fun( );
}
fun( )
{
printf(“I am in fun”);
}
A function can call itself, it is called as a ‘‘recursion”
e.g.
main ( )
{
printf(“I am in main”);
main( );
}
• A function can be called from another function but
can not be defined in another function. It should be
defined outside of the main.
• The order in which the functions are defined in a program and the
order in which they get called need not necessarily be same.
main()
{
message1();
message2();
}
message2()
{
printf(“smile, and the world smiles with you”);
}
message1();
{
printf(“cry, and you stop the monotony”);
}
Why use functions?
• Writing functions avoids rewriting of the same code
again and again in the program.
• Using a function it becomes easier to write program
to keep track of what they are doing.
Passing values between functions
The values that we pass to the function called as function arguments.
e.g.
main( )
{
int i=10, j=12, k=20;
calsum(i,j,k);
}
6485 3276
Ex: main()
{
int i=3; output:
int *j; address of i = 6485
j=&i; address of i = 6485
printf(“address of i=%u”, &i); address of j = 3276
printf(“address of i=%u”, j); value of j = 6485
printf(“address of j=%u”, &j); value of i = 3
printf(“value of j= %u”, j); value of i = 3
printf(“value of i= %d”, i); value of i = 3
printf(“value of i= %d”, *(&i));
printf(“value of i= %d”, *j);
}
Back to Function calls
• Arguments can generally be passed to function in
one of the two ways:
1. sending the values of the arguments
2. sending the addresses of the arguments
• In the first method the value of each of actual
arguments in the calling function is copied into
corresponding formal arguments of the called
function.
• With this method the changes made to the formal
arguments in the called function have no effect on
the values of actual arguments in the calling
function
/* interchange the values */
main()
{
int x=50, y=70;
interchange(x,y);
printf(“x=%d y=%d”,x,y);
}
interchange(x1,y1) output:
int x1,y1; x1 = 70 y1= 50
{ x = 50 y =70
int z1;
z1=x1;
x1=y1;
y1=z1;
printf(“x1=%d y1=%d”,x1,y1);
}
• In second method (call by reference) the address of
actual arguments in the calling function are copied
into formal arguments of the called function.
• This means that using these addresses we would
have an access to the actual arguments and here we
would be able to manipulate them.
main()
{
int x=50, y=70;
interchange(&x,&y);
printf(“x=%d y=%d”,x,y);
}
output:
interchange(x1,y1) *x=70 *y=50
int *x1,*y1; x=70 y=50
{
int z1;
z1=*x1;
*x1=*y1;
*y1=z1;
printf(“*x=%d *y=%d”,x1,y1);
}
Recursion
• A function is called ‘recursive’ if a statement with in the body of a
function calls the same function.
• Sometimes called circular definition, recursion is thus the process of
defining something in terms of itself.
• int fact(int n) { output :
int x,y; Enter the integer whose factorial value you want
if(n==0) 3
return 1;
x=n-1; The factorial value is 6
y=fact(x);
return n*y; }
void main() {
int x;
printf(“\nEnter the integer whose factorial value you want “);
scanf(“%d”,&x);
printf(“\nThe factorial value is:-%d”,fact(x)); }