0% found this document useful (0 votes)
20 views41 pages

First Year C Question Bank With Solution

Uploaded by

methescavenger
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views41 pages

First Year C Question Bank With Solution

Uploaded by

methescavenger
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

UNIT-1

Q1. What is algorithm? Write down the general characteristics of an algorithm and write an
algorithm to print the digits of a number in reverse order.
Ans. Algorithm: An algorithm is a sequence of finite instructions, often used for calculation and data
processing.
An algorithm is a step-by-step method of solving a problem.
An algorithm is a set of instructions designed to perform a specific task.
Characteristics of the algorithm:
1) Finiteness: - an algorithm terminates after a finite number of steps.
2) Definiteness: - each step-in algorithm is unambiguous. This means that the action specified by the step
cannot be interpreted (explain the meaning of) in multiple ways & can be performed without any
confusion.
3) Input: - an algorithm accepts zero or more inputs
4) Output:- it produces at least one output.
5) Effectiveness: - it consists of basic instructions that are realizable. This means that the instructions can
be performed by using the given inputs in a finite amount of time.
Algorithm to print the digits of a number in reverse order:
Digitsreverse(num)
1. Start.
2. Please enter number.
3. Read num.
4. While (num>0) repeat steps 5,6 and 7 otherwise go to step 8.
5. Do digit =num%10
6. Print digit;
7. Do num= num/10
8. Stop
Q2. What do you understand by flow chart? Draw a flow chart to find maximum of three numbers.
Ans-
Flow chart:
It is a very important tool for developing algorithm and program.
It is pictorial representation of step by step solution of a problem. Programmer often uses it as a program
planning tool for visually organizing step necessary to solve a problem.
It uses boxes of different shapes that denote different type of instruction.
While making a flow chart a programmer needs not to pay attention to the elements of the programming
language, he has to pay attention to the logic of solution to the problem
Q3. Define computer. Explain anatomy of computer in detail.
Ans- Computer: Computer is an electronics device that can perform various arithmetic and logical
operations. It can receive data, process it and produce output. It can store large amount of data.

A computer system consists of mainly four basic units; namely input unit, storage unit, central
processing unit and output unit. Central Processing unit further includes Arithmetic logic unit and
control unit, as shown in the figure:
Input Unit: This unit is used for entering data and programs into the computer system by the user for
processing. Input devices are,Keyboard, Mouse, Trackball, Touchpad, Light Pen, Magnetic ink character
recognition (MICR), Optical mark recognition (OMR), Bar code reader.
Memory Unit: The storage unit is used for storing data and instructions before and after processing.
Computer’s memory can be classified into two types; primary memory and secondary memory.
Primary Memory can be further classified as RAM and ROM.
RAM or Random Access Memory is the unit in a computer system. It is the place in a computer where the
operating system, application programs and the data in current use are kept temporarily so that they can
be accessed by the computer’s processor. It is said to be ‘volatile’ since its contents are accessible only as
long as the computer is on. The contents of RAM are no more available once the computer is turned off.
ROM or Read Only Memory is a special type of memory which can only be read and contents of which
are not lost even when the computer is switched off. It typically contains manufacturer’s instructions.
Among other things, ROM also stores an initial program called the ‘bootstrap loader’ whose function is to
start the operation of computer system once the power is turned on.
Secondary Memory
RAM is volatile memory having a limited storage capacity. Secondary/auxiliary memory is storage other
than the RAM. These include devices that are peripheral and are connected and controlled by the
computer to enable permanent storage of programs and data.
Secondary storage devices are of two types; magnetic and optical. Magnetic devices include hard disks
and optical storage devices are CDs, DVDs, Pen drive, Zip drive etc.
Output Unit: The output unit is used for storing the result as output produced by the computer after
processing. Output devices are monitor, printer etc.
CPU: The Central Processing Unit (CPU) takes data and instructions from the storage unit and makes all
sorts of calculations based on the instructions given and the type of data provided. It is then sent back to
the storage unit. CPU includes Arithmetic logic unit (ALU) and control unit (CU)
• Arithmetic Logic Unit: All calculations and comparisons, based on the instructions provided, are
carried out within the ALU. It performs arithmetic functions like addition, subtraction, multiplication,
division and also logical operations like greater than, less than and equal to etc.
• Control Unit: Controlling of all operations like input, processing and output are performed by control
unit. It takes care of step by step processing of all operations inside the computer.
Q4. What do you mean by operating system? Explain various functions of operating system.
Operating System:
It is a software program that acts as an interface between the user and the computer. It is a software
package which allows the computer to function.
It is a program that controls the execution of application programs.
It is an interface between applications and hardware.
Functions:
1. Program creation
2. Program execution
3. Access to Input/Output devices
4. Controlled access to files
5. System access
6. Error detection and response
7. Interpreting the commands
8. Managing peripherals
9. Memory management
10. Processor management
11. Information management
12. Process communication
Q5. What is a computer? Explain classification of computer in detail.
Ans-- Computer: Computer is an electronics device that can perform various arithmetic and logical
operations. It can receive data, process it and produce output. It can store large amounts of data.
Classification of Computer:

Computers differ based on their data processing abilities. They are classified according to purpose, data
handling and functionality.

According to purpose, computers are either general purpose or specific purpose.

Geneal purpose computers are designed to perform a range of tasks. They have the ability to store
numerous programs, but lack in speed and efficiency.

Specific purpose computers are designed to handle a specific problem or to perform a specific task. A set
of instructions is built into the machine.
According to data handling, computers are analog, digital or hybrid.
Analog Computer
An analog computer (spelt analogue in British English) is a form of computer that uses
continuous physical phenomena such as electrical, mechanical, or hydraulic quantities to model the
problem being solved
Digital Computer
A computer that performs calculations and logical operations with quantities represented as digits,
usually in the binary number system
Hybrid Computer (Analog + Digital)
A combination of computers that are capable of inputting and outputting in both digital and analog
signals. A hybrid computer system setup offers a cost-effective method of performing complex
simulations.
On the basis of Size
Supercomputer
The fastest and most powerful type of computer Supercomputers are very expensive and are employed for
specialized applications that require immense amounts of mathematical calculations. For example,
weather forecasting requires a supercomputer. Other uses of supercomputers include animated graphics,
fluid dynamic calculations, nuclear energy research, and petroleum exploration.
The chief difference between a supercomputer and a mainframe is that a supercomputer channels all its
power into executing a few programs as fast as possible, whereas a mainframe uses its power to execute
many programs concurrently.
Mainframe Computer
A very large and expensive computer capable of supporting hundreds, or even thousands, of users
simultaneously. In the hierarchy that starts with a simple microprocessor (in watches, for example) at the
bottom and moves to supercomputers at the top, mainframes are just below supercomputers. In some
ways, mainframes are more powerful than supercomputers because they support more simultaneous
programs. But supercomputers can execute a single program faster than a mainframe.
Mini-computer
It is a midsized computer. In size and power, minicomputers lie between workstations and mainframes. In
the past decade, the distinction between large minicomputers and small mainframes has blurred, however,
as has the distinction between small minicomputers and workstations. But in general, a minicomputer is a
multiprocessing system capable of supporting from 4 to about 200 users simultaneously.
Micro Computer or Personal Computer
Desktop Computer: a personal or micro-mini-computer sufficient to fit on a desk.
• Laptop Computer: a portable computer complete with an integrated screen and keyboard.
It is generally smaller in size than a desktop computer and larger than a notebook computer.
• Palmtop Computer/Digital Diary /Notebook /PDAs: a hand-sized computer. Palmtops have
no keyboard, but the screen serves both as an input and output device.
Workstations
It is a terminal or desktop computer in a network. In this context, workstation is just a generic term for a
user's machine (client machine) in contrast to a "server" or "mainframe."
Q6. What do you mean by translator? Differentiate compiler and interpreter.
Ans- A translator is a computer program that performs the translation of a program written in a given
programming language into a functionally equivalent program in a different computer language, without
losing the functional or logical structure of the original.
Examples of widely used types of computer languages translators include interpreters, compilers, and
assemblers.
Difference between Compiler and Interpreter
No Compiler Interpreter
1 Compiler Takes Entire program as input Interpreter Takes Single instruction as input .
2 Intermediate Object Code is Generated No Intermediate Object Code is Generated
Conditional Control Statements are Executes Conditional Control Statements are Executes
3
faster slower
Memory Requirement : More (Since Object
4 Memory Requirement is Less
Code is Generated)
Every time higher level program is converted into
5 Program need not be compiled every time
lower level program
Errors are displayed after entire program is Errors are displayed for every instruction
6
checked interpreted (if any)
7 Example : C Compiler Example : BASIC

Q7. Explain assembler, linker and loader in detail.


Assembler: A program which translates an assembly language program into a machine language program
is called an assembler. If an assembler runs on a computer and produces the machine codes for the same
computer then it is called self-assembler. If an assembler that runs on a computer and produces the
machine codes for other computer then it is called Cross Assembler.
Linker: In high level languages, some built-in header files or libraries are stored. These libraries are
predefined, and these contain basic functions which are essential for executing the program. These
functions are linked to the libraries by a program called Linker. If a linker does not find a library of a
function, then it informs to compiler and then compiler generates an error. The compiler automatically
invokes the linker as the last step in compiling a program.
Not built in libraries, it also links the user defined functions to the user defined libraries. Usually, a longer
program is divided into smaller subprograms called modules. And these modules must be combined to
execute the program. The process of combining the modules is done by the linker.
Linker creates exe file.
Loader: Loader is a program that loads machine codes of a program into the system memory.
In Computing, a loader is the part of an Operating System that is responsible for loading programs. It is
one of the essential stages in the process of starting a program. Because it places programs into memory
and prepares them for execution. Loading a program involves reading the contents of executable file into
memory. Once loading is complete, the operating system starts the program by passing control to the
loaded program code.

Q8. Differentiate the following:


1. Hardware and software
2. Application and system software

Ans-

Basics Hardware Software


Software is a collection of
Devices that are required to
program that enables a
Definition store and execute (or run) the
computer to perform a specific
software.
task
System software,
Input, storage, processing,
Types Programming software, and
control, and output devices.
Application software.
Software does not wear out
Durability Hardware wears out over time.
over time.
Hardware is physical in
Nature Software is logical in nature.
nature.
QuickBooks, Adobe Acrobat,
CD-ROM, monitor, printer,
Examples Google Chrome, Microsoft
video card, scanners
Word, Microsoft Excel

Graphical User interface permits a


Command line interface enables a
user to interact with the system by
Basic user to communicate with the
using graphics which includes
system through commands.
images, icons, etc.

Device used Keyboard Mouse and keyboard

Hard to perform an operation and Easy to perform tasks and does


Ease of Use
require expertise. not require expertise.

Memory Low Consumption High Consumption

Custom changes can be


Appearance Can't be changed
employed

Speed Fast Slow

BASIS SYSTEM SOFTWARE APPLICATION SOFTWARE

System Software manages


Application Software, when
system resources and provides a
Basic run, perform specific tasks,
platform for application
they are designed for.
software to run.
System Software is written in a Application Software is written
Language low-level language, i.e. assembly in a high-level language like
language. Java, C++, .net, VB, etc.
System Software starts running
when the system is turned on, Application Software runs as
Run
and runs till the system is shut and when the user requests.
down.
System Software is general- Application Software is specific-
Purpose
purpose. purpose.
Microsoft Office, Photoshop,
Examples Operating system.
Animation Software, etc.

Q9. Explain various symbols used in flowchart.


Ans:

Symbol Symbol Name Purpose

Used at the beginning and end of the algorithm


Start/Stop
to show start and end of the program.

Indicates processes like mathematical


Process
operations.

Input/ Output Used for denoting program inputs and outputs.

Stands for decision statements in a program,


Decision
where answer is usually Yes or No.

Connector use to connect the flow of two more flow charts

Arrow It shows relationships between different shapes.


UNIT-2
Q1. What is programming language? Differentiate high level and low-level language.
Ans-
Languages are a means of communication. Communication with computers is carried out through a
language. This language is understood both by users and the machine. Every computer language is bound
by rules known as SYNTAX of that language. The user is bound by that syntax while communicating
with the computer system.

Difference between high level and low-level language:


Sr. No. High level language Low level language
1. In high level code instructions use words. In low level code instructions are in binary
code(0,1) and mnemonics.
2. High-level code is designed to be read by low level code is to be read/executed by the
human programmers. computer.
3. High level code can be portable/translated low level code is specific to a particular
for different machines. machine so not portable.
4. System knowledge not required. System knowledge required.
5. Less error prone. More errors are prone.
6. Execution slow. Execution fast.
Less memory efficient More memory efficient.
7. Translator required. Translator not required in machine code.
(compiler or interpreter) Assembler required for low level code.
8. C , c ++ ,JAVA Machine, assembly

Q2. Define C tokens in detail.


Ans: C tokens are fundamental units used in C language. C tokens are keyword, identifier, operators,
special symbols, constant and string.
Keywords are also known as reserved words whose meaning is already defined in C library, they all
perform some specific purpose. There are mainly 32 keywords: int, char, float, double if , else, break,
continue ,case, void etc.
Identifier: Each program elements in a C program are given a name called identifiers.
Names given to identify Variables, functions and arrays are examples for identifiers.
• Variable: C variable is a named location in a memory where a program can manipulate the data.
This location is used to hold the value of the variable.
• The value of the C variable may change in the program.
• C variable might belong to any of the data type like int, float, char etc.
Rules for naming variable(same rule for all identifier)
• A variable name is any combination of alphabets digits or underscore
• The first character must be always alphabet or underscore
• No comma or blank space is allowed within variable name
• Only underscore is allowed in special symbols
• Examples are ac ,_cc ,c_a
Constant: It is named location in a memory where entity or value that does not change during the
execution of programs.
const key word is used to make constant.
Exp: const int a=10; const float b=2.5;
Type of constant:

Rules for integer constant:


• An integer constant must have at least one digit.
• It must not have a decimal point.
• It can either be positive or negative.
• No commas or blanks are allowed within an integer constant.
• If no sign precedes an integer constant, it is assumed to be positive.
• The allowable range for integer constants is -32768 to 32767.
Example:
5,-7,555 etc

Rule for real constants:


• A real constant must have at least one digit
• It must have a decimal point
• It could be either positive or negative
• If no sign precedes an integer constant, it is assumed to be positive.
• No commas or blanks are allowed within a real constant.
Floating point constants are the numeric constants that has either fractional form or exponent
form. For example:
• -2.0
• 0.0000234
• -0.22e-5
• Note:Here, E-5 represents 10 -5 . Thus, -0.22e-5 = -0.0000022.
Rules for character constant
• It is a single alphanumeric digit.
• The character is enclosed in single quotes.
• Both single inverted comma point towards left.
• The maximum length of a character constant is one.
• Example ‘a’, ‘1’ , ‘@’
Operator are symbols whose meaning is already known to a C compiler there are total 45 operators used
in C language.
String the collection of characters digits or special symbols and closed in double quotes and terminated
by null character is termed as string.

Q3. What is data type in c? Explain basic data type in terms of range, format specifier and size?
Ans-Data Type:
A Data Type is a Type of Data.
Data Type is a Data Storage Format that can contain a Specific Type or Range of Values.
When computer programs store data in variables, each variable must be assigned a specific data
type.
C supports three classes of data types
1)Primary data type→ char, int, float
2) Derived data type→ array, pointer
3)User defined data type → structure, union, enum
Basic data type in C:
Data Type Range Bytes Format
signed char -128 to + 127 1 %c
unsigned char 0 to 255 1 %c
short signed int -32768 to +32767 2 %d
short unsigned int 0 to 65535 2 %u
signed int -32768 to +32767 2 %d
unsigned int 0 to 65535 2 %u
long signed int -2147483648 to 4 %ld
+2147483647
long unsigned int 0 to 4294967295 4 %lu
Float -3.4e38 to +3.4e38 4 %f
double -1.7e308 to +1.7e308 8 %lf
long double -1.7e4932 to +1.7e4932 10 %Lf
Note: The sizes and ranges of int, short and long are compiler dependent. Sizes
in this figure are for 16-bit compiler.

Q22: Define escape sequence character?


Ans:

• It is used at the time of execution.

• Execution character set is also called as non-graphic character (or) Escape


sequence.
• Escape sequence are invisible and cannot be printed (or) displayed on the output
screen.
• Escape sequence are always represented by a back slash(\) followed by a
character

Character Escape Sequence Result

Bell \a Beep Sound

Back Space \b Moves Previous Position

Horizontal Tab \t Moves next horizontal tab

Vertical Tab \v Moves next vertical tab

Newline (line feed) \n Moves next line

Form feed \f Moves initial position next page

Carriage return \r Moves beginning of the line

Single quote \’ Present Apostrophe mark

Double quotes \” Present double quotes

Backslash \\ Present Back slash mark

NULL \0 NULL

Q4: Define structure(layout) of c program with example.


Ans: c program contains the following:

Documentation section: It consists of a set of comment lines giving the name of the author date etc. of
program and other details.

Link section: It provides information or instructions to the compiler to link functions from the system
library.
Definition section: It defines all symbolic constants.
Global declaration section: Variables that are declared outside all the functions and are used in more
than one function.
Main function section: This section contains two parts declaration part and execution part.
Subprogram section: It contains all the user defined functions that are called in main functions.
Example:
// Sample of C Program(documentation Section)
#inclufe<stdio.h> // link section
#include<conio.h> // link section
#define pi 3.14 // definition section
int a=10; // global variable declaration
void disp(); // global function declaration
void main() // main function definition
{
float area,r;
printf(“enter radius”);
scanf(“%f”,&r);
area=pi*r*r;
printf(“area=%f”,area);
disp();
getch();
}
void disp() // user defined function definition
{
printf(“hello”);
}
Q5: Define different type of errors in c program.
Ans: There are different types of error in C

1. Syntax error
2. Run Time error
3. Linker error
4. Logical error
5. Semantic error

Syntax error:
• The errors which arises due to violation of any rule or regulation(syntax) of C language during
the development of program those errors are known as Syntax error.
• Syntax errors are also known as the compilation errors as they occurred at the compilation time,.
These errors are mainly occurred due to the mistakes while typing or do not follow the syntax of
the specified programming language.
Examples:-Missing of semicolon or parenthesis (}) or Displaying the value of a variable without its
declaration while writing the code.
1.If we want to declare the variable of type integer,
int a; // this is the correct form
Int a; // this is an incorrect form. .
2. #include <stdio.h>
int main()
{
a = 10; // a is not declared
printf("The value of a is : %d", a);
return 0;
}
3. #include <stdio.h>
int main()
{
int a=2;
if(.) // syntax error we put the (.) instead of condition in 'if', so this generates the syntax error
printf("a is greater than 1");
return 0;
}

Runtime error: The error which occurs during the execution of program those errors are turn termed as
runtime error. The division by zero is the common example of the run-time error. These errors are very
difficult to find, as the compiler does not point to these errors.
Linker error
• Linker errors are mainly generated when the executable file of the program is not created.
• This can be happened either due to the wrong function prototyping or usage of the wrong header
file.
Example1: The most common linker error that occurs is that we use Main() instead of main().
Example2: Using print() instead of printf().
Logical error : The errors which are introduced due to usage of wrong expression formula for logic in
program these errors are called as logical error.
The logical error is an error that leads to an undesired output.
For example using 2 * 3.14 *r as area of circle.
Or by mistake semi colon after for statements.
for(i=0;i<10;i++);
printf(”hello”);
semantic error: This error occurs when a statement is syntactically valid, but does not do
what the programmer intended.
The following can be the cases for the semantic error:
1.Use of a un-initialized variable.
int i;
i=i+2;
2.Type compatibility
int b = "VINEET";
3.Errors in expressions
int a, b;
b = a+”hi” ;
4.Array index out of bound
int a[10];
a[10] = 34;
Important programs:
1. Write a c program to swap two numbers with or without using third variable.
2. Write a program to find area of circle.
3. WAP to find area of triangle using Heron’s formula.
4. WAP to find simple interest.
5. WAP to print ASCII value of entered character.
UNIT-3

Q1. Define operator. Explain various operators used in c.


An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.
C language is rich in built-in operators and provides the following types of operators:
Arithmetic Operators:
Operator Description
+ Adds two operands
- Subtracts second operand from the first
* Multiply both operands
/ Divide numerator by denumerator
% Modulus Operator and remainder of after an
integer division
++ Increment operator, increases integer value
by one
-- Decrement operator, decreases integer value
by one

Logical (or Relational) Operators:


Operator Description
== Checks if the value of two operands is equal
or not, if yes then condition becomes true.
!= Checks if the value of two operands is equal
or not, if values are not equal then condition
becomes true.
> Checks if the value of left operand is greater
than the value of right operand, if yes then
condition becomes true.
< Checks if the value of left operand is less
than the value of right operand, if yes then
condition becomes true.
>= Checks if the value of left operand is greater
than or equal to the value of right operand, if
yes then condition becomes true.
<= Checks if the value of left operand is less
than or equal to the value of right operand, if
yes then condition becomes true.
&& Called Logical AND operator. If both the
operands are non zero then then condition
becomes true.
|| Called Logical OR Operator. If any of the
two operands is non zero then then condition
becomes true.
! Called Logical NOT Operator. Use to
reverses the logical state of its operand. If a
condition is true then Logical NOT operator
will make false.

Bitwise Operators:

Bitwise operator works on bits and perform bit by bit operation and used with integer only.
Operator Description
& Binary AND Operator copies a bit to the
result if it exists in both operands.
| Binary OR Operator copies a bit if it exists in
eather operand.
^ Binary XOR Operator copies the bit if it is
set in one operand but not both.
~ Binary Ones Complement Operator is unary
and has the efect of 'flipping' bits.
<< Binary Left Shift Operator. The left operands
value is moved left by the number of bits
specified by the right operand.
>> Binary Right Shift Operator. The left
operands value is moved right by the number
of bits specified by the right operand.

Assignment Operators:
Operator Description
= Simple assignment operator, Assigns
values from right side operands to left
side operand
+= Add AND assignment operator, It adds
right operand to the left operand and
assign the result to left operand
-= Subtract AND assignment operator, It
subtracts right operand from the left
operand and assign the result to left
operand
*= Multiply AND assignment operator, It
multiplies right operand with the left
operand and assign the result to left
operand
/= Divide AND assignment operator, It
divides left operand with the right
operand and assign the result to left
operand
%= Modulus AND assignment operator, It
takes modulus using two operands and
assign the result to left operand
<<= Left shift AND assignment operator
>>= Right shift AND assignment operator
&= Bitwise AND assignment operator
^= bitwise exclusive OR and assignment
operator
|= bitwise inclusive OR and assignment
operator

Misc Operators
Operator Description
sizeof() Returns the size of an variable.
& Returns the address of an variable.
* Pointer to a variable.
?: Conditional Expression

Q2. What do you mean by ternary operator in c? Write a program to find the largest of three
numbers using ternary operator.
Ans- Ternary Operator: In C programming language the operator which takes THREE arguments
(operands) is called as Ternary Operator. The "Conditional Operator" ( ? : ) is called as "Ternary
Operator" in C Language, because this operator takes three operands.
Syntax: condition ? Expression_1 : Expression_2 ;
Here, if the given condition is TRUE then Expression_1 is performed, if the condition is FALSE
then Expression_2 is preformed.
Program to find largest of three using ternary operator :
# include <stdio.h>
# include <conio.h>
void main()
{
int a, b, c, big ;
clrscr() ;
printf("Enter three numbers : ") ;
scanf("%d %d %d", &a, &b, &c) ;
big = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c) ;
printf("\nThe biggest number is : %d", big) ;
getch() ;
}
Output of above program
Enter three numbers : 20 30 10
The biggest number is : 30

Q3. Solve the following expression:


(i) c=a++ * ++b where a=3,b=2.
(ii) Given a=2,b=3,x=0 then find the value of x.
x=(++a,b+=a)
Ans(i)-.
So
c=3*3=9

Ans(ii)- operator ++ has highest precedence so ++a will execute first so


a=a+1
a=3 and now
x=(3,b+=a)
operators = and += have same precedence and same associativity(R-L) so += evaluate first.
b=b+a
b=3+3
b=6 and now
x=(3,6)
if many values in parenthesis are separated by comma(,) then assignment operator(=) assign the right
most value to left hand operand. So
x=6

Q4. Explain various bitwise operators with example.


Ans-
Bitwise operators are used to manipulate one or more bits from integral operands like char, int, short,
long.

Operators Meaning of operators

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR
Operators Meaning of operators

~ Bitwise complement

<< Shift left

>> Shift right

Bitwise AND operator in C programming.


The output of logical AND is 1 if both the corresponding bits of operand is 1. If either of bit is
0 or both bits are 0, the output will be 0. Let us suppose the bitwise AND operation of two
integers 12 and 25.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

Bit Operation of 12 and 25


00001100
& 00011001
________
00001000 = 8 (In decimal)

Bitwise OR operator in C
The output of bitwise OR is 1 if either of the bit is 1 or both the bits are 1. In C Programming,
bitwise OR operator is denoted by |.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

Bitwise OR Operation of 12 and 25


00001100
| 00011001
________
00011101 = 29 (In decimal)

C Programming Bitwise XOR(exclusive OR) operator


The output of bitwise XOR operator is 1 if the corresponding bits of two operators are opposite.
It is denoted by ^.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise XOR Operation of 12 and 25
00001100
^ 00011001
________
00010101 = 21 (In decimal)

Bitwise compliment operator


Bitwise compliment operator is a unary operator (works on one operand only). It changes the
corresponding bit of the operand to opposite bit i.e., 0 to 1 and 1 to 0. It is denoted by ~.
35=00100011 (In Binary)
Bitwise complement Operation of 35
~ 00100011
________
11011100 = 220 (In decimal)
Shift Operator in C programming
There are two shift operators in C programming: Right shift operator and Left shift operator.
Right Shift Operator
Right shift operator moves the all bits towards the right by certain number of bits which can be
specified. It is denoted by >>.
212 = 11010100 (In binary)
212>>2 = 00110101 (In binary) [Right shift by two bits]
Left Shift Operator
Left shift operator moves the all bits towards the left by certain number of bits which can be
specified. It is denoted by <<.
212 = 11010100 (In binary)
212<<2 = 01010000 (In binary) [Left shift by two bit]

Q5. Differentiate Associativity and precedence.


Ans: Difference between associativity and precedence:
Operator precedence determines which operator is performed first in an expression with more than one
operators with different precedence. For example 10 + 20 * 30 is calculated as 10 + (20 * 30) and not as
(10 + 20) * 30.
Associativity is used when two operators of same precedence appear in an expression. Associativity can
be either Left to Right or Right to Left. For example ‘*’ and ‘/’ have same precedence and their
associativity is Left to Right, so the expression 100 / 10 * 10″is treated as (100 / 10) * 10.
Precedence and Associativity are two characteristics of operators that determine the evaluation order of
subexpressions in absence of brackets.

Q6. What do understand by type conversion? Explain implicit and explicit type conversion with
example.
Ans- Type conversion: Conversion of one data type from another data type is called type casting.
Conversion between data types can be done in two ways :
• Implicit conversion
• Explicit conversion g
Implicit conversion:
Implicit conversion doesn't require a casting operator. This casting is normally used when converting
data from smaller integral types to larger or derived types to the basic type. Implicit Type Conversion
also known as Widening.

int x = 123;
double y = x;
In the above statement, the conversion of data from int to double is done implicitly, in other words
programmer don't need to specify any type operators.
Explicit conversion: Explicit conversion requires a casting operator. This conversion is normally used
when converting a double to int or a base type to a derived type. The Explicit type Conversion is also
known as borrowing.

double y = 123;
int x = (int)y;
In the above statement, we have to specify the type operator (int) when converting from double to int
else the compiler will throw an error.
Q7. Define sizeof() operator with example. Differentiate pre and post increment.
Ans- sizeof() operator
1. sizeof() operator is used to calcualte the size of data type or variables.
2. sizeof() operator will return the size in integer format.
3. sizeof() operator syntax looks more like a function but it is considered as an operator in c
programming
Example of sizeof() operator :
#include<stdio.h>
#include<conio.h>
void main()
{
int ivar;
char cvar;
float fvar;
clrscr();
printf("%d", sizeof(ivar));
printf("%d", sizeof(cvar));
printf("%d", sizeof(fvar));
return 0;
}

Differentiate pre and post increment:


Pre Increment Operator
Pre-increment operator is used to increment the value of variable before using in the expression. In the
Pre-Increment value is first incremented and then used inside the expression.
b = ++y;
In this example suppose the value of variable ‘y’ is 5 then value of variable ‘b’ will be 6 because the
value of ‘y’ gets modified before using it in a expression.
Post Increment Operator
Post-increment operator is used to increment the value of variable as soon as after executing expression
completely in which post increment is used. In the Post-Increment value is first used in a expression and
then incremented.
b = x++;
In this example suppose the value of variable ‘x’ is 5 then value of variable ‘b’ will be 5 because old
value of ‘x’ is used.
Q8. What do you understand by decision control statement? Write a program to check whether a
given number is even or odd.
Ans-Whenever we build an application in any programming language, there is a need of including
decision control statements in code. We can include various conditions in our program using these
statements; we can perform different- different tasks based on the conditions. Following are the decision
control statements available in C.
a) if statement
b) if-else & else-if statement
c) switch-case statements

1. If statement: The code inside if body executes only when the condition defined by if statement is
true. If the condition is false then compiler skips the statement enclosed in if’s body. We can have
any number of if statements in a C program.

Syntax:
if (condition)
{
Statements;
}
2. If-else statement: Here, we have two block of statements. If condition results true then if block
gets execution otherwise statements in else block executes. else cannot exist without if statement.
Syntax:
if (condition)
{
Statements;
}
else
{
Statements;
}
3. Switch-case statement: This is very useful when we have several blocks of statements, which
requires execution based on the output of an expression or condition. Switch defines an
expression (or condition) and case has a block of statements, based on the result of expression,
corresponding case gets execution. A switch can have any number of cases; however there should
be only one default handler.
switch (n)
{
case constant1:
code/s to be executed if n equals to constant1;
break;
case constant2:
code/s to be executed if n equals to constant2;
break;
.
.
default:
code/s to be executed if n doesn't match to any cases;
}
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("enter number");
scanf("%d",&n);
if(n%2==0)
printf("%d is EVEN\n",n);
else
printf("%d is ODD ",n);
getch();
}
Q9. What is the importance of switch case in c. Write a menu driven program to add, subtract,
multiply and divide two numbers.
Ans-
Decision making are needed when, the program encounters the situation to choose a particular
statement among many statements. If a programmer has to choose one block of statement among
many alternatives, nested if-else can be used but, this makes programming logic complex. This
type of problem can be handled in C programming using switch statement.
Syntax of switch-case
switch (n)
{
case constant1:
code/s to be executed if n equals to constant1;
break;
case constant2:
code/s to be executed if n equals to constant2;
break;
.
.
.
default:
code/s to be executed if n doesn't match to any cases;
}
The value of n is either an integer or a character in above syntax. If the value of n matches
constant in case, the relevant codes are executed and control moves out of the switch statement.
If the ndoesn't matches any of the constant in case, then the default codes are executed and
control moves out of switch statement.

The break statement at the end of each case cause switch statement to exit. If break statement is
not used, all statements below that case statement are also executed.
/* C Program to create a simple calculator for addition, subtraction,
multiplication and division */
#include<conio.h>
# include <stdio.h>
void main()
{
char o;
float num1,num2;
printf("Select an operator either + or - or * or / \n");
fflush(stdin);
scanf("%c",&o);
printf("Enter two operands: ");
scanf("%f%f",&num1,&num2);
switch(o)
{
case '+':
printf("%f + %f = %f",num1, num2, num1+num2);
break;
case '-':
printf("%f - %f = %f",num1, num2, num1-num2);
break;
case '*':
printf("%f * %f = %f",num1, num2, num1*num2);
break;
case '/':
printf("%f / %f = %f",num1, num2, num1/num2);
break;
default:
/* If operator is other than +, -, * or /, error message is shown */
printf("Error! operator is not correct");
break;
}
}

Q10. What do you understand by else if ladder? Write a program to find largest of three numbers.
Ans- In C programming language the else if ladder is a way of putting multiple ifs together when
multipath decisions are involved. It is a one of the types of decision making and branching statements. A
multipath decision is a chain of if’s in which the statement associated with each else is an if. The general
form of else if ladder is as follows -
if ( condition 1)
{
statement - 1;
}
else if (condtion 2)
{
statement - 2;
}
else if ( condition n)
{
statement - n;
}
else
{
default statment;
}
statement-x;

This construct is known as the else if ladder. The conditions are evaluated from the top of the ladder to
downwards. As soon as a true condition is found, the statement associated with it is executed and the
control is transferred to the statement-x (skipping the rest of the ladder). When all the n conditions
become false, then the final else containing the default statement will be executed.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("\n enter three no.");
scanf("%d%d%d",&a,&b,&c);
if(a>=b)
{if(a>=c)
printf("%d is largest",a);
else
printf("%d is largest",a);
}
else
{
if(b>=c)
printf("%d is largest",a);
else
printf("%d is largest",a);
}
}
Q11. Differentiate conditional operator and if else . Write a program to check whether a given year
is leap year or not.
Ans-

If else Conditional operator

In if else statement else is optional Both expr2 and expr3 are needed.

N statement can be written within if and else 1 statement can be written within exp2 and expr3
block. block.

Simple with nested conditions Complex with nested conditions

Slow execution speed. Fast execution speed.

#include<stdio.h>
#include<conio.h>
void main()
{
int n;
printf("enter year");
scanf("%d",&n);
if(n%100==0)
{
if(n%400==0)
printf("%d is LEAP YEAR\n",n);
else
printf("%d is NOT LEAP YEAR ",n);
}
else
{
if(n%4==0)
printf("%d is LEAP YEAR\n",n);
else
printf("%d is NOT LEAP YEAR ",n);
}
}
Q12. Differentiate switch case and if else.
Ans:
If else switch

works on the basis of true/ false ( zero/non-


work on the basis of equality operator
zero)

decision control instruction case control instruction

Less readable More readable

allow all sort of condition Case like (i<5) is not permitted.

No need of break break statement is essential

All data types are permit able in condition Float value is not allowed as case label.

Keyword like “switch”, “case”, “break”,


*keywords like “if” “else” is used.
“default”, are used.

Extra Important Programs for unit-3 :


1. WAP to print grade of students
2. WAP to check whether a entered symbol is digit, small char , upper char or special symbol

Q13. Differentiate break and continue with proper example in detail.


Ans-
Break Statement: In C programming, break is used in terminating the loop and switch case immediately
after it is encountered. The break statement is used with conditional if statement.
Syntax of break statement:
break;
The break statement can be used in terminating all three loops for, while and do while loops.E.g
for(i=1; i<=10; i++)
{
if(i%5==0)
break;
else printf(“%d”, i);
}
OUTPUT: 1 2 3 4
continue Statement: continue is used in loop only.
It is sometimes desirable to skip some statements inside the loop. In such cases, continue statements are
used.
Syntax of continue Statement:
continue;
Just like break, continue is also used with conditional if statement.

for(i=1; i<=10; i++)


{
if(i%5==0)
continue;
else
printf(“%d”, i);
}
OUTPUT: 1 2 3 4 6 7 8 9

Q14. Define loop and iteration. Differentiate while and do while.

Ans- Iteration, in the context of computer programming, is a process wherein a set of instructions or
structures are repeated in a sequence a specified number of times or until a condition is met. When the
first set of instructions is executed again, it is called iteration. When a sequence of instructions is executed
in a repeated manner, it is called a loop.
There are following differences between while and do-while:
Sr.N. do while While
1. do -while loop runs at least once even while loop do not run in case the condition given is
though the the condition given is false false
2. In a do-while loop the condition is In a while loop the condition is first tested and if it
tested at the last. returns true then it goes in the loop.
3. do while is exit control loop. While loop is entry control loop
4. Syntax do while loop : Syntax while loop:
do while (condition)
{ {
Statements; Statements;
}while(condition); }

Q15. Explain various loop control structure in detail.


Ans-L oops cause program to execute the certain block of code repeatedly until test condition is false.
Loops are used in performing repetitive task in programming. Consider these scenarios:
• You want to execute some code/s 100 times.
• You want to execute some code/s certain number of times depending upon input from user.
These types of task can be solved in programming using loops. There are 3 types of loops in C
programming:
I. for loop II. while loop III. do...while loop

Basic syntax of for loop is as follows:


for( expression1; expression2; expression3)
{
Single statement
or
Block of statements;
}

In the above syntax:

• expression1 - Initializes variables.


• expression2 - Conditional expression, as long as this condition is true, loop will keep executing.
• expression3 - expression3 is the modifier which may be simple increment of a variable.
Syntax of while loop:
Initialization;
while (test expression)
{
statement/s to be executed;

updating loop variables;


}
The while loop checks whether the test expression is true or not. If it is true, code/s inside the body of
while loop is executed, that is, code/s inside the braces { } are executed. Then again the test expression is
checked whether test expression is true or not. This process continues until the test expression becomes
false.

Syntax of do...while loops

Initialization;
do {
some code/s;

updating loop variables;


}
while (test expression);

At first codes inside body of do is executed. Then, the test expression is checked. If it is true, code/s
inside body of do are executed again and the process continues until test expression becomes false (zero).

Q16. Write a program to print the following pattern:


*
**
***
****
Ans-
Program for printing given pattern:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,;
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)

{
printf("*");
}
printf("\n");
}
}

Q17. Write a program to print the following pattern:


1
2 3
4 5 6
7 8 9 10
Ans- Program for printing given pattern:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k,a=1;
for(i=1;i<=4;i++)
{
for(j=1;j<=4-i;j++)
{
printf(" ");
}
for(k=1;k<=i;k++)
{
printf("%d ",a);
a++;
}
printf("\n");
}
}
Q18. Write a program in c to check whether a number is prime number or not.
Ans-#include<stdio.h>
#include<conio.h>
void main()
{
int n,i;
printf("enter number");
scanf("%d",&n);
for(i=2;i<n;i++)
{
if(n%i==0)
break;
}
If(i<n)
printf("%d is not prime ",n);
else
printf("%d is prime ",n);
}

Q19. Write a program to find s1 for following series:


S1=12+22+32+42+……………………….+N2
Ans-
// Program to find sum of series S=12+22+32+….+N2.
#include<stdio.h>
#include<conio.h>
void main()
{
int N,i,S=0;
printf("enter the value of N");
scanf("%d",&N);
for(i=1;i<=N;i++)
S=S+i*i;
printf("S=%d",S);
}

Q20. Write a program in c to find sum of digits of an integer number.


Ans- Program for finding sum of digits of a number:
#include<stdio.h>
#include<conio.h>
void main()
{
long int n;
int sum=0 ;
printf("enter number\n");
scanf("%ld",&n);
while(n>0)
{
sum=sum+n%10;
n=n/10;
}
printf("the sum of digits of number is =%d",sum);

}
Unit-4 and 5
Q1. What do you understand by function? Write a program to calculate ab using function (without
using library function pow()).
Ans-
Function in programming is a segment that groups a number of program statements to perform specific
task. A C program has at least one function main( ). Without main() function, there is technically no C
program.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,r;
int power(int,int);
printf("enter number and its power\n");
scanf("%d%d",&a,&b);
r=power(a,b);
printf("result=%d\t",r);
}
int power(int m,int n)
{
int i,p=1;
for(i=1;i<=n;i++)
p=p*m;
return(p);
}

Q2. What do mean by library function. Explain four type of user defined function with example.
Ans- Library function:
• Library functions in C language are inbuilt functions which are grouped together and placed in a
common place called library.
• Each library function in C performs specific operation.
• We can make use of these library functions to get the pre-defined output instead of writing our
own code to get those outputs.
• These library functions are created by the persons who designed and created C compilers.
• All C standard library functions are declared in many header files which are saved as file_name.h.
User defined Function: These function are created by user as per his need.
Type of user defined function:
1. No argument no return value
void add(void);
2. With argument but no return value
void add(int,int);
3. No argument with return value
int add(void);
4. With argument with return value
int add(int,int);
Q3. What is recursive function? Write a program to calculate factorial of a number using
recursion.
Recursive Function: Recursive function is the function which calls itself repeatedly until some condition
is met and then the function stops calling itself and returns to the caller.
A recursive function has two parts:
1- Base case (stopping condition)
2-Recursive case :which must always get closer to base case from one invocation to another.
/*program to calculate factorial using recursive function*/
#include<stdio.h>
int fact(int);
int main(){
int num,f;
printf("\nEnter a number: ");
scanf("%d",&num);
f=fact(num);
printf("\nFactorial of %d is: %d",num,f);
return 0;
}

int fact(int n){


if((n==0)||(n==1)))
return 1;
else
return(n*fact(n-1));
}

Q4. Differentiate iteration and recursion. Write a recursive program to find GCD(greatest common
divisor) of two numbers.
Ans- Difference between Recursion and Iteration
RECURSION ITERATIONS

Recursive function – is a function that is partially Iterative Instructions –are loop based
defined by itself repetitions of a process

Recursion Uses selection structure Iteration uses repetition structure

Infinite recursion occurs if the recursion step does An infinite loop occurs with iteration if the

not reduce the problem in a manner that converges loop-condition test never becomes false

on some condition.(base case)

Recursion terminates when a base case is recognized It terminates when the loop-condition fails

Recursion is usually slower then iteration due to Iteration does not use stack so it's faster than

overhead of maintaining stack recursion


Recursion uses more memory than iteration Iteration consume less memory

Infinite recursion can crash the system infinite looping uses CPU cycles repeatedly

Recursion makes code smaller Iteration makes code longer

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,r;
int gcd(int,int); //Function prototype
printf("enter two numbers\n");
scanf("%d%d",&a,&b);
if(a>b)
r=gcd(a,b);
else
r=gcd(b,a);
printf("result=%d\t",r);
}
int gcd(int m,int n)
{
if(n==0)
return(m);
else
return(gcd(n,m%n));
}
}
Q5. Differentiate call by value and call by reference with example.
Difference between call by value and call by reference in c:
No. Call by value Call by reference

1 A copy of value is passed to the function An address of value is passed to the function

2 Changes made inside the function is not Changes made inside the function is reflected
reflected on other functions outside the function also

3 Actual and formal arguments will be created Actual and formal arguments will be created
in different memory location in same memory location

4. Pointers not required. Pointers required.


5. void swap(int,int);// function declaration void swap(int *,int *);// function declaration
swap(a,b);// function calling swap(&a,&b);// function calling
//function definition //function definition
void swap(int c,int d) void swap(int *c,int *d)
{ {
int t; int t;
t=c; t=*c;
c=d; *c=*d;
d=t; *d=t;
} }

Q6. What is pointer? Write a program to swap two numbers using call by reference.
Ans-
Pointer-A pointer is a variable whose value is the address of another variable, i.e., direct address of the
memory location. Like any variable or constant, you must declare a pointer before you can use it to store
any variable address.
The general form of a pointer variable declaration is:
type *var-name;
example- int *p; here p is a pointer which stores the address of an integer variable.

// WAP to to swap two numbers using call by reference


#include<stdio.h>
#include<conio.h>
void main()
{

int a,b;
void swap(int *,int *);
printf("enter first no.");
scanf("%d",&a);
printf("enter second no.");
scanf("%d",&b);
printf("before swapping =%d b=%d\n",a,b);
swap(&a,&b);
printf("\nafter swapping in main a=%d b=%d ",a,b);
}
void swap(int *p,int *q)
{
int c;
c=*p;
*p=*q;
*q=c;
printf("after swapping in swap a=%d b=%d ",*p,*q);
}
Q7. What is double pointer? Write a program to calculate area and perimeter of a circle using
pointer.
Ans-
Pointer Stores the address of the Variable. Double Pointer Stores the address of the Pointer Variable.
Double (**) is used to denote the double Pointer.
Exp:
int num = 45 , *ptr , **ptr2 ;
ptr = &num;
ptr2 = &ptr;
Statement What will be the Output ?
*ptr 45
**ptr2 45
Ptr &num
ptr2 &ptr

Q8. Define array. Write a program to search for an element in array.


Ans- Array:

• An array is a collection of similar data type elements stored in contiguous memory locations.

• An array is also termed as subscript variable. Here first element is stored as 0th location.
• Till the array is not initialized it contains garbage value while if partially initialized it contains
zero.
• One of the limitation of array is, it does not provide bound checking.
• Array name is base address of array (base address is the address of first element of array). And
You cannot change the base address of array.
Application of Array
Searching- It is the process of finding the location of specific element in an array of n elements. e.g.
linear search, binary search
Sorting- It is the process of arranging the elements in specific order in an array of n elements. e.g. bubble
sort
Example for C Arrays:
• int a[10]; // integer array
• char b[10]; // character array
// WAP to search an element in one dimensional array
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100];
int i,num,pos,c=0,n;
clrscr();
printf("enter size of array");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter value");
scanf("%d",&a[i]);
}
printf("enter number which you want to search");
scanf("%d",&num);
for(i=0;i<n;i++)
{
if(num==a[i])
{
printf("%d is found at a[%d]\n",num,i);
c++;
}
}
if(c==0)
printf("%d in not present in array");
else
printf("%d is fount %d times in array",num,c);
getch();
}
Q9. What is 2D array? Write a program to find sum of all elements of 2D array.
Ans- Two dimensional array in C:
• Two dimensional array is nothing but array of array.
• syntax : data_type array_name[num_of_rows][num_of_column]
S.no Array declaration Array initialization Accessing array
Syntax: data_type arr_name data_type arr_name[2][2] =
1 arr_name[index];
[num_of_rows][num_of_column]; {{0,0},{0,1},{1,0},{1,1}};
arr [0] [0] = 1; arr [0]
]1] = 2;arr [1][0] = 3;
2 Example:int arr[2][2]; int arr[2][2] = {1,2, 3, 4};

arr [1] [1] = 4;

#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5],i,j,m,n,s=0;
clrscr();
printf("enter the order of matrix");
scanf("%d%d",&m,&n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("enter matrix");
scanf("%d",&a[i][j]);
s=s+a[i][j];
}
}
printf("\nsum=%d",s);
getch();
}
Q10. What is storage class in c? Explain various storage classes in c in detail.
Ans-

A storage class is an attribute that tells us where the variable would be stored, what will be the initial
value of the variable if no value is assigned to that variable, life time of the variable and scope of the
variable.
There are four storage classes in C:
1) Automatic storage class
2) Register storage class
3) Static storage class
4) External storage class
Initial /
Storage Storage
S.No. default Scope Life
Specifier place
value

CPU Garbage Local to the Within the function


1 auto
Memory value block only.

Register Garbage Local to the Within the function


2 register
memory value block only.

Retains the value of


CPU Local to the the variable between Q8. What is
3 static Zero
memory block different function structure?
calls. Differentiat
CPU Till the end of the e structure
4 extern Zero Global
memory main program. and union
in detail.
Ans- Structure is the collection of variables of different types under a single name for better handling.
Keyword struct is used for creating a structure.
Syntax of structure
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeber;
};

Structure Union
1.The keyword struct is used to define a structure 1. The keyword union is used to define a union.
2. When a variable is associated with a structure, 2. When a variable is associated with a union, the
the compiler allocates the memory for each compiler allocates the memory by considering the
member. The size of structure is greater than or size of the largest memory. So, size of union is
equal to the sum of sizes of its members. The equal to the size of largest member.
smaller members may end with unused slack bytes.
3. Each member within a structure is assigned 3. Memory allocated is shared by individual
unique storage area of location. members of union.
4. The address of each member will be in ascending 4. The address is same for all the members of a
order This indicates that memory for each member union. This indicates that every member begins at
will start at different offset values. the same offset value.
5 Altering the value of a member will not affect 5. Altering the value of any of the member will
other members of the structure. alter other member values.
6. Individual member can be accessed at a time 6. Only one member can be accessed at a time.
7. Several members of a structure can initialize at 7. Only the first member of a union can be
once. initialized.

Q11. What is union? Write a program to print the record of student having maximum marks.
Structure student has following fields: Integer roll number, string student name, string class name,
integer marks.
Ans- A union is a special data type available in C that enables you to store different data types in the
same memory location. You can define a union with many members, but only one member can contain a
value at any given time. Unions provide an efficient way of using the same memory location for multi-
purpose.
Defining a Union: To define a union, you must use the union statement. Here is the way you would
define a union type named Data which has the three members i, f, and str. The format of the union
statement is as follows:
union Data
{
int i;
float f;
char str[20];
} data;
Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. The
memory occupied by a union will be large enough to hold the largest member of the union. For example,
in above example Data type will occupy 20 bytes of memory space because this is the maximum space
which can be occupied by character string.

Accessing Union Members


To access any member of a union, we use the member access operator (.). The member access operator
is coded as a period between the union variable name and the union member that we wish to access.
data.i=10.
Program for displaying the record of student having maximum marks:
#include<stdio.h>
#include<conio.h>
void main()
{
struct student
{
int rn;
char name[20];
char clas[20];
int marks;
}s[10];
int i,pos=0,max;
clrscr();
for(i=0;i<10;i++)
{
printf("Enter roll number,name,class and marks\n");
scanf("%d%s%s%d",&s[i].rn,&s[i].name,&s[i].clas,&s[i].marks);
}
max=s[0].marks;
for(i=1;i<10;i++)
{
if(s[i].marks>max)
{
max=s[i].marks;
pos=i;
}
}
printf("\nRecord of student having maximum marks\n");
printf("\n%d\t%s\t%s\t%d",s[pos].rn,s[pos].name,s[pos].clas,s[pos].marks);
getch();
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy