C PROGRAMMING
LANGUAGE
Pranoti R. Doke
ME(Entc), BE(Entc)
Chapter
01
Introduction
What is automation?
Automation is basically the delegation of human
control function to technical equipment.
It is the use of control systems such as computers,
PLCs, Microcontrollers to control machinery and
processes to reduce the need for human sensory and
mental requirements as well.
Now what is mean by Computer-
▪ A computer is an electronic device that manipulates
information, or data. It has the ability to store, retrieve,
and process data. You probably already know that you
can use a computer to type documents, send
email, play games, and browse the Web. You can also
use it to edit or create spreadsheets, presentations,
and even videos.
▪ And computer needs a set of instructions to perform
this tasks and this set of instruction is called as
program.
What is programming-
▪ Programming is the process of taking an algorithm
and encoding it into a notation, a programming
language, so that it can be executed by a computer.
Although many programming languages and many
different types of computers exist, the important first
step is the need to have the solution. Without an
algorithm there can be no program.
▪ By using algorithm we can generate program.
▪ There are different types of programming language .
1.Machine level language.
2.Assembly language.
3.High level language.
1.Machine level language-
▪ machine level language is the language which is
understandable by computer i.e in the form of 0’s and
1’s .
▪ It requires less memory and it has high speed.
▪ But it is not convenient for human .
2.Assembly language-
▪ Assembly language includes some instructions like
MOV ,add etc to do programming.
▪ Its speed is quite less than machine level language and
it requires memory more than machine level language.
▪ There fore it is called as low level language.
3. High level language-
▪ C language is a high level language comparing to
machine level language and assembly language.
▪ It requires more memory comparing to assembly and
machine level language and its speed also low
comparing to both of this.
▪ Then also it is most used language because it is
convenient to human.
Machine Language Assembly Language High level Language
The language of 0s and
1s is called as machine
language.
In Assemblylanguage
are mnemonic (ni-
monic) codes. Like
MOV,ADD etc.
High level languages
are English like
statements and
programs
It requires less Storage
memory.
It requires storage
memory more than
machine level language.
It requires more
memory comparing
both of language.
Speed of execution is
high.
Speed of execution is
quite low.
Speed of execution is
low.
It is not convenientto
human.
It is convenient for
human but Writingcode
in assembly language is
lengthy process.
It is most used language
because it is convenient
to human.
Steps to Learn Language-
Words Constant,Variable & keywords
Sentences Instructions
paragraph Program
History of C language-
▪ C is a general purpose procedure oriented programming
language developed by Dennis Ritchie in 1972 at Bell
telephone laboratories (now ATand T Bell
Laboratories).
A character denotes any alphabet, digit or special symbol
used to represent information. Following list shows the
valid alphabets, numbers and special symbols allowed in
C.
Alphabets-
A B C D E F……………..Z. a b
c d e f……………….z.
Digits-
0,1,2,3,4,5,6,7,8,9.
Special Symbols-
@ # $ % ^ & * () _ = + ~! {} [] ” ’ < > ; : . Etc
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 : Audible alert
n : new line
0 : null
b : backspace
t : tab
The alphabets, numbers and special symbols when
properly combined form constants, variables and
keywords. Let us see what are ‘constants’ and
‘variables’ in C. A constant is an entity that doesn’t
change whereas a variable is an entity that may change.
Constants:
C constants can be divided into two major categories:
(a) Primary Constants
(b) Secondary Constants
C constants
Secondary constants
1.Array.
2.Pointer.
3.Structure.
4.Union.
5.Enum.
6.String
Primary constants
1.Integerconstant.
2.Real constant.
3.Charactor constant.
1. An integer constant must have at least one digit.
2. It must not have a decimal point.
3. It can be either positive or negative.
4. If no sign precedes an integer constant it is assumed to be positive.
5. No commas or blanks are allowed within an integer constant.
6. The allowable range for integer constants is -32768 to 32767.
Ex. 426
+782
-8000
-7605
▪ Real constants are often called Floating Point constants. The real
constants could be written in two forms—
Fractional form and Exponential form.
▪ Following rules must be observed while constructing real
constants expressed in fractional form:
1. A real constant must have at least one digit.
2. It must have a decimal point.
3. It could be either positive or negative.
4. Default sign is positive.
5. No commas or blanks are allowed within a real constant.
Ex. +325.34
426.0
-32.76
-48.5792
1. A character constant is a single alphabet, a single
digit or a single special symbol enclosed within
single inverted commas.
2.The maximum length of a character constant can be
1 character.
Ex. 'A‘
'I'
'5'
'='
▪ As we saw earlier, an entity that may vary during program execution is
called a variable. Variable names are names given to locations in
memory.
▪ These locations can contain integer, real or character constants.
▪ Rules for Constructing Variable Names
1.A variable name is any combination of 1 to 31 alphabets, digits or
underscores. Some compilers allow variable names whose length could
be up to 247 characters. Still, it would be safer to stick to the rule of 31
characters. Do not create unnecessarily long variable names as it adds to
your typing effort.
2.Keywords are not used as a variable.
3. The first character in the variable name must be an alphabet or
underscore.
4. No commas or blanks are allowed within a variable name.
5. No special symbol other than an underscore (as in gross_sal) can be
used in a variable name.
Ex. si_int
m_hra
pop_e_89
▪ Keywords are the words whose meaning has already been
explained to the C compiler .
▪ Keywords are not used as a variable.
▪ There are only 32 keywords available in C.
auto double if static
break else int struct
case enum long switch
char float near typedef
const far register union
continue for return unsigned
default
do
goto
extern
short
signed
void
while
▪ Block Diagram ,Flowchart ,Algorithm for following
system
▪ Car automation.
Light intensity
Air conditioning
▪ Temperature control Fan .
32o c
▪ Home AutomationSystem
Door Open
Light ON
Chapter
02
DataTypes
#include<pre-processor directives>
[macro declaration and defination]
[globle variable declaration]
Main()
{
Local variable declaration with proper data-type;
.
Statements;
.
.
}
[user_defined_function_defination([arguments])]
{
Statement_block;
}
What is Data
Data /
information
Speech
(Float)
Numeric
(Integer/float)
Text
(Character)
Image/Video
(integer)
Type Storage size Value range
char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
int 2 or 4 bytes -32,768 to 32,767 or -
2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to
4,294,967,295
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 4 bytes -2,147,483,648 to
2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
Type Storage size Range
float 4 byte 1.2E-38 to 3.4E+38
double 8 byte 2.3E-308 to 1.7E+308
long double 10 byte 3.4E-4932 to 1.1E+4932
typedef-
• This user defined data type identifier can later be used
to declare the variable.
• Its purpose is to redefine the name of an existing data
type.
• Ex-
typedef int PUNE;
• I can write the variable ‘a’ which has data type intas
below-
PUNE a;
it define a as a integer.
enum day{mon,tue,wed,thr,fri,sat,sun};
0 1 2 3 4 5 6
//declaration of new datatype -
day
enum day{mon=10,tue,wed,thr,fri,sat,sun};
day
10 11 12 13 14 15 16
//declaration of new datatype -
enum day a; // a is a variable whoes type is day.
enum day{mon,tue,wed,thr,fri,sat,sun}a,b,c; // a,b,c:variables
a=mon;
b=sat;
//a=0;
//b=5;
syntax:
int temp;
int a,b,c;
(data_type) expression;
int a=2,b=3,c=4;
int a=0xff; //hex
int a=025; //octal
float a=3.4;
float a=2e-4;.....................2*10^-4
char a='#';
Constant declaration
1. const int a=4;
2. #define a 4
char .....................%c
int........................%d
unsigned int.........%u
short int................%h
long int................%ld
float.....................%f
hex.......................%x
octal.....................%o
string.....................%s
1. Printing message
printf("Message");
printf(« Welcomen to cprogrsmming");
2. Printing value of variable
int a=4,b=6;
printf("%d",a);
printf("%d%d",a,b);
printf("a=%dnb=%d",a,b);
Reading data from user
main()
{
int a,b,c;
printf("enter value of a and b");
scanf("%d%d",&a,&b); //&:address of
c=a+b;
printf("addition=%d",c);
}
1)Write a program “Hello” to user.
2)Write a Program to illustrate the use of int, Character
,Float data Type.
3)Write a program give a name using Scanf() then Print
the Welcome To user.
Chapter
03
Operators in C
1.Arithmatic operators
+ ,- ,* ,/, %
c=a+b;
c=a-b;
c=5/2------->2(Q)
c=5%2----->1(R) // applicable for only integer division
2. Logical operators
&& logical and
|| or
! not
result is T(1) or F(0)
T: any value which is not =0
F: value =0
a=10, b=15;
c=a&&b-------->c=1
3. Relational operators
>, < , >= , <= , == , !=
if((gas==1)||(fire==1))
buzzer=1;
else
buzzer=0;
result is T or F
4. Assignment operator
= , +=, -=, *=, /=, %=,|=,&=,^=,>>=,<<=
c=a+b;
a=a+1;------> a+=1;
a-=4-------->a=a-4;
5. Bitwise operators
&.......and
|...... ..or
~…… compliment
^...... .xor
<<.....left shift
>>.....right shift
c=5&2;
101
& 010
000 -------> c=0;
c=5<<2;
00101<<2
10100------> c=(10100) D
6. Ternary operator (Conditional
Operators)
? :
c=(a>0)? 10:15;
if(a>0)
c=10;
else
c=15;
7. Special operators
*----> value at address of data
&----> address of location
. -------DOT
8. sizeof operator
c=sizeof(short int);-------->1
9. Increment or decrement operators
++, --
int a=4;
a++ --------------> a=a+1;
a > a=a-1;
a++
++a
post incr
pre incr
int a=4;
c=a++;--------------->c=4 (use then incr)
int a=4;
c=++a;--------------->c=5 (incr then use)
1)Program to convert days into months and days.
2)Program to illustrate sizeof operator.
3)Swapping of two variables .
Chapter
04
Decision Making
Statements
C programming language provides following types of
decision making statements
1. if
2. if-else
3. Nested if else
4. switch case
5. goto Statements
1. if statement-
• Syntax-
if(condition)
{
statments;
}
Ex. if(a>b)
{
printf("a is greater");
}
Syntax-
if (condition)
{
statment1;
}
else
{
statment2;
}
Example-
if(a>b)
{
printf("a is greater");
}
else
{
printf("b is greater");
}
Syntax
-
if(condition1)
{
statement1;
}
else if(condition2)
{
statements2;
}
else if(condition3)
{
statements3;
}
else
{
statments;
}
Ex-
if(per>=75)
{
printf("dist");
}
else if((per<75)&&(per>=60))
{
printf("1st class);
}
else
{
printf("fail");
}
Switch is used to switch any function.. if a break is not included at the
end of a case, then execution will continue into the nextcase.
eg switch(2.5)
eg. switch(a>b)
Floating no are not allowed
Condition is not allowed
Syntax-
switch(integer/char constant)
{
case x:
statements;
break;
case Y:
statments;
break;
default:
statments;
.
}
Example -
switch(a)
{
case 20:
printf("twenty");
break; //it is used to jump out of switch
case when case is matched.
case 10:
printf("ten");
break;
.
default:
printf("invalid no");
}
It is used to make jumps in pgm
Syntax-
label:
statments;
'
.
goto label;
statements;
Example-
loop:
printf("enter no: ");
scanf("%d",&a);
if(a>0)
{
goto loop;
}
printf(" u entered –ve no”);
1)Program to accept any number & find out whether it is
negative or positive.
2)Write a program to find out largest number of 4 numbers.
3)Write a program to accept name, marks in 6 subjects find %
of mark & print grade to students.
if student fail in 1 subject then grade is fail.
% >=75 == Distinction
%<75 and %>=60 ==First class
%<60 and %>=50 ==Second Class
%<50 and %>=40 ==Third class
4)Write a program to accept month number and display the
season using switch.
Chapter
05
Loop Control
Structures
• There are three looping statements in c language which
are as follows-
• A. for..........pre test..........counter control
• B. while........pre test..........variable control
• C. Do.While.....post test.........variable control
1. for Loop-
Syntax-
for ( initialise ; Condition ; increment /decrement )
{
Statment;
}
Example-
for(a=1;a<=10;a++)
{
printf("%d",a);
}
• It is often the case in programming that you want to do
something a fixed number of times. The while loop is
ideally suited for such cases.
1. Variable control
int a;
a=10;
2. Counter control
int a;
a=1;................initializatio
n
while(a<=10)...condition
{
printf("%d",a);
a++;.........inc/dec
statement
}
while(a>4)
{
printf("%d",a);
printf("enter value of a");
scanf("%d",&a);
}
Syntax-
do
{
statements;
.
.
.
}while(condition);
eg.
int a=1;
do
{
printf("%d", a);
a++;
}while(a<=10);
Break
•int a=1;
for(a=1;a<=10;a++)
•{
•printf("%d",a);
if(a>5)
•{
•break; // loop is
terminated after a=6;
•}
•}
continue;
Continue
int a;
for(a=1;a<=10;a++)
{
if(a==5)
{
// current iteration of
loop is skipped if a=5;
}
printf("%d",a);
}
1)Write a program for accepting ten numbers and
print. 2)Write a program to display
*
**
***
3)Write a program to find out roots of a quadratic equation.
4)Write a program to print alphabets in a designable manner as
given below
ABCDEDCBA
ABCD DCBA
ABC CBA
AB BA
A A
Chapter
06
Assignment
1)Write a program to Convert given number intoword.
2)Write a program to find sum
3) 1+(1+2)+(1+2+3)+…..(1+2+3+….50) using while loop.
4)Write a program to accept 3 angles of triangle and
check whether it is triangle or not. If the sum of all3
angles is 180 then it is a triangle.
5)Write a program to calculate the income tax the details
are as follows
a) If the person is male
till 100000 Rs of income there is no income tax.
Above 100000 the tax is 10% on the income
b) If the person is female
till 135000 rs of income there is no income tax.
Above 135000 the tax is 10% on the income
Chapter
07
Arrays
• C programming language provides a data structure
called the array, which can store a fixed-size
sequential collection of elements of the same type.
• All arrays consist of contiguous memory locations. The
lowest address corresponds to the first element and the
highest address to the last element.
➢ DeclaringArrays
To declare an array in C, a programmer specifies the type of the
elements and the number of elements required by an array as follow.
Data_type arrayName [ arraySize ];
This is called a single-dimensional array.
➢ InitializingArrays
Initialize array in C either one by one or using a single statement
as follows:
int balance[5] = {1,2,3,4,5};
The number of values between braces { } can not be larger than
the number of elements that we declare for the array between
square brackets [ ].
int a[];.........................a is array of integer
int a[5]; ......................5 is size of array a.
int a[5]={10, 20, 30, 40, 50};
a[0] a[1] a[2] a[3] a[4]
int a[5]={10,5}.............rest locations are filled with zeros
char a[4]="pune";
char a[4]={'p','u','n','e','0'};
•data_type array_name [rows][coloumn];
Ex-
int value [2][3];
It implies 2 rows and 3 coloumns.
Initialization of 2D array-
int value [2][3]={2,11,3,5,1,10};
This initialized array can be represented as-
col0 col1 col2
row0 2 11 3
Row1 5 1 10
Ex-
int a[5]={10,20,30,40,50};
int i;
for(i=0;i<5;i++)
{
printf("%d",a[i]);
}
2D-
int a[3][3]={1,2,3,4,5,6,7,8,9 };
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d",a[i][j]);
}
printf("n");
}
Multidimensional array-
• Arrays in c may have more than one dimension. such
arrays are called multi dimensional array.
• 2D array- Two dimensional arrays are used to store a
table of values. Thus it is refered to as matrix or table.
• A matrix has two subscripts, the first subscriptdenotes
the no of rows and second subscript denotes no. of
column.
1)Accepting 10 numbers and print.
2)Program for addition of 1-D array.
3)Write a program for finding matrix addition.
4)Write a program for accepting 10 numbers and print sum of odd
numbers and even numbers.
5)In one organization there are 3 department, every department has 3
teacher and each teacher can teach to 5 individual students . Write a
program to accept the marks of each student and display the report
of passing percentage of each department.
Chapter
08
Pointers
• Pointers are the variables that contain the address of
another variable within the memory.
• EX-
int x=5;
X variable
value
1002 Address
fig: representation of x=5 in the memory
5
Syntax-
data_type * ptvar;
name of the pointer var.
*indicates that this variable is a pointer
.
data type of pointers object.
Ex- int *p –it declares that points to an integer data type.
Ex-
int a=5 ,x, *aptr;
aptr= &a; // assigns the address of variable ‘a’to
pointer ‘aptr’
//assigns the value at address
pointed by ‘aptr’ to variablex
i.e x=5.
x= *aptr;
Eg-
int a=4;
int *p; //p stores memory location's address
& : address of
* : value at address
p=&a;
c=*p;
int a=5;
int *p;
p=&a;
printf("%d",a);--------------5
printf("%u",&a);-------------1000
printf("%d",*p);--------------5
printf("%d",*(&a));-----------5
printf("%u",p);---------------1000
int a[5];
int *p;
p=a; //p= base address of a(add of 1st element)
for(i=0;i<5;i++)
{
printf("%d",*(p+i));
// p++;
}
……………..read from user..............
for(i=0;i<5;i++)
{
scanf("%d",p+i);
// p++;
}
1)Write a program to print the address of a variable along
with its value.
2) C Program to Access Elements of an Array UsingPointer
Chapter
09
Functions
Introduction
A function is a group of statements that together perform a task.
Every C program has at least one function, which is main().
Two Types Of Function
1. library functions
2. user defined function
Defining a Function:
The general form of a function definition in C programming language
is as follows:
return_type function_name ( parameter list )
{
body of the function
}
• Syntax-
return_datatype function name ( arg1, arg2,…..);
arg list
Name of the function
return datatype(optional)
Types of
function calls-
Functions can be called in different ways-
1. functions with no arguments and no return values.
Ex .main()
2. Functions with arguments and no return values.
Ex. void main()
3. Functions with arguments and return values
Ex. void main(void)
• Call by value
This method copies the actual value of an argument
into the formal parameter of the function. In this case,
changes made to the parameter inside the function have
no effect on the argument.
• Call by reference
This method copies the address of an argument into the
formal parameter. Inside the function, the address is
used to access the actual argument used in the call. This
means that changes made to the parameter affect the
argument.
eg.
#include<stdio.h>
void square();
main()
{
//fn prototype/declaration
printf(" pgm to find square of a no");
square();
printf("the end");
}
void square()
{
int a,b;
printf("enter value of a");
scanf("%d",&a);
b=a*a;
printf("%d",b);
}
Eg-
#include<stdio.h>
void square(int);
main()
{
int a;
//fn prototype/declaration
printf(" pgm to find square of a no");
printf("enter value of a");
scanf("%d",&a);
square(a);
printf("the end");
}
void square(int x)
{
int y;
y=x*x;
printf("%d",y);
}
Eg-
#include<stdio.h>
int square(int);
main()
{
int a,b;
//fn prototype/declaration
printf(" pgm to find square of a no");
printf("enter value of a");
scanf("%d",&a);
b=square(a);
printf("%d",b);
printf("the end");
}
int square(int x)
{
int y;
y=x*x;
return(y);
}
1) C Program to Display Prime Numbers Between
Intervals Using User-defined Function.
2)Write a program to find out sin,cos,tan values of a
given range using pre defined function.
Chapter
10
Strings
• The string in C programming language is actually a one-
dimensional array of characters which is terminated by a
null character '0'.
• The following declaration and initialization create a string consisting
of the word "Hello". To hold the null character at the end of the array,
the size of the character array containing the string is one more than
the number of characters in the word "Hello.“
• char greeting[6] = {'H', 'e', 'l', 'l', 'o', '0'};
• If you follow the rule of array initialization then you can write
the above statement as follows:
• char greeting[ ] = "Hello";
• Following is the memory presentation of above defined string
in C/C++:
The few Standard library functions that deal with
strings. They all are declared in the header file string.h.
All these functions perform certain operation on string.
1)strlen(s1)->Length of the string s1
2)Strcat(s1,s2,N)->Concatenate of string1 to string2 and
terminates s1 with null.
3)strcmp(s1,s2)->Compares S1 and s2
4)strcpy(s1,s2)->copies the string s2 into string s1.
1)strlen(s1)
In below example program, length of the string “4dimension” is
determined by strlen( ) function as below. Length of this string 10is
displayed as output.
Eg.
#include <stdio.h>
#include <string.h>
int main( )
{
int len;
char array[20]=“4dimension" ;
len = strlen(array) ;
printf ( "string length = %d n" , len ) ;
return 0;
}
2)Strcat(s1,s2,N)
It concatenates two strings and returns the combined one string.
Eg. #include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strncat(s1,s2, 3);
printf("Concatenation using strncat: %s", s1);
return 0;
}
Output:
Concatenation using strncat: HelloWor
3)strcmp(s1,s2)
In this program, strings “fresh” and “refresh” are compared. 0 is
returned when strings are equal. Negative value is returned
when str1 < str2 and positive value is returned when str1 > str2.
Eg. #include <stdio.h>
#include <string.h>
int main( )
{
char str1[ ] = "fresh" ;
char str2[ ] = "refresh" ;
int i, j, k ;
i = strcmp ( str1, "fresh" ) ;
j = strcmp ( str1, str2 ) ;
k = strcmp ( str1, "f" ) ;
printf ( "n%d %d %d", i, j, k ) ;
return 0;
}
4)strcpy(s1,s2)
It copies the string str2 into string str1.
Eg.
#include <stdio.h>
#include <string.h>
int main()
{
char s1[30] = "string 1";
char s2[30] = "string 2 : I’m copied into s1";
/* this function has copied s2 into s1*/
strcpy(s1,s2);
printf("String s1 is: %s", s1);
return 0;
}
Output:
String s1 is: string 2: I’m copied into s1
1)Write a program to accept two
strings and concatenate them.
2)Write a program to accept full name from the keyboard
and display surname first and then middle name.
Chapter
01
Structures and
Union
• C arrays allow you to define type of variables that can hold
several data items of the same kind but structure is another
user defined data type available in C programming, which
allows you to combine data items of different kinds.
• Structures are used to represent a record, Suppose you want to
keep track of your books in a library. You might want to track
the following attributes about each book:
• Defining a Structure
• To define a structure, you must use the struct statement. The
struct statement defines a new data type, with more than one
member for your program. The format of the struct statement
is this:
struct [structure tag]
{
member definition;
member definition;
...
member definition;
} [one or more structure variables];
Example-
struct book
{
char title[10];
float price;
int quantity;
};
struct book b1,b2,b3; //structure variables
Eg.
struct book
{
char title[10];
float price;
int quantity;
}b[10];
printf("enter book info");
for(i=0;i<10;i++)
{
scanf("%s%f%d",b[i].title,&b[i].price,&b[i].quantity);
}
• 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 sharing of memory space.
union book
{
char a; //------1byte
float b; //-----4bytes
int c; //-------2bytes
//-------total=7bytes
};
union book math; //---------------------------4bytes
math.a='@';
math.c=125;
printf("%c",math.a);
1)Write a program to accept name , address and phone
number of employee using structure and print the
same.
2)Accept basic pay, dearness allowance, travelling
allowance, house rent allowance of n employee and
calculate the salary of employ’s
DA is 35 % basic pay
TAis 15 % basic pay
HRA is 20 % of basic pay
Chapter
12
Storage Class
There are the following storage classes, which can be
used in a C Program
❑ auto
❑ register
❑ static
❑ extern
Storage class defines following:
1. Scope of variable
2. Storage
3. lifetime
4. initial value
1.auto (local variables)
a. scope: local(within block or fn)
b. storage: temp. memory
c. lifetime : within block or fn.
d. initial value: garbage
int a;
main()
{
//global
auto int b; //local
b=a+4;
}
square()
{
int c;
c=a+8;
}
2. extern (global variables)
a.scope: global(within file or
pgm)
b. storage: permanent. memory
c. lifetime : within file(global)
d. initial value: zero
main()
{
extern int a;
auto int b; //local
b=a+4;
}
int a; //global
square()
{
int c;
c=a+8;
}
3. static(local variables)
a.scope: local(within block or
fn)
b. storage: permanent. memory
c. lifetime : (global)
d. initial value: zero
main()
{
int i;
for(i=0;i<3;i++)
{
add();
}
}
add()
{
static int a=0;
// this executes only once
a++;
printf("%d",a);
}
4. register(local)
a. scope: local(within block or fn)
b. storage: CPU register
c. lifetime : within block or fn
d. initial value: garbage
Instructions to compiler
1. File inclusion
2. macro
3. compiler control
1. file inclusion. #include
#include<file_name>
#include"file_name"
2. macro
#define
a. #define PI 3.14
b. #define print printf("hello")
main()
{
print; //printf("hello");
}
c. macro with arguments
#define square(x) (x*x)
main()
{
int a=4,b;
b=square(a);
}
d. nesting of macro
#define square(x) (x*x)
#define cube(x) (square(x)*x)
main()
{
int a=4,b;
b=cube(a);
}
3. compiler control
a.#ifdef.................(if defined)
b.#ifndef..............(if not defined)
c.#undef...............(undefine)
d.#if......................(if condition)
e.#else..................(alternate to if)
f.#elif...................(else if)
g.#endif................(end if)
h.#pragma.............(hardware specific configuration of compiler)
#define PIC 18
main()
{
#ifdef PIC
printf("u r using PIC MCU");
#endif
}
main()
{
#ifndef PIC
printf("u r not using PIC MCU");
endif
}
#if(PIC==12)
printf("u r using PIC12");
#elif(PIC==16)
printf("u r using PIC16");
#else
printf("PIC18");
#endif
}
#define PIC 18
#ifdef PIC
#undef PIC
#define PIC 24
#endif
main()
{
printf("%d",PIC);
}
//24
#define PIC 18
main()
{
#if(PIC==12)
printf("u r using PIC12");
#elif(PIC==16)
printf("u r using PIC16");
#else
printf("PIC18");
#endif
}
Thank you !

C programming Ms. Pranoti Doke

  • 1.
    C PROGRAMMING LANGUAGE Pranoti R.Doke ME(Entc), BE(Entc)
  • 2.
  • 3.
    What is automation? Automationis basically the delegation of human control function to technical equipment. It is the use of control systems such as computers, PLCs, Microcontrollers to control machinery and processes to reduce the need for human sensory and mental requirements as well.
  • 4.
    Now what ismean by Computer- ▪ A computer is an electronic device that manipulates information, or data. It has the ability to store, retrieve, and process data. You probably already know that you can use a computer to type documents, send email, play games, and browse the Web. You can also use it to edit or create spreadsheets, presentations, and even videos. ▪ And computer needs a set of instructions to perform this tasks and this set of instruction is called as program.
  • 5.
    What is programming- ▪Programming is the process of taking an algorithm and encoding it into a notation, a programming language, so that it can be executed by a computer. Although many programming languages and many different types of computers exist, the important first step is the need to have the solution. Without an algorithm there can be no program. ▪ By using algorithm we can generate program.
  • 6.
    ▪ There aredifferent types of programming language . 1.Machine level language. 2.Assembly language. 3.High level language. 1.Machine level language- ▪ machine level language is the language which is understandable by computer i.e in the form of 0’s and 1’s . ▪ It requires less memory and it has high speed. ▪ But it is not convenient for human .
  • 7.
    2.Assembly language- ▪ Assemblylanguage includes some instructions like MOV ,add etc to do programming. ▪ Its speed is quite less than machine level language and it requires memory more than machine level language. ▪ There fore it is called as low level language.
  • 8.
    3. High levellanguage- ▪ C language is a high level language comparing to machine level language and assembly language. ▪ It requires more memory comparing to assembly and machine level language and its speed also low comparing to both of this. ▪ Then also it is most used language because it is convenient to human.
  • 9.
    Machine Language AssemblyLanguage High level Language The language of 0s and 1s is called as machine language. In Assemblylanguage are mnemonic (ni- monic) codes. Like MOV,ADD etc. High level languages are English like statements and programs It requires less Storage memory. It requires storage memory more than machine level language. It requires more memory comparing both of language. Speed of execution is high. Speed of execution is quite low. Speed of execution is low. It is not convenientto human. It is convenient for human but Writingcode in assembly language is lengthy process. It is most used language because it is convenient to human.
  • 10.
    Steps to LearnLanguage- Words Constant,Variable & keywords Sentences Instructions paragraph Program
  • 11.
    History of Clanguage- ▪ C is a general purpose procedure oriented programming language developed by Dennis Ritchie in 1972 at Bell telephone laboratories (now ATand T Bell Laboratories).
  • 12.
    A character denotesany alphabet, digit or special symbol used to represent information. Following list shows the valid alphabets, numbers and special symbols allowed in C. Alphabets- A B C D E F……………..Z. a b c d e f……………….z. Digits- 0,1,2,3,4,5,6,7,8,9. Special Symbols- @ # $ % ^ & * () _ = + ~! {} [] ” ’ < > ; : . Etc
  • 13.
    An escape sequenceis 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 : Audible alert n : new line 0 : null b : backspace t : tab
  • 14.
    The alphabets, numbersand special symbols when properly combined form constants, variables and keywords. Let us see what are ‘constants’ and ‘variables’ in C. A constant is an entity that doesn’t change whereas a variable is an entity that may change. Constants: C constants can be divided into two major categories: (a) Primary Constants (b) Secondary Constants
  • 15.
    C constants Secondary constants 1.Array. 2.Pointer. 3.Structure. 4.Union. 5.Enum. 6.String Primaryconstants 1.Integerconstant. 2.Real constant. 3.Charactor constant.
  • 16.
    1. An integerconstant must have at least one digit. 2. It must not have a decimal point. 3. It can be either positive or negative. 4. If no sign precedes an integer constant it is assumed to be positive. 5. No commas or blanks are allowed within an integer constant. 6. The allowable range for integer constants is -32768 to 32767. Ex. 426 +782 -8000 -7605
  • 17.
    ▪ Real constantsare often called Floating Point constants. The real constants could be written in two forms— Fractional form and Exponential form. ▪ Following rules must be observed while constructing real constants expressed in fractional form: 1. A real constant must have at least one digit. 2. It must have a decimal point. 3. It could be either positive or negative. 4. Default sign is positive. 5. No commas or blanks are allowed within a real constant. Ex. +325.34 426.0 -32.76 -48.5792
  • 18.
    1. A characterconstant is a single alphabet, a single digit or a single special symbol enclosed within single inverted commas. 2.The maximum length of a character constant can be 1 character. Ex. 'A‘ 'I' '5' '='
  • 19.
    ▪ As wesaw earlier, an entity that may vary during program execution is called a variable. Variable names are names given to locations in memory. ▪ These locations can contain integer, real or character constants. ▪ Rules for Constructing Variable Names 1.A variable name is any combination of 1 to 31 alphabets, digits or underscores. Some compilers allow variable names whose length could be up to 247 characters. Still, it would be safer to stick to the rule of 31 characters. Do not create unnecessarily long variable names as it adds to your typing effort. 2.Keywords are not used as a variable. 3. The first character in the variable name must be an alphabet or underscore. 4. No commas or blanks are allowed within a variable name. 5. No special symbol other than an underscore (as in gross_sal) can be used in a variable name. Ex. si_int m_hra pop_e_89
  • 20.
    ▪ Keywords arethe words whose meaning has already been explained to the C compiler . ▪ Keywords are not used as a variable. ▪ There are only 32 keywords available in C. auto double if static break else int struct case enum long switch char float near typedef const far register union continue for return unsigned default do goto extern short signed void while
  • 21.
    ▪ Block Diagram,Flowchart ,Algorithm for following system ▪ Car automation. Light intensity Air conditioning ▪ Temperature control Fan . 32o c ▪ Home AutomationSystem Door Open Light ON
  • 22.
  • 23.
    #include<pre-processor directives> [macro declarationand defination] [globle variable declaration] Main() { Local variable declaration with proper data-type; . Statements; . . } [user_defined_function_defination([arguments])] { Statement_block; }
  • 24.
    What is Data Data/ information Speech (Float) Numeric (Integer/float) Text (Character) Image/Video (integer)
  • 25.
    Type Storage sizeValue range char 1 byte -128 to 127 or 0 to 255 unsigned char 1 byte 0 to 255 signed char 1 byte -128 to 127 int 2 or 4 bytes -32,768 to 32,767 or - 2,147,483,648 to 2,147,483,647 unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295 short 2 bytes -32,768 to 32,767 unsigned short 2 bytes 0 to 65,535 long 4 bytes -2,147,483,648 to 2,147,483,647 unsigned long 4 bytes 0 to 4,294,967,295
  • 26.
    Type Storage sizeRange float 4 byte 1.2E-38 to 3.4E+38 double 8 byte 2.3E-308 to 1.7E+308 long double 10 byte 3.4E-4932 to 1.1E+4932
  • 27.
    typedef- • This userdefined data type identifier can later be used to declare the variable. • Its purpose is to redefine the name of an existing data type. • Ex- typedef int PUNE; • I can write the variable ‘a’ which has data type intas below- PUNE a; it define a as a integer.
  • 28.
    enum day{mon,tue,wed,thr,fri,sat,sun}; 0 12 3 4 5 6 //declaration of new datatype - day enum day{mon=10,tue,wed,thr,fri,sat,sun}; day 10 11 12 13 14 15 16 //declaration of new datatype - enum day a; // a is a variable whoes type is day. enum day{mon,tue,wed,thr,fri,sat,sun}a,b,c; // a,b,c:variables a=mon; b=sat; //a=0; //b=5;
  • 29.
    syntax: int temp; int a,b,c; (data_type)expression; int a=2,b=3,c=4; int a=0xff; //hex int a=025; //octal float a=3.4; float a=2e-4;.....................2*10^-4 char a='#'; Constant declaration 1. const int a=4; 2. #define a 4
  • 30.
    char .....................%c int........................%d unsigned int.........%u shortint................%h long int................%ld float.....................%f hex.......................%x octal.....................%o string.....................%s
  • 31.
    1. Printing message printf("Message"); printf(«Welcomen to cprogrsmming"); 2. Printing value of variable int a=4,b=6; printf("%d",a); printf("%d%d",a,b); printf("a=%dnb=%d",a,b);
  • 32.
    Reading data fromuser main() { int a,b,c; printf("enter value of a and b"); scanf("%d%d",&a,&b); //&:address of c=a+b; printf("addition=%d",c); }
  • 33.
    1)Write a program“Hello” to user. 2)Write a Program to illustrate the use of int, Character ,Float data Type. 3)Write a program give a name using Scanf() then Print the Welcome To user.
  • 34.
  • 35.
    1.Arithmatic operators + ,-,* ,/, % c=a+b; c=a-b; c=5/2------->2(Q) c=5%2----->1(R) // applicable for only integer division
  • 36.
    2. Logical operators &&logical and || or ! not result is T(1) or F(0) T: any value which is not =0 F: value =0 a=10, b=15; c=a&&b-------->c=1
  • 37.
    3. Relational operators >,< , >= , <= , == , != if((gas==1)||(fire==1)) buzzer=1; else buzzer=0; result is T or F
  • 38.
    4. Assignment operator =, +=, -=, *=, /=, %=,|=,&=,^=,>>=,<<= c=a+b; a=a+1;------> a+=1; a-=4-------->a=a-4;
  • 39.
    5. Bitwise operators &.......and |........or ~…… compliment ^...... .xor <<.....left shift >>.....right shift c=5&2; 101 & 010 000 -------> c=0; c=5<<2; 00101<<2 10100------> c=(10100) D
  • 40.
    6. Ternary operator(Conditional Operators) ? : c=(a>0)? 10:15; if(a>0) c=10; else c=15;
  • 41.
    7. Special operators *---->value at address of data &----> address of location . -------DOT 8. sizeof operator c=sizeof(short int);-------->1
  • 42.
    9. Increment ordecrement operators ++, -- int a=4; a++ --------------> a=a+1; a > a=a-1; a++ ++a post incr pre incr int a=4; c=a++;--------------->c=4 (use then incr) int a=4; c=++a;--------------->c=5 (incr then use)
  • 43.
    1)Program to convertdays into months and days. 2)Program to illustrate sizeof operator. 3)Swapping of two variables .
  • 44.
  • 45.
    C programming languageprovides following types of decision making statements 1. if 2. if-else 3. Nested if else 4. switch case 5. goto Statements
  • 46.
    1. if statement- •Syntax- if(condition) { statments; } Ex. if(a>b) { printf("a is greater"); }
  • 47.
  • 48.
  • 49.
    Switch is usedto switch any function.. if a break is not included at the end of a case, then execution will continue into the nextcase. eg switch(2.5) eg. switch(a>b) Floating no are not allowed Condition is not allowed Syntax- switch(integer/char constant) { case x: statements; break; case Y: statments; break; default: statments; . }
  • 50.
    Example - switch(a) { case 20: printf("twenty"); break;//it is used to jump out of switch case when case is matched. case 10: printf("ten"); break; . default: printf("invalid no"); }
  • 51.
    It is usedto make jumps in pgm Syntax- label: statments; ' . goto label; statements; Example- loop: printf("enter no: "); scanf("%d",&a); if(a>0) { goto loop; } printf(" u entered –ve no”);
  • 52.
    1)Program to acceptany number & find out whether it is negative or positive. 2)Write a program to find out largest number of 4 numbers. 3)Write a program to accept name, marks in 6 subjects find % of mark & print grade to students. if student fail in 1 subject then grade is fail. % >=75 == Distinction %<75 and %>=60 ==First class %<60 and %>=50 ==Second Class %<50 and %>=40 ==Third class 4)Write a program to accept month number and display the season using switch.
  • 53.
  • 54.
    • There arethree looping statements in c language which are as follows- • A. for..........pre test..........counter control • B. while........pre test..........variable control • C. Do.While.....post test.........variable control
  • 55.
    1. for Loop- Syntax- for( initialise ; Condition ; increment /decrement ) { Statment; } Example- for(a=1;a<=10;a++) { printf("%d",a); }
  • 56.
    • It isoften the case in programming that you want to do something a fixed number of times. The while loop is ideally suited for such cases. 1. Variable control int a; a=10; 2. Counter control int a; a=1;................initializatio n while(a<=10)...condition { printf("%d",a); a++;.........inc/dec statement } while(a>4) { printf("%d",a); printf("enter value of a"); scanf("%d",&a); }
  • 57.
  • 58.
    Break •int a=1; for(a=1;a<=10;a++) •{ •printf("%d",a); if(a>5) •{ •break; //loop is terminated after a=6; •} •} continue; Continue int a; for(a=1;a<=10;a++) { if(a==5) { // current iteration of loop is skipped if a=5; } printf("%d",a); }
  • 59.
    1)Write a programfor accepting ten numbers and print. 2)Write a program to display * ** *** 3)Write a program to find out roots of a quadratic equation. 4)Write a program to print alphabets in a designable manner as given below ABCDEDCBA ABCD DCBA ABC CBA AB BA A A
  • 60.
  • 61.
    1)Write a programto Convert given number intoword. 2)Write a program to find sum 3) 1+(1+2)+(1+2+3)+…..(1+2+3+….50) using while loop. 4)Write a program to accept 3 angles of triangle and check whether it is triangle or not. If the sum of all3 angles is 180 then it is a triangle. 5)Write a program to calculate the income tax the details are as follows a) If the person is male till 100000 Rs of income there is no income tax. Above 100000 the tax is 10% on the income b) If the person is female till 135000 rs of income there is no income tax. Above 135000 the tax is 10% on the income
  • 62.
  • 63.
    • C programminglanguage provides a data structure called the array, which can store a fixed-size sequential collection of elements of the same type. • All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
  • 64.
    ➢ DeclaringArrays To declarean array in C, a programmer specifies the type of the elements and the number of elements required by an array as follow. Data_type arrayName [ arraySize ]; This is called a single-dimensional array. ➢ InitializingArrays Initialize array in C either one by one or using a single statement as follows: int balance[5] = {1,2,3,4,5}; The number of values between braces { } can not be larger than the number of elements that we declare for the array between square brackets [ ].
  • 65.
    int a[];.........................a isarray of integer int a[5]; ......................5 is size of array a. int a[5]={10, 20, 30, 40, 50}; a[0] a[1] a[2] a[3] a[4] int a[5]={10,5}.............rest locations are filled with zeros char a[4]="pune"; char a[4]={'p','u','n','e','0'};
  • 66.
    •data_type array_name [rows][coloumn]; Ex- intvalue [2][3]; It implies 2 rows and 3 coloumns. Initialization of 2D array- int value [2][3]={2,11,3,5,1,10}; This initialized array can be represented as- col0 col1 col2 row0 2 11 3 Row1 5 1 10
  • 67.
    Ex- int a[5]={10,20,30,40,50}; int i; for(i=0;i<5;i++) { printf("%d",a[i]); } 2D- inta[3][3]={1,2,3,4,5,6,7,8,9 }; for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf("%d",a[i][j]); } printf("n"); }
  • 68.
    Multidimensional array- • Arraysin c may have more than one dimension. such arrays are called multi dimensional array. • 2D array- Two dimensional arrays are used to store a table of values. Thus it is refered to as matrix or table. • A matrix has two subscripts, the first subscriptdenotes the no of rows and second subscript denotes no. of column.
  • 69.
    1)Accepting 10 numbersand print. 2)Program for addition of 1-D array. 3)Write a program for finding matrix addition. 4)Write a program for accepting 10 numbers and print sum of odd numbers and even numbers. 5)In one organization there are 3 department, every department has 3 teacher and each teacher can teach to 5 individual students . Write a program to accept the marks of each student and display the report of passing percentage of each department.
  • 70.
  • 71.
    • Pointers arethe variables that contain the address of another variable within the memory. • EX- int x=5; X variable value 1002 Address fig: representation of x=5 in the memory 5
  • 72.
    Syntax- data_type * ptvar; nameof the pointer var. *indicates that this variable is a pointer . data type of pointers object. Ex- int *p –it declares that points to an integer data type.
  • 73.
    Ex- int a=5 ,x,*aptr; aptr= &a; // assigns the address of variable ‘a’to pointer ‘aptr’ //assigns the value at address pointed by ‘aptr’ to variablex i.e x=5. x= *aptr;
  • 74.
    Eg- int a=4; int *p;//p stores memory location's address & : address of * : value at address p=&a; c=*p; int a=5; int *p; p=&a; printf("%d",a);--------------5 printf("%u",&a);-------------1000 printf("%d",*p);--------------5 printf("%d",*(&a));-----------5 printf("%u",p);---------------1000
  • 75.
    int a[5]; int *p; p=a;//p= base address of a(add of 1st element) for(i=0;i<5;i++) { printf("%d",*(p+i)); // p++; } ……………..read from user.............. for(i=0;i<5;i++) { scanf("%d",p+i); // p++; }
  • 76.
    1)Write a programto print the address of a variable along with its value. 2) C Program to Access Elements of an Array UsingPointer
  • 77.
  • 78.
    Introduction A function isa group of statements that together perform a task. Every C program has at least one function, which is main(). Two Types Of Function 1. library functions 2. user defined function Defining a Function: The general form of a function definition in C programming language is as follows: return_type function_name ( parameter list ) { body of the function }
  • 79.
    • Syntax- return_datatype functionname ( arg1, arg2,…..); arg list Name of the function return datatype(optional)
  • 80.
    Types of function calls- Functionscan be called in different ways- 1. functions with no arguments and no return values. Ex .main() 2. Functions with arguments and no return values. Ex. void main() 3. Functions with arguments and return values Ex. void main(void)
  • 81.
    • Call byvalue This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. • Call by reference This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.
  • 82.
    eg. #include<stdio.h> void square(); main() { //fn prototype/declaration printf("pgm to find square of a no"); square(); printf("the end"); } void square() { int a,b; printf("enter value of a"); scanf("%d",&a); b=a*a; printf("%d",b); }
  • 83.
    Eg- #include<stdio.h> void square(int); main() { int a; //fnprototype/declaration printf(" pgm to find square of a no"); printf("enter value of a"); scanf("%d",&a); square(a); printf("the end"); } void square(int x) { int y; y=x*x; printf("%d",y); }
  • 84.
    Eg- #include<stdio.h> int square(int); main() { int a,b; //fnprototype/declaration printf(" pgm to find square of a no"); printf("enter value of a"); scanf("%d",&a); b=square(a); printf("%d",b); printf("the end"); } int square(int x) { int y; y=x*x; return(y); }
  • 85.
    1) C Programto Display Prime Numbers Between Intervals Using User-defined Function. 2)Write a program to find out sin,cos,tan values of a given range using pre defined function.
  • 86.
  • 87.
    • The stringin C programming language is actually a one- dimensional array of characters which is terminated by a null character '0'. • The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello.“ • char greeting[6] = {'H', 'e', 'l', 'l', 'o', '0'};
  • 88.
    • If youfollow the rule of array initialization then you can write the above statement as follows: • char greeting[ ] = "Hello"; • Following is the memory presentation of above defined string in C/C++:
  • 89.
    The few Standardlibrary functions that deal with strings. They all are declared in the header file string.h. All these functions perform certain operation on string. 1)strlen(s1)->Length of the string s1 2)Strcat(s1,s2,N)->Concatenate of string1 to string2 and terminates s1 with null. 3)strcmp(s1,s2)->Compares S1 and s2 4)strcpy(s1,s2)->copies the string s2 into string s1.
  • 90.
    1)strlen(s1) In below exampleprogram, length of the string “4dimension” is determined by strlen( ) function as below. Length of this string 10is displayed as output. Eg. #include <stdio.h> #include <string.h> int main( ) { int len; char array[20]=“4dimension" ; len = strlen(array) ; printf ( "string length = %d n" , len ) ; return 0; }
  • 91.
    2)Strcat(s1,s2,N) It concatenates twostrings and returns the combined one string. Eg. #include <stdio.h> #include <string.h> int main() { char s1[10] = "Hello"; char s2[10] = "World"; strncat(s1,s2, 3); printf("Concatenation using strncat: %s", s1); return 0; } Output: Concatenation using strncat: HelloWor
  • 92.
    3)strcmp(s1,s2) In this program,strings “fresh” and “refresh” are compared. 0 is returned when strings are equal. Negative value is returned when str1 < str2 and positive value is returned when str1 > str2. Eg. #include <stdio.h> #include <string.h> int main( ) { char str1[ ] = "fresh" ; char str2[ ] = "refresh" ; int i, j, k ; i = strcmp ( str1, "fresh" ) ; j = strcmp ( str1, str2 ) ; k = strcmp ( str1, "f" ) ; printf ( "n%d %d %d", i, j, k ) ; return 0; }
  • 93.
    4)strcpy(s1,s2) It copies thestring str2 into string str1. Eg. #include <stdio.h> #include <string.h> int main() { char s1[30] = "string 1"; char s2[30] = "string 2 : I’m copied into s1"; /* this function has copied s2 into s1*/ strcpy(s1,s2); printf("String s1 is: %s", s1); return 0; } Output: String s1 is: string 2: I’m copied into s1
  • 94.
    1)Write a programto accept two strings and concatenate them. 2)Write a program to accept full name from the keyboard and display surname first and then middle name.
  • 95.
  • 96.
    • C arraysallow you to define type of variables that can hold several data items of the same kind but structure is another user defined data type available in C programming, which allows you to combine data items of different kinds. • Structures are used to represent a record, Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book:
  • 97.
    • Defining aStructure • To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member for your program. The format of the struct statement is this: struct [structure tag] { member definition; member definition; ... member definition; } [one or more structure variables];
  • 98.
    Example- struct book { char title[10]; floatprice; int quantity; }; struct book b1,b2,b3; //structure variables
  • 99.
    Eg. struct book { char title[10]; floatprice; int quantity; }b[10]; printf("enter book info"); for(i=0;i<10;i++) { scanf("%s%f%d",b[i].title,&b[i].price,&b[i].quantity); }
  • 100.
    • Union isa 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 sharing of memory space. union book { char a; //------1byte float b; //-----4bytes int c; //-------2bytes //-------total=7bytes }; union book math; //---------------------------4bytes math.a='@'; math.c=125; printf("%c",math.a);
  • 102.
    1)Write a programto accept name , address and phone number of employee using structure and print the same. 2)Accept basic pay, dearness allowance, travelling allowance, house rent allowance of n employee and calculate the salary of employ’s DA is 35 % basic pay TAis 15 % basic pay HRA is 20 % of basic pay
  • 103.
  • 104.
    There are thefollowing storage classes, which can be used in a C Program ❑ auto ❑ register ❑ static ❑ extern Storage class defines following: 1. Scope of variable 2. Storage 3. lifetime 4. initial value
  • 105.
    1.auto (local variables) a.scope: local(within block or fn) b. storage: temp. memory c. lifetime : within block or fn. d. initial value: garbage int a; main() { //global auto int b; //local b=a+4; } square() { int c; c=a+8; }
  • 106.
    2. extern (globalvariables) a.scope: global(within file or pgm) b. storage: permanent. memory c. lifetime : within file(global) d. initial value: zero main() { extern int a; auto int b; //local b=a+4; } int a; //global square() { int c; c=a+8; }
  • 107.
    3. static(local variables) a.scope:local(within block or fn) b. storage: permanent. memory c. lifetime : (global) d. initial value: zero main() { int i; for(i=0;i<3;i++) { add(); } } add() { static int a=0; // this executes only once a++; printf("%d",a); }
  • 108.
    4. register(local) a. scope:local(within block or fn) b. storage: CPU register c. lifetime : within block or fn d. initial value: garbage
  • 109.
    Instructions to compiler 1.File inclusion 2. macro 3. compiler control 1. file inclusion. #include #include<file_name> #include"file_name" 2. macro #define a. #define PI 3.14 b. #define print printf("hello") main() { print; //printf("hello"); }
  • 110.
    c. macro witharguments #define square(x) (x*x) main() { int a=4,b; b=square(a); } d. nesting of macro #define square(x) (x*x) #define cube(x) (square(x)*x) main() { int a=4,b; b=cube(a); }
  • 111.
    3. compiler control a.#ifdef.................(ifdefined) b.#ifndef..............(if not defined) c.#undef...............(undefine) d.#if......................(if condition) e.#else..................(alternate to if) f.#elif...................(else if) g.#endif................(end if) h.#pragma.............(hardware specific configuration of compiler)
  • 112.
    #define PIC 18 main() { #ifdefPIC printf("u r using PIC MCU"); #endif } main() { #ifndef PIC printf("u r not using PIC MCU"); endif } #if(PIC==12) printf("u r using PIC12"); #elif(PIC==16) printf("u r using PIC16"); #else printf("PIC18"); #endif }
  • 113.
    #define PIC 18 #ifdefPIC #undef PIC #define PIC 24 #endif main() { printf("%d",PIC); } //24 #define PIC 18 main() { #if(PIC==12) printf("u r using PIC12"); #elif(PIC==16) printf("u r using PIC16"); #else printf("PIC18"); #endif }
  • 114.