Programming in C -Converted
Programming in C -Converted
.
* Programming in C
Mainframe computers:
Programming in C A mainframe computer supports a vast number of
users. It can process large amounts of data at very
high speeds. These computers are very large in size,
UNIT-1 and expensive.
Computer Fundamentals The main difference between a supercomputer and
a mainframe is that:
Introduction of Computers: A supercomputer can execute a single program
The term computer is derived from the Latin word faster than a mainframe. A Mainframe uses its
compute, which means to calculate. power to execute many programs concurrently.
Example: The IBM 370 and IBM 3090.
A Computer is an electronic device that processes
data and converts it into information that is useful Minicomputers
to people. A minicomputer can be used by multiple users
(between10 to 100). It is smaller in size. They are
A computer is a data processor. It can accept input less expensive. Minicomputers are used for
[data + instructions]. The computer stores the input in scientific and engineering tasks. They are also used
memory cells. It then processes the stored input. It as small servers.
gives out the result as output information. Example: The IBM AS/400.
Microcomputers:
The computer accepts input and outputs data in an The microcomputer can be used by a single user at
alphanumeric form. Internally it converts the input a time. It contains a microprocessor chip, a memory
data [English] to meaningful binary digits [Machine system, interface units and I/O units, etc.
Language], performs the given operations and There are many types of microcomputers:
transforms the data from binary format to English. Desktop computer: It is a microcomputer that can
fit on a desk.
Classification of Computers Laptop computer: It is a microcomputer that can fit
Based on their configuration, Computers can be on your lap.
classified into 4 types: Palmtop computer/PDAs: It is a hand-sized
1. Super Computers microcomputer. Its screen serves both as an input
2. Mainframe Computers and output device.
3. Mini Computers ****
4. Micro Computers Anatomy of a Computer
.
* Programming in C
Input Devices Printer The printer is a device that prints any data,
The devices, which are used to enter the data and report, document, etc. Printers can produce hard
instructions into the computer are known as the input copies of the data. They are of 2 types: An impact
devices. The most common input devices are: printer: It is a printer in which the print head will
be in physical contact with the paper. Example: Dot
Keyboard: A Keyboard is like a type-writer. matrix printer.
Normally it contains of 104 keys. Keyboard follows A non–impact printer: It is a printer in which the
QWERTY layout. It includes Character keys, print head does not have any physical contact with
Function keys, Control keys, Navigation keys, the paper. Example: Laser printer.
Toggle keys, miscellaneous keys, etc.
.
* Programming in C
.
* Programming in C
.
* Programming in C
Static RAM Dynamic RAM Secondary Memory
It does not require It requires‘‘refresheing’’ There are four main types of secondary storage
refreshing. devices:
It is more expensive It is less expensive • Disk drives
It is lower in bit It holds more bits of • CD drives (CD-R, CD-RW, and DVD)
density storage • Tape drives
It is faster than It is slower than SRAM. • USB flash drives
dynamic RAM.
Floppy Disk:
Cache Memory The floppy disk is a thin, round piece of plastic
It is a high-speed memory. It stores the data currently material, coated with a magnetic medium.
in use by the processor. It acts as a high speed buffer The floppy disk is enclosed by a plastic shell. Its
between CPU and main memory. It increases the size is 3½ inches and can store 1.44 MB of data.
processing speed. The cache memory is very
expensive and is limited in capacity. Hard Disk:
There are two levels of cache: A hard disk is a permanent memory device found
Level 1 (Primary) cache This type of cache memory inside the system unit. A hard disk consists of metal
is placed on the processor itself. This cache is very platters. Each platter is divided into tracks and
fast and its size varies generally from 8 KB to 64 KB. sectors. Read/write heads are used to read/write the
Level 2 (Secondary) cache It is slower than L1 cache. data. The storage capacity of a hard disk is very
It is usually 64 KB to 2 MB in size. Level 2 cache is large and expressed in terms of gigabytes (GB). It
also called external cache. stores the data permanently.
ROM CD’s
ROM stand for Read Only Memory. ROM is used in A CD is a portable secondary storage medium.
personal computers for storing start-up instructions. It Various types of CDs are available: CD-R and
is used for BIOS test or POST. ROMs can be written CD-RW. Once created Data stored on CD-R
only at the time of manufacture. (CDRecordable) disc can’t be changed. A
PROM: CDRewritable (CD-RW) disc can be erased and
A Programmable ROM (PROM), is also non-volatile reused. . CD-RW drives are used to create and read
and can be programmed only once. both CD-R and CD-RW discs.
EPROM: Erasable Programmable Read Only
Memories can be written electrically. Its data can be Tape drive
erased by using ultraviolet light. A tape drive is a data storage device that reads and
EEPROM: Electrically Erasable Programmable writes data on a magnetic tape. Magnetic tapes are
Read Only Memory (EEPROM can be written onto generally used for backup. Magnetic tapes are
by electrical signals. Its data can be erased by cheap but has a long stability.
electrical signals.
USB Flash drive:
It is a small, portable flash memory card. It can be
plugged into a computers USB port. It is easy to
carry and more durable. Because it cannot contain
any internal moving parts. It is also are called pen
drive.
.
* Programming in C
Operating System
An operating system is a system software that acts as
an intermediary between the user and the Hardware.
Mac, MS Windows, Linux, Solaris, Android etc are
some of the operating systems.
▪ Process(or) management
A process is a program in execution. The operating
system decides which process to run. It also assigns
priority to the processes.
.
* Programming in C
***
.
* Programming in C
3. Problem-oriented languages:
These languages provide pre-programmed
functions. The user need to write those
functions. MATLAB is an example of this
1. Procedural programming languages: category. MATLAB is very popular
In procedural programming, each program can be language among scientists and engineers.
divided into small procedures (subroutines or
functions). This style is easier for programmers. ***
There are mainly three types: Translator, Loader, Linker
• Algorithmic languages: In this style, the
programmer must specify the steps, which the • A Translator is a program that translates
computer has to follow. It uses top-down the source program into machine
approach. Languages like C, COBOL, understandable form.
PASCAL and FORTRAN fall into this • A Linker is a program that combines the
category. machine language program with other
[Top-down approach: It is a technique of programs in the library.
programming that first defines the overall outlines of • A Loader is a program that loads the
the program and then fills in the details.] executable program’s from secondary
memory into primary memory and prepares
• Object Oriented languages: Object-oriented them for execution and starts the execution.
programming depends on software objects.
Data and associated operations are combined ***
into objects. This approach provides reuse of
code and design. C++, JAVA, SMALLTALK,
etc. are some examples of object-oriented
languages
.
* Programming in C
Compilers – Interpreters 1. Lexical analysis:
In this phase, the source program is scanned
There are two ways to translate a program from high for lexical units (identifiers, operators, etc.).
level language into the machine language. They are: It creates a table called symbol table. The
COMPILING and INTERPRETING. Symbol Table is used to record information
about the user-defined names in the program.
Compiling: When you compile a program, the entire
program is translated into machine language before 2. Syntax analysis: In this phase, tokens are
it is executed. combined into expressions or statements.
• A COMPILER is a translator program that This process is known as parsing. This
performs Compilation. parsing process can produce a Parse Tree.
Syntax rules can be described by using a
• C and C++ languages uses Compilers for their technique called as BNF (Backus Naur
translation. Form) grammar.
Differences:
1. A Compiler takes the entire program as its
input. 3. Semantic analysis: The semantic analysis
2. An Interpreter takes Instruction by instruction phase further analyses the parsed
as its input. statements.
3. A Compiler generates Object Code
4. An Interpreter does not generate any object 4. Intermediate code generation and
code. optimization: Many compilers produce an
5. A Compiler requires more memory intermediate form of code for optimization.
6. An Interpreter requires less memory. The intermediate code may be is in
assembly language.
***
Compiling, Linking and Loading a Program 5. Code generation: This is the final phase
that converts the intermediate code into
A Compiler translates a program written in a source target machine code. It also performs
language into target language. The compilation linking and loading step to generate an
process can be divided into the following phases: executable program.
1. Lexical Analysis
2. Syntax Analysis ***
3. Semantic Analysis
4. Intermediate code generation
5. Code Generation
.
* Programming in C
Software Development
Developing a Program
Software development is more than programming.
There are seven important steps in developing a
It involves a large number of people. Programming
program:
is one of the activities in software development. A
1. Definition
software is built according to client’s requirements.
2. Design
It is driven by cost, schedule and quality. That is,
3. Coding
software should be developed at reasonable cost,
4. Testing
handed over in reasonable time.
5. Documentation
6. Implementation
Software development involves the following
7. Maintenance.
steps:
1. Definition: This is the first step in developing
1. Feasibility study:
a program. The definition must include the
Feasibility study is an assessment of the proposed
needed output, the available input, and etc.
project. It verifies the feasibility of the software
2. Design: This is the second step in developing development. Feasibility study is of three types:
a program. It should design the problem • Economic feasibility
solution (algorithm). • Technical feasibility
• Operational feasibility
3. Coding: This is the third step in developing a
program. It writes the program instructions in Economic feasibility: It verifies whether the
a programing language. The instructions must development of new software will be financially
follow the syntax. beneficial or not.
4. Testing: This is the fourth step in developing Technical feasibility: It verifies various factors
a problem. It tests the program for the errors. such as the performance of the technologies, their
Errors in a program are called bugs. The interoperability with other technologies, etc.
process of finding the bugs and correcting
them is called Debugging. Operational feasibility: It verifies the (a) Type of
5. Documentation: This is the fifth step in tools needed (b) Skills required (c) Documentation
developing a program. It completes the d) other support required for operating the software.
documentation of the program.
Documentation is extremely important. 2. Requirement analysis:
Documentation should contain user In this phase, the requirements related to the
instructions, an explanation of the logic of the software are understood. This is an important step
program, and expected I/O. in developing software. If the requirements of the
user are not properly understood, then the
6. Implementation: This is the sixth step in developing software becomes a failure.
developing a program. After completing the
program, it needs to be installed on a 3. Design:
computer. The Design phase creates the architecture and
7. Maintenance: A completed program requires design of the new software. It has two stages:
attention. It needs to be maintained and • System design
evaluated for possible changes. • Detailed software design.
***
.
* Programming in C
• System design: It designs the overall system
architecture. It prepares an abstract
representation of that system.
5. Testing:
The Testing phase detects errors in the new software
and rectify those errors. The testing phase performs
verification and validation.
• Verification is the process of checking the
software based on some specifications.
• Validation involves testing the product to
verify whether it meets the user requirements.
6. Deployment:
The newly developed software need to be installed in
its target environment. It hand overs the software
documentation to the users. It also gives training to
the users.
7. Maintenance:
In this phase, developed software becomes
operational. It requires a continuous support.
***
.
* Programming in C
Algorithms Pseudo-code
To solve any problem a plan is needed. An algorithm • It is a written form representation of the
is a part of the plan for the computer program. algorithm.
What is an Algorithm? • It is in the human language.
Computer scientist Niklaus Wirth stated that: • It uses a limited vocabulary to define its
Program = Algorithms + Data.
actions.
Example:
An algorithm is ‘an effective procedure for solving a
If student's grade is greater than or equal to 60
problem in a finite number of steps’.
Print "passed"
“Effective” means that an answer is found and it has else
a finite number of steps. A well-designed algorithm Print "failed"
should give an answer and also it must be terminated.
Endif
Definition:
An Algorithm is a finite set of instructions for Flowchart and Nassi-Schneiderman
solving a problem. • These are a graphical representation of the
algorithm.
Different Ways of Stating Algorithms: • They use symbols and language to
Algorithms can be represented in four ways: represent sequence, decision, and
1. Step-form repetition actions.
2. Pseudo-code Example:
3. Flowchart Draw a flowchart to find largest of three
4. Nassi-Schneiderman numbers?
Step-form representation: Solution:
• The step-form uses normal language.
• It states the algorithm with written
statements.
• Every statement is logically related to the
preceding statement.
• Each statement solves a part of the problem
and all the statements together complete the
solution.
Example:
Write an algorithm for finding the sum of any two
numbers.
Step 1. START
Step 2. PRINT “ENTER TWO NUMBERS”
Step 3. INPUT A, B ***
Step 4. C A + B
Step 5. PRINT C
Step 6. STOP
.
* Programming in C
Strategy for Designing Algorithms Spaghetti code
The strategy for designing algorithms involves 3 A Non-modular code is known as Spaghetti code.
steps: It produces a disorganized computer program. It
1. Investigation step may also contain many GOTO statements in it.
2. Top-Down development step That makes the program more complex.
3. Step-wise refinement ***
Structured programming
Investigation step:
The investigation phase determines the requirements Structured programming is a style of programming
for the problem solution. Here you need to: that includes the following characteristics:
I. Identify the outputs. 1. Block structure:
II. Identify the input variables. The statements in the program must be organized
III. Identify the decisions and conditions. into functional groups.
IV. Identify the processes. 2. Avoidance of jumps:
V. Identify the environment. A lot of GOTO statements makes the programs
more error-prone. Structured programming uses
Top–down development: less number of goto statements. Therefore it is also
It plans the solution by breaking it into smaller known as ‘GOTO less programming’.
modules. 3. Modularity: Structuring the program makes it
• Devise the overall problem solution: Divide easier to understand.
the problem solution into small modules.
• Verify the feasibility of solution: Check that Advantages of structured programming:
the modules together form the whole solution
to the Problem. • Structured programming can develop well-
organized codes.
Stepwise refinement:
• Many developers can work simultaneously
It further decomposes the modules, defines the
on the same program.
procedures and also verifies their correctness.
• It reduces complexity.
• Work out all the details for each module.
• It also saves time
• Decompose any module into further
• It encourages stepwise refinement.
meaningful smaller pieces.
• Group common processes together Disadvantages of structured programming:
• Group common variables together. • Error control may be harder to manage.
• Test each small procedure for its correctness • Managing modifications may also be
difficult.
Example:
• Debugging efforts can be delayed.
Write an algorithm for finding the sum of any two
numbers.
Solution:
***
Let the two numbers be A and B and let their sum be
equal to C. Then, the desired algorithm is given as
follows:
Step 1. START
Step 2. PRINT “ENTER TWO NUMBERS”
Step 3. INPUT A, B
Step 4. C A + B
Step 5. PRINT C
Step 6. STOP ***
ABVG Degree College,Jangaon 14
.
* Programming in C
Developing programs in C
There are mainly three steps in developing a program
in C:
1. Writing the C program
2. Compiling the program
3. Executing the program
***
Header files
A header file is a file that has C declarations and
macro definitions. It provides the required
information for the pre-processor and compiler to Preprocessor directives:
process the program. In C all the lines that begin with # are known as pre-
The ISO C contains the following header files: processor directives. A Pre-Processor is a program
assert.h signal.h errno.h stddef.h that processes the directives before the compilation
complex.h stdarg.h fenv.h stdint.h process.
ctype.h stdbool.h float.h stdio.h Global declarations:
inttypes.h stdlib.h locale.h time.h The global declaration contain the global variables.
iso646.h string.h math.h wchar.h The variables that are available for all the functions
limits.h tgmath.h setjmp.h wctype.h in the program are known as global variables.
There are two ways of including files in C program: Main program section:
1. #include<filename> All the functions in a c program can be divided
This method tells the preprocessor to look for into two sections:
the file in the default location. This method is ▪ Local definition
used to include standard headers such as ▪ Statements.
stdio.h or stdlib.h. Local definitions:
2. #include “file name” Local definitions are at the beginning of the
This method tells the preprocessor to look for functions. Local definitions are available within
the file in the current directory first, then that function only.
in the predefined locations. This method is Statements:
used to include programmer created files. Statement section consists of the executable
instructions.
***
***
Unit – II getchar(): -
The getchar() is a non-formatted Input function. It
Input-Output can read a single character at a time. It has the
following format:
Input-Output: char_variable = getchar();
Generally, The keyboard and the screen are the Example:
standard input and output devices in programming. int ch;
All input and output is performed with streams. A ch = getchar();
Stream is a sequences of bytes. In input operations, The getchar()function reads a character and places
the bytes flow from keyboard to main memory. In it in the memory location “ch”
output operations, bytes flow from main memory to
screen. putchar():-
The putchar() is a non-formatted output function. It
In C, the input and output are managed through can displays a single character at a time on the
standard streams. Those standard streams are: monitor screen. It has the following format:
1. stdin : Standard Input Stream putchar(char_variable);
2. stdout : Standard Output Stream Example:
int ch = ‘x’;
3. stderr : Standard Error Stream
puchar(ch)’
When a program execution begins, these three
The putchar() function displays the character stored
streams are connected to the program automatically.
in the memory location “ch”.
Normally, the standard input stream is connected to
the keyboard and the standard output stream is
1. Write a C program to display a keyed in
connected to the screen. A third stream, the standard
character.
error stream, is connected to the screen.
Solution
#include<stdio.h>
I/O Functions in C
main()
C has a number of standard functions to perform input
{
and output operations.
int ch;
In C, The input/output (I/O) functions are of two
ch=getchar();
types:
putchar(ch);
1. Non-formatted input/output functions
return 0;
2. Formatted input/output functions. }
Non-formatted input/output functions : I/O
The I/O statements that does not use format codes Input A
are known as Non-Formatted I/O functions. Output A
These functions can handle one character at a
time. There are two important non-formatted I/O
functions in C:
1. getchar()
2. putchar()
Escape sequences
Escape sequences are the control codes that can be
used to control the output as required. C has the
following escape sequence characters:
Code Meaning
Code Meaning
\a Ring bell (a is for alert) Selection Statements
\? Question mark Selection statements are of three types:
\b Backspace • One-way Selection Statements→ These
\r Carriage return statements can do a particular thing or they
\f Form feed do not do anything. In C a simple if
\t Horizontal tab \ statement can do this.
\v Vertical tab • Two-way Selection Statements→ These
\0 ASCII null character statements can do one thing or another
\\ Backslash thing. In C an if..else statement can do this.
\” Double quote • Multi-way Selection Statements→ These
\’ Single quote
statements can do one of many different
\n New line
things. In C an else..if ladder/nested if
\o Octal constant
statements can do this.
\x Hexadecimal constant
Write a program to find the largest among three Write a C program to check whether a number
numbers. given by the user is odd or even.
#include <stdio.h> #include <stdio.h>
main() int main()
{ {
int a, b, c, max; int n,r;
printf(“\nEnter 3 numbers”); printf(“\nEnter the number”);
scanf(“%d %d %d”, &a, &b, &c); scanf(“%d”, &n);
max=a; r=n%2;
if(b>max) if(r==0)
max=b; printf(“EVEN”);
if(c>max) else
max=c; printf(“ODD”);
printf(“Largest No is %d”, max); return 0;
getche(); }
return 0;
}
}
getche();
return 0;
}
***
→Bounded loops can be used when you know how While loop
many times you need to loop. C provides one while statement is a pre-test loop. First, it verifies
bounded loop: for loop. the test expression before every iteration of the
loop.
→Unbounded loops can be used when you does not It has the following syntax:
know how many times to loop. C provides two types
of unbounded loops: while loop and do...while loop. Initialization;
while (TestExpr)
A loop can be either a {
• pre-test loop or stmT
• post-test loop. ...
→In a pre-test loop, first, the condition is checked. If ...
the test condition is true, then only it executes the Updating
statements of that loop. }
This process is repeated till the test expression
becomes false. In a pre-test loop, the statements may stmT will be executed repeatedly till the value of
not be executed even once. TestExpr becomes 0 (FALSE).
The following figure shows the execution of
→In the post-test loop, first the code is always “while” loop:
executed once. The test condition is tested at the end
of the loop. If the test condition is true, the loop
repeats. if it is false the loop terminates.
if(isspace(ch))
words++;
chars++;
}
printf("\nNumber of Lines : %d", lines+1);
printf("\nNumber of Words: %d", words+1);
printf("\nTotal Number of Characters: %d", chars);
getch( );
return 0; Statements
} Block
I/O
Enter the required no. of lines:
This is a Test
This is a Test
This is a Test ^Z
Number of Lines : 3
Number of Words : 12
Number of Characters: 44
I/O:
Enter the number of terms: 5
Sum is 15
Example:
Write a C program to print the numbers from 1 to 3.Write a C program to calculate the factorial of
10. the given number.
#include<stdio.h>
#include<stdio.h> #include<conio.h>
#include<conio.h> main()
main() {
{ int n, i, f=1;
int i; printf(“\n Enter the number: ”);
clrscr(); scanf(“%d”,&n);
for(i = 1; i <= 10; i++) for(i=1;i<=n;++i)
printf(“%d”,i); f*=i;
return 0’ printf(“\n Factorial is %ld”,f);
} getche();
return 0;
I/O }
1
2 I/O:
3 Enter the number: 5
4 Factorial is 120
5
6
7
8
9
10
2. return statement:
The return type is used in a function definition to set
its returne value.
The return statement has two forms.
(1) return;
This format can be used for the functions
which return a blank control without value.
(2) return expression;
This format can be used for the functions which
return a particular value.
Write a C program to search for an element in the Write a C program to sort the array elements
array. using bubble sort.
#include <stdio.h>
#include <stdio.h> #include<conio.h>
#include<conio.h> #include <stdlib.h>
#include <stdlib.h> main()
main() {
{ int a[30],n,i,j,temp;
int a[30],n,i,key, FOUND=0; clrscr();
clrscr(); printf(“\n How many numbers”);
printf(“\n How many numbers”); scanf(“%d”,&n);
scanf(“%d”, &n); if(n>30)
} Example:
} arr [0][0] = 1;
printf(“\n The numbers in sorted order \n”); arr [0][1] = 2;
for(i=0 ; i<n; ++i) arr [0][2] = 3;
printf(“\n %d”, a[i]); arr [1][0] =4;
getche(); arr [1][1] = 5;
return 0; arr[1][2] = 6;
} arr [2][0] = 7;
arr [2][1] = 8;
Multidimensional Arrays arr[2][2] = 9;
Strings
printf("\n Matrix a is:\n");
One-dimensional Character Arrays
for(i = 0; i < row1; i++)
→A String is an arrays of characters.
{
In C, a String can be terminated by a null
for(j = 0; j < col1; j++)
character(\0).
printf("%3d", a[i][j]);
printf("\n");
Declaraing a String
}
Strings can be declared like one-dimensional
arrays. For example:
printf("\n Matrix b is: \n");
char name[30];
for(i = 0; i < row2; i++)
char address[80];
{
for(j = 0; j < col2; j++)
String Initialization
printf("%3d", b[i][j]);
Strings allow a shorthand initialization, for
printf("\n");
example,
}
char str[9] = “I like C”;
char msg[] = “Hello”;
if(col1 == row2)
{ Printing Strings
printf("\n Multiplication is possible and the Result is The format code ‘%s’ can be used to print strings
as follows \n"); by using printf(). For For example,
for(i=0; i<row1; i++) printf(“%s”,name);
for(j=0; j<col2; j++)
{ Reading a String
m[i][j] = 0; The format code %s can be used to read a string
for(k = 0; k < col1; k++) with scanf().
m[i][j] += a[i][k] * b[k][j]; For example:
} scanf("%s', &name);
Write a C Program to illustrate Strings:
for(i = 0; i < row1; i++) #include<stdio.h>
{ main()
for(j = 0; j < col2; j++) {
printf("%3d", m[i][j]); char str[50];
printf("\n"); printf(“Enter a string”);
} scanf(“%s”,str);
} printf(“The string was :%s\n”,str);
return 0;
else }
printf("\n Multiplication is not possible");
getche(); I/O:
return 0; (a) Enter a string: Ritchie
} The string was :Ritchie
***
USING FUNCTIONS
You can use a function by calling it. A function
which calls another function is known as a Calling
Function. A function which responds to a function
call is known as a Called function.
/* Declaring a Pointer:
output The syntax for declaring a pointer variable is
=========== datatype * pointer_variable;
Enter a Number : 4
Factorial of 4 is = 24 Example:
*/ char *ptr;
Initializing and Assigning Values to Pointers
Pointers A pointer may be initialized to an address or NULL,
A pointer is a special type of variable that can hold or 0.
the memory address of another variable.
Example:
#include <stdio.h>
int swap(int*, int*);
int main()
{
int x=5,y=10; For example:
void swap(int *,int *); #include<stdio.h>
printf(“%d %d\n”,x,y); main()
swap(&x, &y); {
printf(“%d %d\n”,x,y); int a[]={1,2,3,4,5};
return 0; int b[]={10,20,30,40,50};
} int c[]={100,200,300,400,500};
int *p[3];
int i,j;
p[0]=a;
p[1]=b;
p[2]=c;
***
Structures S2.sno=201;
A structure is a collection of variables under a single S2.sname=”Bobbage”;
name. These variables can be of different types S2.marks=654;
printf("\n sno \t name \t s1 \t s2 \t s3 \t total \t avg The members of a union can be accessed by using
:\n"); the ‘.’ the ‘dot operator’. It has the following form:
for(i=0;i<10;i++) < union_variable >.< member_name > ;
{
printf("\n%d \t %s \t %d \t %d \t %d \t %d \t%f Example:
\n", student1[i].sno, student1[i].sname, student1[i]. e1.eno=101;
s1, student1[i].s2, student1[i].s3, student1[i].total, e1.ename=”Ritchie”;
student1[i].avg); e1.salary=25000;
A union can be declared by using the keyword printf("\n\t Employee Number = %d", e1.eno);
"union". printf("Enter Employee Name:");
scanf("%s",e1.ename);
Declaring a Union and its Members: printf("\n\t Employee Name = %s", e1.ename);
The general format for declaring a union is :
union tag_name printf("Enter Employee Salary:");
{ scanf("%f",e1.salary);
data type member1;
data typemember2; printf("\n\t Employee Salary = %f", e1.salary);
.
. getche();
data type memberN; return 0;
}variable1,variable2,variable3,…,variableX; }
Example:
union emp
{
int eno;
char ename[10];
float salary;
} e1;