Professional Documents
Culture Documents
char name[20];
int rollno;
float percent;
}s;
's' is name of Structure variable
Method 2: Declare Variables using struct Keyword
struct student
{
char name[20];
int rollno;
float percent;
};
struct student s;
where “student” is name of structure and “s” is name of variable.
Method 3 : Declaring Multiple Structure Variables
struct student
{
char name[20];
int rollno;
float percent;
}s1,s2,s3;
We can declare multiple variables separated by comma directly after closing curly.
}employee;
Or
typedef struct Record
{
char ename[30];
int ssn;
int deptno;
}employee;
In the second example, Record is tag-name. ‟employee‟ is nothing but New Data Type. We can
now create the variables of type ‟employee‟ Tag name is optional.
Declaring Variable :
employee e1,e2;
Example : Using Typedef For Declaring Structure
#include<stdio.h>
typedef struct b1 {
char bname[30];
int ssn;
int pages;
}book;
book b1 = {"Let Us C",1000,90};
int main()
{
printf("\nName of Book : %s",b1.bname);
printf("\nSSN of Book : %d",b1.ssn);
printf("\nPages in Book : %d",b1.pages);
return(0);
}
Output :
Name of Book : Let Us C
SSN of Book : 1000
Pages in Book : 90
Though there are three members of structure,only one is initialized , Then remaining two
members are initialized with Zero. If there are variables of other data type then their initial
values will be –
Integer 0
Float 0.00
Char NULL
int main()
{
printf("Name of the student : %s",s1.name);
printf("Roll Number : %d",s1.roll);
printf("Average : %f",s1.average);
return(0);
}
Output :
Name of the student : Pritesh
Roll Number : 67
Average : 78.3
Example :
struct student
{
char sname[20];
int roll;
float percent;
int marks[3]; //Note Carefully
}s1;
Access marks of Student s1 :
Access Subject 1 Marks : s1.marks[0]
Access Subject 2 Marks : s1.marks[1]
Access Subject 3 Marks : s1.marks[2]
Example :
#include <stdio.h>
struct student
{
char sname[20];
int marks[3]; //Note Carefully
}s1;
int main()
{
printf("\nEnter the Name of Student : ");
gets(s1.sname)
printf("\nEnter the Marks in Subject 1 : ");
scanf("%d",&s1.marks[0]);
printf("\nEnter the Marks in Subject 2 : ");
scanf("%d",&s1.marks[1]);
printf("\nEnter the Marks in Subject 3 : ");
scanf("%d",&s1.marks[2]);
Explanation :
Here student structure is used to Store the information of one student.
If we need to store the Information of 100 students then Array of Structure is used.
s[0] stores the Information of 1st student , s[1] stores the information of 2nd student
{
struct Book b1[3] = {
{"Anita", 123, 78.3},
{"Venkat", 124, 88.9},
{"Ganga:, 125, 90.2}
};
}
Example :
#include <stdio.h>
struct student
{
char name[20];
int roll;
float average;
}s[3];
int main()
{
int i;
for(i=0;i<3;i++)
{
printf("\nEnter the Name of Student : ");
scanf("%s",s[i].name);
printf("\nEnter the Roll Number : ");
scanf("%d",&s[i].roll);
printf("\nEnter the average : ");
scanf("%f",&s[i].average);
}
printf("\n--------- Student Details ------------ ");
for(i=0;i<3;i++)
{
{
int date;
int month;
int year;
};
struct Employee
{
char ename[20];
int ssn;
float salary;
struct date doj;
}emp1;
int date;
int month;
int year;
}doj;
}emp1;
Accessing Nested Members :
Accessing Month Field : emp1.doj.month
Accessing day Field : emp1.doj.day
Accessing year Field : emp1.doj.year
Complete Example :
#include <stdio.h>
struct Employee
{
char ename[20];
int ssn;
float salary;
struct date
{
int date;
int month;
int year;
}doj;
}emp = {"Pritesh",1000,1000.50,{22,6,1990}};
void main()
{
printf("\nEmployee Name : %s",emp.ename);
printf("\nEmployee SSN : %d",emp.ssn);
printf("\nEmployee Salary : %f",emp.salary);
printf("\nEmployee DOJ : %d/%d/%d", \
emp.doj.date,emp.doj.month,emp.doj.year);
}
Output :
Employee Name : Pritesh
Employee SSN : 1000
Employee Salary : 1000.500000
Employee DOJ : 22/6/1990
typedefstruct b1 {
char bname[30];
int ssn;
int pages;
}book;
book b1 = {"Let Us C","1000",90};
int main()
{
printf("\nSize of Structure : %d",sizeof(b1));
return(0);
}
Output :
Size of Structure : 26
Book Author :
Book Price : 0.000000
It is clear from above output , Default values for different data types.
Integer 0
Float 0.0000
Character Blank
Unions are Declared in the same way as a Structure.Only “struct Keyword” is replaced
with union
Union Members that compose a union, all share the same storage area within the computers
memory
Each member within a structure is assigned its own unique storage area
Unions are useful for application involving multiple members , where values need not be
assigned to all the members at any one time.
Syntax Explanation
Output :
ID : 10
Name : Pritesh
1 Structure allocates storage Union allocates one common storage space for all its
space for all its members members.
separately. Union finds that which of its member needs high storage
space over other members and allocates that much space
2 Structure occupies higher Union occupies lower memory space over structure.
memory space.
3 We can access all members of We can access only one member of union at a time.
structure at a time.
5 For above structure, memory For above union, only 8 bytes of memory will be allocated
allocation will be like below. since double data type will occupy maximum space of
int mark – 2B memory over other data types.
char name[6] – 6B Total memory allocation = 8 Bytes
double average – 8B
Total memory allocation =
2+6+8 = 16 Bytes
AUTOMATIC VARIABLES
A variable declared inside a function without any storage class specification, is by default
an automatic variable.
They are created when a function is called and are destroyed automatically when the function
exits. Automatic variables can also be called local variables because they are local to a
function.
By default they are assigned garbage value by the compiler.
void main()
{
int detail;
or
auto int detail; //Both are same
}
EXTERN KEYWORD
The extern keyword is used before a variable to inform the compiler that this variable is declared
somewhere else. The extern declaration does not allocate storage for variables.
Problem when extern is not used
main()
{
a = 10; //Error:cannot find variable a
printf("%d",a);
}
STATIC VARIABLES
A static variable tells the compiler to persist the variable until the end of program.
Instead of creating and destroying a variable every time when it comes into and goes out of
scope, static is initialized only once and remains into existence till the end of program.
A static variable can either be internal or external depending upon the place of declaration.
Scope of internal static variable remains inside the function in which it is defined. External
static variables remain restricted to scope of file in each they are declared.
They are assigned 0 (zero) as default value by the compiler.
void test(); //Function declaration (discussed in next topic)
main()
{
test();
test();
test();
}
void test()
{
static int a = 0; //Static variable
a = a+1;
printf("%d\t",a);
}
output :
1 2 3
Register variable
Register variable inform the compiler to store the variable in register instead of
memory. Register variable has faster access than normal variable.
Frequently used variables are kept in register. Only few variables can be placed inside
register.
NOTE : We can never get the address of such variables.
Syntax :
register int number;
1 Macro #define This macro defines constant value and can be any of the
basic data types.
2 Header file #include <file_name> The source code of the file “file_name” is included in
inclusion the main program at the specified place
3 Conditional #ifdef, #endif, #if, Set of commands are included or excluded in source
compilation #else, #ifndef program before compilation with respect to the
condition
4 Other directives #undef, #pragma #undef is used to undefine a defined macro variable.
#Pragma is used to call a function before and after main
function in a C program
This statement is placed before the main() function in source program. The pre-processor
replaces the every occurrence of an identifier by the specified string or integer in source
program.
Macros are generally declared with capital letters for quick identification. It can be declared
as small letters
Macro definition should not be terminated with a semicolon
There are three different types of macros.
1. Simple macros
2. Argumened macros
3. Nested macros
Simple macros:
This is commonly used to define symbolic constants
Example:
#define age 20
#define CITY “Chennai”
Program:
#define PI 3.14
void main()
{
float r, area;
printf(“enter the radius of the circle\n”);
scanf(“%f”,&r);
area=PI*r*r;
printf(“area of circle=%f\n”,area);
}
OUTPUT:
enter the radius of the circle: 7
area of circle=153.86
Nested macros:
The macros defined within another macro called nested macros
Example:
#include <stdio.h>
#define sq(n) (n*n)
#define cube(n) (n*sq(n))
main()
{
int a=5,b=3,s,c;
s=sq(a);
c=cube(b);
printf("square value of 5 is %d\n", s);
printf("Cube value of 3 is %d\n",c);
}
Output :
square value of 5 is 25
Cube value of 3 is 27
Result of the Expression is TRUE , then Block of Statement between #if and #endif is followed
Result of the Expression is FALSE , then Block of Statement between #if and #endif is skipped
#else statement :
These Conditional Compilation Directives allow us to include certain portion of the code
depending upon the output of constant expression
Example:
#include<stdio.h>
#define NUM 11
void main()
{
#if((NUM%2)==0)
printf("\nNumber is Even");
#else
printf("\nNumber is Odd");
#endif
}
Output :
Number is Odd
#elif statement :
These Conditional Compilation Directives allow us to include certain portion of the code
depending upon the output of constant expression
Syntax :
#if Expression1
Statement_block 1;
#elif Expression2
Statement_block 2;
#elif Expression3
Statement_block 3;
#else
Statement_block 4;
#endif
Expression allows only constant expression
#elif directive means “else if”
#elif establishes an if-else-if chain for multiple compilation options.
Result of the Expression is TRUE , then Block of Statement between #if and fist #elif is
compiled , then it jumps to #endif.
Result of the Expression is FALSE , then Corresponding #elif condition is tested , if true the the
block followed by that elif is Compiled otherwise it checks for Next condition followed by next
elif statement
#endif is the end of #if statement
Example :
#include<stdio.h>
#define NUM 10
void main()
{
#if(NUM == 0)
printf("\nNumber is Zero");
#elif(NUM > 0)
printf("\nNumber is Positive");
#else
printf("\nNumber is Negative");
#endif
}
Output :
Number is Positive
#ifdef statement :
These Conditional Compilation Directives allow us to include certain portion of the code
depending upon the output of constant expression
Syntax :
#ifdef MACRONAME
Statement_block;
#endif
If the MACRONAME specified after #ifdef is defined previously in #define
then statement_block is followed otherwise it is skipped.The conditional succeeds if MACRO is
defined, fails if it is not.
Example:
#include<stdio.h>
void main()
{
#ifdef MAX
#define MIN 90
#else
#define MIN 100
#endif
printf("MIN number : %d",MIN);
}
Output :
MIN number : 100
#include<stdio.h>
#define MAX 10
void main()
{
#ifdef MAX
#define MIN 90
#else
#define MIN 100
#endif
printf("MIN number : %d",MIN);
}
Output:
MIN number : 90
#ifndef statement :
#ifndef works exactly opposite to that of #ifdef. It tests whether the identifier has defined
substitute text or not. If the identifier is defined then #else block is compiled
Syntax :
#ifndef MACRONAME
Statement_block;
#endif
If the MACRONAME specified after #ifndef is not defined previously in #define then
statement_block is followed otherwise it is skipped, the conditional succeeds if MACRO is not
defined, fails if it is not.
Example:
#include<stdio.h>
#define MAX 90
void main()
{
#ifndef MAX
#define MIN 90
#else
#define MIN 100
#endif
printf("MIN number : %d",MIN);
}
Output :
MIN number : 100
#undef Directive
Removes (undefines) a name previously created with #define.
Syntax
#undef identifier
The #undef directive removes the current definition of identifier. subsequent occurrences
of identifier are ignored by the preprocessor.
To remove a macro definition using #undef, give only the macro identifier ; do not give a
parameter list.
You can also apply the #undef directive to an identifier that has no previous definition. This
ensures that the identifier is undefined.
The #undef directive also works with the #if directive to control conditional compilation of
the source program. In the following example, the #undef directive removes definitions of a
symbolic constant and a macro. Note that only the identifier of the macro is given.
#define WIDTH 80
#define ADD( X, Y ) ((X) + (Y))
.
.
.
#undef WIDTH
#undef ADD
PROGRAMS:
1. Write a C Program to Store Information of Single Student
#include <stdio.h>
struct student{
char name[50];
int roll;
float marks;
};
int main(){
struct student s;
printf("Enter information of students:\n\n");
printf("Enter name: ");
scanf("%s",s.name);
printf("Enter roll number: ");
scanf("%d",&s.roll);
printf("Enter marks: ");
scanf("%f",&s.marks);
printf("\nDisplaying Information\n");
printf("Name: %s\n",s.name);
printf("Roll: %d\n",s.roll);
printf("Marks: %.2f\n",s.marks);
return 0;
}
Output
Enter information of students:
Displaying Information
name: Adele
Roll: 21
Marks: 334.50
OUTPUT:
Enter number of students:5
Enter information of 5 students:
For roll number 1
Enter name: Veena
Enter marks: 90
Enter grade:A
For roll number 2
Enter name: Roopa
Enter marks: 95
Enter grade:A+
For roll number 3
Enter name: Pooja
Enter marks: 92
Enter grade:A
For roll number 4
Enter name: Lata
Enter marks: 96
Enter grade:A+
For roll number 5
Enter name: Aditi
Enter marks: 85
Enter grade:B
Displaying information of students:
Roll No Name Marks Grade
1 Veena 90 A
2 Roopa 95 A+
3 Pooja 92 A
4 Lata 96 A+
5 Aditi 85 B