0% found this document useful (0 votes)
2 views

Question_and_answers_-_Programming_in_C-1

The document is a comprehensive question bank on programming in C, covering key concepts such as constants, variables, keywords, data types, operators, and features of the C language. It includes detailed explanations, rules, and examples for each topic, providing a solid foundation for understanding C programming. Additionally, it discusses operator precedence and associativity, which are crucial for evaluating expressions in C.

Uploaded by

ajaykakde2908
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Question_and_answers_-_Programming_in_C-1

The document is a comprehensive question bank on programming in C, covering key concepts such as constants, variables, keywords, data types, operators, and features of the C language. It includes detailed explanations, rules, and examples for each topic, providing a solid foundation for understanding C programming. Additionally, it discusses operator precedence and associativity, which are crucial for evaluating expressions in C.

Uploaded by

ajaykakde2908
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

QUESTION BANK WITH ANSWERS

SUBJECT: -PROGRAMMING IN C

Q1.What do you understand by constant?


ANS: C Constants are like normal variables. Whose values can not be modified by the program
once they are defined.Constants refer to fixed values. They are also called as
literals.Constants may be belonging to any of the data type.
Syntax:

const data_type variable_name; (or) const data_type *variable_name;

Types of C constant:
1. Integer constants
2. Real or Floating point constants
3. Octal & Hexadecimal constants
4. Character constants
5. String constants
6. Backslash character constants
Rules for constructing C constant:

1. Integer Constants in C:

o An integer constant must have at least one digit.


o It must not have a decimal point.
o It can either be positive or negative.
o No commas or blanks are allowed within an integer constant.
o If no sign precedes an integer constant, it is assumed to be positive.
o The allowable range for integer constants is -32768 to 32767.

2. Real constants in C:

o A real constant must have at least one digit


o It must have a decimal point
o It could be either positive or negative
o If no sign precedes an integer constant, it is assumed to be positive.
o No commas or blanks are allowed within a real constant.

3. Character and string constants in C:

o A character constant is a single alphabet, a single digit or a single special symbol


enclosed within single quotes.
o The maximum length of a character constant is 1 character.
o String constants are enclosed within double quotes.

4. Backslash Character Constants in C:

o There are some characters which have special meaning in C language.


o They should be preceded by backslash symbol to make use of special function of
them.
o Given below is the list of special characters and their purpose.

Backslash_character Meaning
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\” Double quote
\’ Single quote
\\ Backslash
\v Vertical tab
\a ALERT or bell
\? Question mark
\N Octal constant (N is an octal constant)
\XN Hexadecimal constant (N – hex.dcml cnst)

Q2.What are variables in C programming?

ANS

 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 get change in the program.
 C variable might be belonging to any of the data type like int, float, char etc.

Rules for naming C variable:

1. Variable name must begin with letter or underscore.


2. Variables are case sensitive
3. They can be constructed with digits, letters.
4. No special symbols are allowed other than underscore.
5. sum, height, _value are some examples for variable name

Declaring & initializing C variable:

 Variables should be declared in the C program before to use.


 Memory space is not allocated for a variable while declaration. It happens only on
variable definition.
 Variable initialization means assigning a value to the variable.

S.No Type Syntax Example


1 Variable declaration data_type variable_name; int x, y, z; char flat, ch;
Variable data_type variable_name = int x = 50, y = 30; char flag = ‘x’,
2
initialization value; ch=’l’;
Q3.What are keyword?

ANS:

o Keywords are pre-defined words in a C compiler.


o Each keyword is meant to perform a specific function in a C program.
o Since keywords are referred names for compiler, they can’t be used as variable name.

C language supports 32 keywords which are given below.

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Q5. Explain data types in C language.?

ANS:

 C data types are defined as the data storage format that a variable can store a data to perform a
specific operation.
 Data types are used to define a variable before to use in a program.

Integer data type:

 Integer data type allows a variable to store numeric values.


 “int” keyword is used to refer integer data type.
 The storage size of int data type is 2 or 4 or 8 byte.
 It varies depend upon the processor in the CPU that we use. If we are using 16 bit processor,
2 byte (16 bit) of memory will be allocated for int data type.
 Like wise, 4 byte (32 bit) of memory for 32 bit processor and 8 byte (64 bit) of memory for 64
bit processor is allocated for int data type.
 int (2 byte) can store values from -32,768 to +32,767
 int (4 byte) can store values from -2,147,483,648 to +2,147,483,647.
 If you want to use the integer value that crosses the above limit, you can go for “long int” and
“long long int” for which the limits are very high.

Character data type:

 Character data type allows a variable to store only one character.


 Storage size of character data type is 1. We can store only one character using character data
type.
 “char” keyword is used to refer character data type.
 For example, ‘A’ can be stored using char datatype. You can’t store more than one character
using char data type.
 Please refer C – Strings topic to know how to store more than one characters in a variable.
1.3. Floating point data type:

Floating point data type consists of 2 types. They are,

1. float
2. double

1. float:

 Float data type allows a variable to store decimal values.


 Storage size of float data type is 4. This also varies depend upon the processor in the CPU as
“int” data type.
 We can use up-to 6 digits after decimal using float data type.
 For example, 10.456789 can be stored in a variable using float data type.

2. double:

 Double data type is also same as float data type which allows up-to 10 digits after decimal.
 The range for double data type is from 1E–37 to 1E+37.

Q6. Explain operator in C?

ANS:

Types of C operators:

C language offers many types of operators. They are,

1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators

Continue on types of C operators:

o Click on each operators name below for detail description and example programs.

S.no Types of Operators Description


These are used to perform mathematical calculations like addition,
1 Arithmetic_operators
subtraction, multiplication, division and modulus
2 Assignment_operators These are used to assign the values for the variables in C programs.
3 Relational operators These operators are used to compare the value of two variables.
These operators are used to perform logical operations on the given
4 Logical operators
two variables.
5 Bit wise operators These operators are used to perform bit operations on given two
variables.
Conditional (ternary) Conditional operators return one value if condition is true and
6
operators returns another value is condition is false.
Increment/decrement These operators are used to either increase or decrease the value of
7
operators the variable by one.
8 Special operators &, *, sizeof( ) and ternary operators.

1.Arithmetic Operators in C:

o C Arithmetic operators are used to perform mathematical calculations like addition,


subtraction, multiplication, division and modulus in C programs.

S.no Arithmetic Operators Operation Example


1 + Addition A+B
2 - Subtraction A-B
3 * multiplication A*B
4 / Division A/B
5 % Modulus A%B

Assignment operators in C:

o In C programs, values for the variables are assigned using assignment operators.
o For example, if the value “10″ is to be assigned for the variable “sum”, it can be
assigned as “sum = 10;”
o Other assignment operators in C language are given below.

Operators Example Explanation


Simple assignment operator = sum=10 10 is assigned to variable sum
+= sum+=10 This_is_same_as_sum=sum+10…………
-= sum-=10 This is same as sum = sum-10
*= sum*=10 This is same as sum = sum*10
Compound assignment operators /+ sum/=10 This is same as sum = sum/10
%= sum%=10 This is same as sum = sum%10
&= sum&=10 This is same as sum = sum&10
^= sum^=10 This is same as sum = sum^10

Example program for C assignment operators:

o In this program, values from 0 – 9 are summed up and total “45″ is displayed as
output.
o Assignment operators such as “=” and “+=” are used in this program to assign the
values and to sum up the values.

Relational operators in C:

o Relational operators are used to find the relation between two variables. i.e. to
compare the values of two variables in a C program.
S.no Operators Example Description
1 > x>y x is greater than y
2 < x<y x is less than y
3 >= x >= y x is greater than or equal to y
4 <= x <= y x is less than or equal to y
5 == x == y x is equal to y
6 != x != y x is not equal to y

Logical operators in C:

o These operators are used to perform logical operations on the given expressions.
o There are 3 logical operators in C language. They are, logical AND (&&), logical OR
(||) and logical NOT (!).

S.no Operators Name Example Description


logical
1 && (x>5)&&(y<5) It returns true when both conditions are true
AND
2 || logical OR (x>=10)||(y>=10) It returns true when at-least one of the condition is true
It reverses the state of the operand “((x>5) && (y<5))”
logical
3 ! !((x>5)&&(y<5)) If “((x>5) && (y<5))” is true, logical NOT operator
NOT
makes it false

Bit wise operators in C:

o These operators are used to perform bit operations. Decimal values are converted
into BINARY values which are the sequence of bits and bit wise operators work on
these bits.
o Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise OR),
^ (XOR), << (left shift) and >> (right shift).

Conditional or ternary operators in C:

o Conditional operators return one value if condition is true and returns another value is
condition is false.
o This operator is also called as ternary operator.

Syntax : (Condition? true_value: false_value);


Example : (A > 100 ? 0 : 1);
.

o In above example, if A is greater than 100, 0 is returned else 1 is returned. This is


equal to if else conditional statements.

Increment Decrement

 Increment operators are used to increase the value of the variable by one and decrement
operators are used to decrease the value of the variable by one in C programs.

 Syntax:
Increment operator : ++var_name; (or) var_name++;
Decrement operator : – - var_name; (or) var_name – -;

 Example:

Increment operator : ++ i ; i ++ ;
Decrement operator: – - i ; i – - ;

Q7. Describe the main features of C language with examples.

ANS
Features of ‘C’ language:-
C is a general purpose, structured programming language. C programming is widely used in
computer Technology.
Low Level Features:
C programming provides Low level features that are generally provided by the Lower
level languages. C is closely related to Lower level Language such as “Assembly
Language”.
It is easier to write assembly codes in C programming.
Portability:
C Programs are portable i.e. they can run on any Compiler with little or No
Modification.
Compiler and Preprocessor make it possible for C Programs to run it on Different
Platforms.
Powerful:
Provides wide verity of “Data Types”
Provides wide verity of “Functions”
Provides useful Control and Loop Control Statements
Bit Manipulation
C Programs can be manipulated using bits. We can perform different operations at bit
level.
It provides wide verity of bit manipulation Operators. We have bitwise operators to
manage Data at bit level.
High Level Features:
It is more User friendly as compare to Previous Languages. Previous languages such
as BCPL, Pascal and other programming languages never provide such great features
to manage data.
Previous languages have their Pros and Cons but C Programming collected all useful
features of previous languages thus C become more effective Language.
Modular Programming:
Modular programming is a software design technique that increases the extent to
which software is composed of separate parts, called Modules.
C Program consist of different modules that are integrated together to form complete
program.
Efficient Use of Pointers:
Pointers have direct access to memory.
C supports efficient use of pointer.
More Efficient:
C Programming language is more efficient to Other languages.
Q.8 Discuss Precedence order and associativity of operators.

If more than one operators are involved in an expression then, C language has predefined rule of
priority of operators. This rule of priority of operators is called operator precedence.

In C, precedence of arithmetic operators(*,%,/,+,-) is higher than relational


operators(==,!=,>,<,>=,<=) and precedence of relational operator is higher than logical
operators(&&, || and !). Suppose an expression:

Associativity of operators

Associativity indicates in which order two operators of same precedence(priority) executes. Let us
suppose an expression:

a==

(a==b)!

Here, operators == and != have same precedence. The associativity of both == and != is left to right,
i.e, the expression in left is executed first and execution take pale towards right.
Thus, a==b!=c equivalent to :

The table below shows all the operators in C with precedence and associativity.

Note: Precedence of operators decreases from top to bottom in the given table.

Summary of C operators with precedence and associativity


Operator Meaning of operator Associativity
() Functional call
[] Array element reference
Left to right
-> Indirect member selection
. Direct member selection
! Logical negation
~ Bitwise(1 's) complement
+ Unary plus
- Unary minus
++ Increment
Right to left
-- Decrement
& Dereference Operator(Address)
* Pointer reference
sizeof Returns the size of an object
(type) Type cast(conversion)
* Multiply
/ Divide Left to right
% Remainder
+ Binary plus(Addition)
Left to right
- Binary minus(subtraction)
<< Left shift
Left to right
>> Right shift
Summary of C operators with precedence and associativity
Operator Meaning of operator Associativity
< Less than
<= Less than or equal
Left to right
> Greater than
>= Greater than or equal
== Equal to
Left to right
!= Not equal to
& Bitwise AND Left to right
^ Bitwise exclusive OR Left to right
| Bitwise OR Left to right
&& Logical AND Left to right
|| Logical OR Left to right
?: Conditional Operator Left to right
Simple assignment
=
Assign product
*=
Assign quotient
/=
Assign remainder
%=
Assign sum
-=
Assign difference Right to left
&=
Assign bitwise AND
^=
Assign bitwise XOR
|=
Assign bitwise OR
<<=
Assign left shift
>>=
Assign right shift
, Separator of expressions Left to right

Q10 Discuss the basic structure of a ‘C’ program.

ANS: Basic structure of C program:

Structure of C program is defined by set of rules called protocol, to be followed by programmer


while writing C program. All C programs are having sections/parts which are mentioned below.

1. Documentation section
2. Link Section
3. Definition Section
4. Global declaration section
5. Function prototype declaration section
6. Main function
7. User defined function definition section

oSectionsDescription

1Documentation section:
We can give comments about the program, creation or modified date, author name etc
in this section. The characters or words or anything which are given between “/*” and
“*/”, won’t be considered by C compiler for compilation process.These will be
ignored by C compiler during compilation.
Example : /* comment line1 comment line2 comment 3 */

2.Link Section

Header files that are required to execute a C program are included in this section

3.Definition Section

In this section, variables are defined and values are set to these variables.

4.Global declaration section

Global variables are defined in this section. When a variable is to be used throughout
the program, can be defined in this section.

5.Function prototype declaration section

Function prototype gives many information about a function like return type,
parameter names used inside the function.

6.Main function

Every C program is started from main function and this function contains two major
sections called declaration section and executable section.

7.User defined function section

User can define their own functions in this section which perform particular task as
per the user requirement.

Q11.What is type modifier :


T y p e M o d i fi er s
|

In addition, these data types have some modifiers preceding them. The use of these modifiers changes
the meaning of the base type.

The memory in the computer is organized in terms of units called bytes. One byte consists of 8 bits
and bit is a smallest unit of memory.

Need of Data Modifiers:


Let us take an example of a Program where we need to input the “Salary” of “Employees” in a team.
This program will accept the salary as an input from user and then calculate the Income Tax of that
user. We use “int” to store the Salary of the employee as we are assuming that the salary will be in
“Whole Numbers”.

An integer data type takes 2 Bytes of Memory and we are aware that the Salary of any of the
employee can not be “Negative”. We are using “2 Bytes” to store the memory of an Employee and
we can easily save 1 Byte over there by removing the “Signed Part” in the integer. This positive value
can easily be stored in “1 Bye Int” This leads us to the user of Data Type Modifiers.

Types of Data Modifiers in C:

The modifiers are listed below :

Signed Type Modifier:

All data types are “signed” by default. Signed Data Modifier implies that the data type variable can
store positive values as well as negative values.

For example, if we need to declare a variable to store temperature, it can be negative as well as
positive.

signed int temperature; Or int temperature;

Unsigned Type Modifier:


If we need to change the data type so that it can only store only store positive values, “unsigned” data
modifier is used.

For example, if we need to declare a variable to store the salary of an employee as explained above,
we will use “Unsigned” Data Qualifier here.
unsigned int salary;

Long Type Modifier:

Sometimes while coding a program, we need to increase the Storage Capacity of a variable so that it
can store values higher than its maximum limit which is there as default. In such situations or
programs, we need to make use of the “long” data type qualifier. “long” type modifier doubles the
“length” of the data type when used along with it.
For example, if we need to store the “annual turnover” of a company in a variable, we will make us
of this type qualifier.

long int turnover;

This variable will take 4 Bytes in memory.

Short Type Modifier:

A “short” type modifier does just the opposite of “long”. If one is not expecting to see high range
values in a program and the values are both positive & negative.

For example, if we need to store the “age” of a student in a variable, we will make use of this type
qualifier as we are aware that this value is not going to be very high.

short int age;

This variable will consume only 1 Byte in memory.

We can apply the above mentioned modifiers to integer (int) and character (char) base types.

1. Integer Type Modifiers:

* We can use all the above mentioned Type Modifiers for int data type in C Language
* Short int and long int are also termed as short and long respectively.

* Int is signed & unsigned by default.

2. Character Type Modifiers:

* Variables of type char consume 1 byte in memory.


* Char can be signed or unsigned only.
* They have a range of -128 to 127 and 0 to 255 for signed & unsigned respectively.

3. Float Type & Double Type Modifier:

There are 3 types of float type modifiers as given below:

* float

* double

* long double

Double is same as long float. Float type occupies 4 bytes of memory. Type double occupies 8 bytes.
Long double occupies 10 bytes. The exception to this is long double, which modifies the size of the
double data type to 10 bytes. Please note that in some compilers this has no effect.

Note: We may use long modifier with double data type but it cannot be used with float, i.e. long
double is allowed but long float is not allowed because long float is equal to double.

Q11.how to compile and execute a program

1. Editor-Type your program in editor(source code).


2. Preprocessing-During this step, the C source code is expanded based on the
preprocessor directives like as #include, #ifdef, #define etc. The expanded source code is
stored in an intermediate file with .i extension.
3. Compilation- The expanded source code is then passed to the compiler, which
identifies the syntax error in the expanded source code. If the expanded source code is error
free, then the compiler transfer the expanded source code in C, into an equivalent assembly
language program. The assembly code is typically stored in .ASM file. So our first.c file
would be changed and stored in first.ASM.
4. Assembling - Assembler translate the .ASM program into Relocatable Object code.
Thus assembler translate our first.asm file into first.OBJ. .OBJ file is one of the binary file.
This object file contained header and several section.
5. Linking - Linking is the final step of build process i.e. creating an executable
program. It's do following works :
o Find definition of all external function
o Find definition of all global variables
o Combine Data Section
o Combine Code Section
6. Loading - Once the .EXE file is created and stored on the disk,it is ready for
execution. when we execute it, it is first brought from the disk into the memory (RAM) by an
OS component called Program Loader.

Q12explain printf() in c
printf() function:

o printf() function is used to print the “character, string, float, integer, octal and
hexadecimal values” onto the output screen.
o We use printf() function with %d format specifier to display the value of an integer
variable.
o Similarly %c is used to display character, %f for float variable, %s for string
variable, %lf for double and %x for hexadecimal variable.
o To generate a newline,we use “\n” in C printf() statement.

Q13. Explain printf()and scanf() in detail


Ans:
Printf():
 To print a character string, supply the string (contained in double quotes) as the parameter
to printf. This string is called the format string. The two-character sequence \n displays a
newline, and the two-character sequence \t displays a tab.
 To print an int, embed the sequence %d in the format string, and include an integer expression
as a second parameter. (The sequence %d is called a conversion specification.) The value of
the expression will be displayed in place of the %d.
 To print a double, embed one of the sequences %g, %f, or %e in the format string, and
include a floating-point expression as a second parameter. The value of the expression will be
displayed in place of the conversion specification. The way that the value will be displayed
depends upon which of the three conversion specifications you use.
o The %g specification displays the number as a six-digit mantissa, with an exponent if
necessary.
o The %f specification displays the number with six digits after the decimal point and no
exponent.
o The %e specification displays the number using scientific notation, with one digit
before the decimal point, six after the decimal point, and an exponent.
 To display more than one number, include more than one conversion specification and more
than one extra parameter.

Scanf():
 To read an int, supply scanf with a format string containing the conversion specification %d,
and include an int variable preceded by an ampersand (&) as the second parameter.
 To read a double, supply scanf with a format string containing the conversion
specification %lf (that's a lower case L, not a one), and include a doublevariable preceded by
an ampersand as the second parameter.
 To read more than one number, include more than one conversion specification and more than
one extra parameter.
Importance of the Ampersand symbol (&)

It is important to put the ampersand in front of the variables that appear as parameters to scanf, and it
is easy to forget to do this. Remove the ampersand and compile and run the program. The program
will crash before it runs to completion. Put the ampersand back. If you see this behavior in the future,
check your scanfstatements.

Q14. What re escape sequence characters in c?


Ans:
In C language there are some characters that are not treated as the same. These character
combinations that give different results such as a new line, a tab space, or a backspace, are known
as escape sequences.

Q15 Which are library function used in c


Ans:
 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.
 Actually, function declaration, definition for macros are given in all header files.
 We are including these header files in our C program using “#include<file_name.h>”
command to make use of the functions those are declared in the header files.
 When we include header files in our C program using “#include<filename.h>” command, all
C code of the header files are included in C program. Then, this C program is compiled by
compiler and executed.

S.No Header file Description


This is standard input/output header file in which Input/Output
1 stdio.h
functions are declared
2 conio.h This is console input/output header file
3 string.h All string related functions are defined in this header file
4 stdlib.h This header file contains general functions used in C programs
5 math.h All maths related functions are defined in this header file
Q16.what are the control structure in c Explain Decision making statements

Ans:
Control statements enable us to specify the flow of program control; ie, the order in which the
instructions in a program must be executed. They make it possible to make decisions, to perform
tasks repeatedly or to jump from one section of code to another.
There are four types of control statements in C:

1. Decision making statements


2. Selection statements
3. Iteration statements
4. Jump statements

Decision making statements

 In decision control statements (C if else and nested if), group of statements are executed when
condition is true. If condition is false, then else part statements are executed.
 There are 3 types of decision making control statements in C language. They are,

1. if statements
2. if else statements
3. nested if statements

“If”, “else” and “nested if” decision control statements in C:

o Syntax for each C decision control statements are given in below table with
description.

Decision
control Syntax Description
statements
if (condition) In these type of statements, if condition is true, then
if
{ Statements; } respective block of code is executed.
if (condition)
In these type of statements, group of statements are
{ Statement1; Statement2;}
if…else executed when condition is true. If condition is false,
else
then else part statements are executed.
{ Statement3; Statement4; }
if
(condition1){ Statement1; } If condition 1 is false, then condition 2 is checked and
nested if else_if (condition2) statements are executed if it is true. If condition 2 also
{ Statement2; } gets failure, then else part is executed.
else Statement 3;
Q17. Which looping statements used in c.
Ans:
There may be a situation, when you need to execute a block of code several number of times. In
general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.

Programming languages provide various control structures that allow for more complicated execution
paths.

A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages:

1.While Loop:
A while loop statement in C programming language repeatedly executes a target statement as long as
a given condition is true.
Syntax:
The syntax of a while loop in C programming language is:
while(condition)
{
statement(s);
}
Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is any nonzero value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following the
loop.
Flow Diagram:

Here, key point of the while loop is that the loop might not ever run. When the condition is tested and
the result is false, the loop body will be skipped and the first statement after the while loop will be
executed.
Example:
#include <stdio.h>

void main ()
{
/* local variable definition */
int a = 10;

/* while loop execution */


while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
}

Getch();
}
2.Do…While loop
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at
least one time.
Syntax:
The syntax of a do...while loop in C programming language is:
do
{
statement(s);
}while( condition );

Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop
execute once before the condition is tested.

If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop
execute again. This process repeats until the given condition becomes false.

Flow Diagram:

Example:
#include <stdio.h>

void main ()
{
/* local variable definition */
int a = 10;

/* do loop execution */
do
{
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );

Getch();
}

3.For loop:
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
Syntax:
The syntax of a for loop in C programming language is:
for ( init; condition; increment )
{
statement(s);
}

Here is the flow of control in a for loop:

1. The init step is executed first, and only once. This step allows you to declare and initialize any loop
control variables. You are not required to put a statement here, as long as a semicolon appears.
2. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body
of the loop does not execute and flow of control jumps to the next statement just after the for loop.
3. After the body of the for loop executes, the flow of control jumps back up to the incrementstatement.
This statement allows you to update any loop control variables. This statement can be left blank, as
long as a semicolon appears after the condition.
4. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself
(body of loop, then increment step, and then again condition). After the condition becomes false, the
for loop terminates.

Flow Diagram:

Example:
#include <stdio.h>

void main ()
{
/* for loop execution */
for( int a = 10; a < 20; a = a + 1 )
{
printf("value of a: %d\n", a);
}

Getch();
}
Q18.Difference between while loop and do..while loop
Ans:

Q19. CONDITIONAL EXPRESSION OPERATOR in c

Ans:

THE CONDITIONAL EXPRESSION OPERATOR


This conditional expression operator takes THREE operators. The two symbols used to denote this
operator are the ? and the :. The first operand is placed before the ?, the second operand between the ?
and the :, and the third after the :. The general format is,

condition ? expression1 : expression2

If the result of condition is TRUE ( non-zero ), expression1 is evaluated and the result of the
evaluation becomes the result of the operation. If the condition is FALSE (zero), then expression2 is
evaluated and its result becomes the result of the operation. An example will help,

s = ( x < 0 ) ? -1 : x * x;

If x is less than zero then s = -1


If x is greater than zero then s = x * x

Q20.Use of break statement in c


Ans:
There are two statements built in C programming, break; and continue; to alter the normal
flow of a program. Loops perform a set of repetitive task until text expression becomes false
but it is sometimes desirable to skip some statement/s inside loop or terminate the loop
immediately without checking the test expression. In such cases, break and continue
statements are used. The break;statement is also used in switch statement to exit switch
statement.

break Statement

In C programming, break is used in terminating the loop 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.

The figure below explains the working of break statement in all three type of loops.
Q21.Use of continue statement in c

Ans:

continue Statement

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 better understanding of how continue statements works in C programming. Analyze the
figure below which bypasses some code/s inside loops using continue statement.
Example of continue statement
Write a C program to find the product of 4 integers entered by a user. If user enters 0
skip it.

//program to demonstrate the working of continue statement in C programming

# include <stdio.h>

void main()

int i,num,product;

for(i=1,product=1;i<=4;++i){

printf("Enter num%d:",i);

scanf("%d",&num);

if(num==0)

continue; / *In this program, when num equals to zero, it skips the statement
product*=num and continue the loop. */
product*=num;

printf("product=%d",product);

getch();

Q21. Explain goto statement in c


Ans:
A goto statement in C programming language provides an unconditional jump from the goto to a
labeled statement in the same function.
NOTE: Use of goto statement is highly discouraged in any programming language because it makes
difficult to trace the control flow of a program, making the program hard to understand and hard to
modify. Any program that uses a goto can be rewritten so that it doesn't need the goto.
Syntax:
The syntax for a goto statement in C is as follows:
goto label;
..
.
label: statement;
Here label can be any plain text except C keyword and it can be set anywhere in the C program
above or below to goto statement.
Flow Diagram:

Example:
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;

/* do loop execution */
LOOP:do
{
if( a == 15)
{
/* skip the iteration */
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;

}while( a < 20 );

return 0;
}

Q23. Expain the types of array in detail


Ans:
C programming language provides a data structure called the array, which can store a fixed-size
sequential collection of elements of the same type. An array is used to store a collection of data, but it
is often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare
one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to
represent individual variables. A specific element in an array is accessed by an index.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.

Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of elements
required by an array as follows:

type arrayName [ arraySize ];


This is called a single-dimensional array. The arraySize must be an integer constant greater than zero
and type can be any valid C data type. For example, to declare a 10-element array called balance of
type double, use this statement:
int balance[10];
Now balance is avariable array which is sufficient to hold upto 10 double numbers.
Initializing Arrays

You can initialize array in C either one by one or using a single statement as follows:

int balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};

The number of values between braces { } can not be larger than the number of elements that we
declare for the array between square brackets [ ].

If you omit the size of the array, an array just big enough to hold the initialization is created.
Therefore, if you write:

int balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};

You will create exactly the same array as you did in the previous example. Following is an example
to assign a single element of the array:

balance[4] = 50.0;

The above statement assigns element number 5th in the array with a value of 50.0. All arrays have 0
as the index of their first element which is also called base index and last index of an array will be
total size of the array minus 1. Following is the pictorial representation of the same array we
discussed above:

Accessing Array Elements


An element is accessed by indexing the array name. This is done by placing the index of the element
within square brackets after the name of the array. For example:

Int salary = balance[9];

The above statement will take 10th element from the array and assign the value to salary variable.
Following is an example which will use all the above mentioned three concepts viz. declaration,
assignment and accessing arrays:

#include <stdio.h>

void main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;

/* initialize elements of array n to 0 */


for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 100; /* set element at location i to i + 100 */
}

/* output each array element's value */


for (j = 0; j < 10; j++ )
{
printf("Element[%d] = %d\n", j, n[j] );
}

Getch();
}

When the above code is compiled and executed, it produces the following result:

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

Q24. WAP to print “HELLO”


Ans:]
/*Program to print hello*/
#include<stdio.h>
#include<conio.h>
Void main()
{
Printf(“HELLO”);
Getch();
}

Q25.WAP to find area of circle


Ans:
C program for area of circle
#include<conio.h>
#include <stdio.h>
#define PI 3.141
void main()
{
float r, a;
printf("Radius: ");
scanf("%f", &r);
a = PI * r * r;
printf("%f\n", a);
getch();
}

NOTE: Dear student please refer the class work note-book


for the program preparation
Q .25 What is function ? Explain different types of functions.
Ans : Types of C functions
Basically, there are two types of functions in C on basis of whether it is defined by user or not.
1. Library function
2. User defined function
 Library function
Library functions are the in-built function in C programming system. Function prototype and data
definitions of these functions are written in their respective header file. For example: If you want to
use printf() function, the header file <stdio.h> should be included. For example:
main(),printf(),scanf()
There are many library functions available in C programming to help the programmer to write a good
efficient program. you can find the square root by just using sqrt() function which is defined under
header file "math.h"Use Of Library Function To Find Square root.
#include <stdio.h>
#include <math.h>
void main()
{
float num,root;
printf("Enter a number to find square root.");
scanf("%f",&num);
root=sqrt(num); /* Computes the square root of num and stores in root. */
printf("Square root of %.2f=%.2f",num,root);
getch();
}

Library functions under "math.h"

Function Work of function

acos Computes arc cosine of the argument

acosh Computes hyperbolic arc cosine of the argument

asin Computes arc sine of the argument

asinh Computes hyperbolic arc sine of the argument


Library functions under "math.h"

Function Work of function

atan Computes arc tangent of the argument

atanh Computes hyperbolic arc tangent of the argument

atan2 Computes arc tangent and determine the quadrant using sign

cbrt Computes cube root of the argument

ceil Returns nearest integer greater than argument passed

cos Computes the cosine of the argument

cosh Computes the hyperbolic cosine of the argument

exp Computes the e raised to given power

fabs Computes absolute argument of floating point argument

floor Returns nearest integer lower than the argument passed.

hypot Computes square root of sum of two arguments (Computes hypotenuse)

log Computes natural logarithm

log10 Computes logarithm of base argument 10

pow Computes the number raised to given power

sin Computes sine of the argument

sinh Computes hyperbolic sine of the argument

sqrt Computes square root of the argument

tan Computes tangent of the argument

tanh Computes hyperbolic tangent of the argument

Library functions under "ctype.h"

Function Work Of Function

isalnum Tests whether a character is alphanumeric or not

isalpha Tests whether a character is aplhabetic or not

iscntrl Tests whether a character is control or not

isdigit Tests whether a character is digit or not

isgraph Tests whether a character is grahic or not


Library functions under "math.h"

Function Work of function

islower Tests whether a character is lowercase or not

isprint Tests whether a character is printable or not

ispunct Tests whether a character is punctuation or not

isspace Tests whether a character is white space or not

isupper Tests whether a character is uppercase or not

isxdigit Tests whether a character is hexadecimal or not

tolower Converts to lowercase if the character is in uppercase

toupper Converts to uppercase if the character is in lowercase

 User defined function


C provides programmer to define their own function according to their requirement known as user
defined functions.
Q.26 What is user-defined function? Explain.
User defined function: C provides programmer to define their own function according to their
requirement known as user defined functions.
Elements of function:
1.Function call
Control of the program cannot be transferred to user-defined function unless it is called invoked).
Syntax :function_name(argument(1),....argument(n));
In the above example, function call is made using statement add(num1,num2); from main(). This
make the control of program jump from that statement to function definition and executes the codes
inside that function.
2.Function declaration
Function prototype(declaration):
Every function in C programming should be declared before they are used. These type of declaration
are also called function prototype. Function prototype gives compiler information about function
name, type of arguments to be passed and return type.
Syntax of function prototype
return_type function_name(type(1) argument(1),....,type(n) argument(n));
In the above example,int add(int a, int b); is a function prototype which provides following
information to the compiler:
name of the function is add()
return type of the function is int.
two arguments of type int are passed to function.
Function prototype are not needed if user-definition function is written before main() function.
3.Function Definition
Function definition contains programming codes to perform specific task.
Syntax :
return_type function_name(type argument(1),..,type argument(n))
{
//body of function
}
Function definition has two major components:
1. Function header
Function header is the first line of function definition. When a function is invoked from calling
function, control of the program is transferred to function header or called function.
Syntax :
return_type function_name(type(1) argument(1),....,type(n) argument(n))
Syntax of function declaration and header are almost same except, there is no semicolon at the end of
header and function header is followed by function body.
In above example, int add(int a,int b) in line 12 is a function header.
2. Function body
Function header is followed by body of function which is composed of statements.
Passing arguments to functions
In programming, argument/parameter is a piece of data(constant or variable) passed from a program
to the function.
Return Statement
Return statement is used for returning a value from function definition to calling function.
Syntax of return statement
return (expression);
OR
return;
Syntax:
#include <stdio.h>
#include<conio.h>
void function_name()
{
................
................
}
int main(){
...........
...........
function_name();
...........
...........
}
Ex.1 A sample program of userdefined functions.
#include <stdio.h>
#include <conio.h>
void print(void);/*function declaration or function prototype*/
void main()
{
print(); /*Function call*/
getch();
}
void print() /*Function definition*/
{
printf("Welcome to c");
}
Ex.2 Write a C program to add two integers. Make a function add to add integers and display sum in
main() function.
/*Program to demonstrate the working of user defined function*/
#include <stdio.h>
int add(int a, int b); //function prototype(declaration)
int main(){
int num1,num2,sum;
printf("Enters two number to add\n");
scanf("%d %d",&num1,&num2);
sum=add(num1,num2); //function call
printf("sum=%d",sum);
return 0;
}
int add(int a,int b) //function header
{
/* Start of function definition. */
int add;
add=a+b;
return add; //return statement of function
/* End of function definition. */
}
Q .27 What are the advantages of user-defined function?
Advantages of user defined functions:
1.User defined functions helps to decompose the large program into small segments which makes
programmar easy to understand, maintain and debug.
2.If repeated code occurs in a program. Function can be used to include those codes and execute
when needed by calling that function.
3.Programmar working on large project can divide the workload by making different functions.

What are the different categories of functions in C Programming?


ANS: Depending on whether arguments are present or not and whether a value is returned or not, functions
are categorized into −
 Functions without arguments and without return values
 Functions without arguments and with return values
 Functions with arguments and without return values
 Functions with arguments and with return values

Functions without arguments and without return values

Example

#include<stdio.h>
main (){

void sum ();


clrscr ();
sum ();
getch ();

void sum (){


int a,b,c;

printf("enter 2 numbers:
");

scanf ("%d%d", &a, &b);


c = a+b;
printf("sum = %d",c);

Output
Enter 2 numbers:

5
Sum=8

Functions without arguments and with return values

Example

#include<stdio.h>
main (){

int sum ();


int c;

c= sum ();
printf(“sum = %d”,c);

getch ();

}
int sum (){
int a,b,c;
printf(“enter 2 numbers”);
scanf (“%d%d”, &a, &b);

c = a+b;
return c;

Output

Enter two numbers 10 20


30

Functions with arguments and without return values

Example

#include<stdio.h>
main (){
void sum (int, int );

int a,b;
printf("enter 2 numbers");

scanf("%d%d", &a,&b);
sum (a,b);

getch ();
}

void sum ( int a, int b){

int c;
c= a+b;
printf (“sum=%d”, c);

Output
Enter two numbers 10 20
Sum=30

Functions with arguments and with return values

Example

#include<stdio.h>

main (){
int sum ( int,int);
int a,b,c;
printf("enter 2 numbers");
scanf("%d%d", &a,&b);

c= sum (a,b);
printf ("sum=%d", c);

getch ();
}

int sum ( int a, int b ){

int c;
c= a+b;
return c;

Output
Enter two numbers 10 20

Sum=30
Q. 28.Differentiate between call by value and call by reference.

Call By Value Call By Reference

While calling a function, instead of passing


While calling a function, we pass the values of variables, we pass address of
values of variables to it. Such functions variables(location of variables) to the
are known as “Call By Values”. function known as “Call By References.

In this method, the value of each In this method, the address of actual
variable in calling function is copied variables in the calling function are copied
into corresponding dummy variables of into the dummy variables of the called
the called function. function.

With this method, the changes made to With this method, using addresses we
the dummy variables in the called would have an access to the actual
function have no effect on the values of variables and hence we would be able to
actual variables in the calling function. manipulate them.

// C program to illustrate // C program to illustrate


// call by value // Call by Reference

#include <stdio.h> #include <stdio.h>

// Function Prototype // Function Prototype


void swapx(int x, int y); void swapx(int*, int*);

// Main function // Main function


int main() int main()
{ {
int a = 10, b = 20; int a = 10, b = 20;

// Pass by Values // Pass reference


swapx(a, b); swapx(&a, &b);

printf("a=%d b=%d\n", a, b); printf("a=%d b=%d\n", a, b);


Call By Value Call By Reference

return 0; return 0;
} }

// Swap functions that swaps // Function to swap two variables


// two values // by references
void swapx(int x, int y) void swapx(int* x, int* y)
{ {
int t; int t;

t = x; t = *x;
x = y; *x = *y;
y = t; *y = t;

printf("x=%d y=%d\n", x, y); printf("x=%d y=%d\n", *x, *y);


} }

Output:
x=20 y=10
Output:
a=20 b=10
x=20 y=10
a=10 b=20

Thus actual values of a and b remain


unchanged even after exchanging the Thus actual values of a and b get changed
values of x and y. after exchanging values of x and y.

In call-by-values, we cannot alter the


values of actual variables through In call by reference we can alter the values
function calls. of variables through function calls.

Values of variables are passed by the Pointer variables are necessary to define to
Simple technique. store the address values of variables.
Q29. Write a program to swap (interchange) two numbers using call by reference.
/*C program to swap two number using call by reference */

#include <stdio.h>

/* Swap function declaration */


void swap(int * num1, int * num2);

int main()
{
int num1, num2;

/* Input numbers */
printf("Enter two numbers: ");
scanf("%d%d", &num1, &num2);

/* Print original values of num1 and num2 */


printf("Before swapping in main n");
printf("Value of num1 = %d \n", num1);
printf("Value of num2 = %d \n\n", num2);

/* Pass the addresses of num1 and num2 */


swap(&num1, &num2);

/* Print the swapped values of num1 and num2 */


printf("After swapping in main n");
printf("Value of num1 = %d \n", num1);
printf("Value of num2 = %d \n\n", num2);

return 0;
}

/*Function to swap two numbers */


void swap(int * num1, int * num2)
{
int temp;

// Copy the value of num1 to some temp variable


temp = *num1;

// Copy the value of num2 to num1


*num1= *num2;

// Copy the value of num1 stored in temp to num2


*num2= temp;

printf("After swapping in swap function n");


printf("Value of num1 = %d \n", *num1);
printf("Value of num2 = %d \n\n", *num2);
}
Q30. What is recursive function? OR What is recursion?
Ans: A function that calls itself is known as recursive function and the process of calling function
itself is known as recursion in C programming.
Ex 1. /* Program to calculate factorial of a number using recursion*/
#include<stdio.h>
int factorial (int n);
void main()
{
int n;
printf("Enter an positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, factorial(n));
getch();
}
int factorial(int n)
{
if(n==1)
return(1);
else
return n*factorial(n-1);
}
Output:
Enter an positive integer: 6
Factorial of 6 = 720
Ex.2 Program:Write a C program to find sum of first n natural numbers using recursion. Note:
Positive integers are known as natural number i.e. 1, 2, 3....n
#include <stdio.h>
int sum(int n);
int main(){
int num,add;
printf("Enter a positive integer:\n");
scanf("%d",&num);
add=sum(num);
printf("sum=%d",add);
}
int sum(int n){
if(n==0)
return n;
else
return n+sum(n-1); /*self call to function sum() */
}
Output
Enter a positive integer:
5
15
In, this program, sum() function is invoked from the same function. If n is not equal to 0 then, the
function calls itself passing argument 1 less than the previous argument it was called with. Suppose, n
is 5 initially. Then, during next function calls, 4 is passed to function and the value of argument
decreases by 1 in each recursive call. When, n becomes equal to 0, the value of n is returned which is
the sum numbers from 5 to 1.
For better visualization of recursion in this example:
sum(5)
=5+sum(4)
=5+4+sum(3)
=5+4+3+sum(2)
=5+4+3+2+sum(1)
=5+4+3+2+1+sum(0)
=5+4+3+2+1+0
=5+4+3+2+1
=5+4+3+3
=5+4+6
=5+10
=15
Every recursive function must be provided with a way to end the recursion. In this example when, n
is equal to 0, there is no recursive call and recursion ends.
Q31 What are the advantages and disadvantages of recursion?
Ans:Advantages and Disadvantages of Recursion
Recursion is more elegant and requires few variables which make program clean. Recursion can be
used to replace complex nesting code by dividing the problem into same problem of its sub-type.
In other hand, it is hard to think the logic of a recursive function. It is also difficult to debug the code
containing recursion.
Q.9 Write a program in C to Calculate Factorial of a Number Using Recursion
/* Program to calculate factorial of a number using recursion*/
#include<stdio.h>
int factorial (int n);
void main()
{
int n;
printf("Enter an positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, factorial(n));
getch();
}
int factorial(int n)
{
if(n!=1)
return n*factorial(n-1);
}
Output
Enter an positive integer: 6
Factorial of 6 = 720
Q.10 Write a program to generate Fibonacci series using recursion in c
#include<stdio.h>
void Fibonacci(int);
int main()
{
int k,n;
long int i=0,j=1,f;
printf("Enter the range of the Fibonacci series: ");
scanf("%d",&n);
printf("Fibonacci Series: ");
printf("%d %d ",0,1);
Fibonacci(n);
return 0;
}
void Fibonacci(int n)
{
static long int first=0,second=1,sum;
if(n>0)
{
sum = first + second;
first = second;
second = sum;
printf("%ld ",sum);
Fibonacci(n-1);
}

}
output:
Enter the range of the Fibonacci series: 10
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34 55 89
Q.11.Explain the different storage classes in ‘C’.
Ans: Every variable and function in C programming has two properties: type and storage class. Type
refers to the data type of variable whether it is character or integer or floating-point value etc.
There are 4 types of storage class:
1.automatic
2.External
3.static
4.register
 Automatic storage class
Variables declared inside the function body are automatic by default. These variable are also known
as local variables as they are local to the function and doesn't have meaning outside that function
Since, variable inside a function is automatic by default, keyword auto is rarely used.
eg. int n;
 External storage class
External variable can be accessed by any function. They are also known as global variables.
Variables declared outside every function are external variables.
In case of large program, containing more than one file, if the global variable is declared in file 1 and
that variable is used in file 2 then, compiler will show error. To solve this problem, keyword extern is
used in file 2 to indicate that, the variable specified is global variable and declared in another file.
Example to demonstrate working of external variable
#include<stdio.h>
void Check();
int a=5; /* a is global variable because it is outside every function */
int main()
{
a+=4;/* same as a=a+4*/
Check();
return 0;
}
void Check()
{
++a; /* ----- Variable a is not declared in this function but, works in any function as they are
global variable ------- */
printf("a=%d\n",a);
}
Output
a=10
 Register Storage Class
register int a;
Register variables are similar to automatic variable and exists inside that particular function only.
If the compiler encounters register variable, it tries to store variable in microprocessor's register
rather than memory. Value stored in register are much faster than that of memory.
In case of larger program, variables that are used in loops and function parameters are declared
register variables.eg. for(i=1;i<=10;i++)
Since, there are limited number of register in processor and if it couldn't store the variable in register,
it will automatically store it in memory.
 Static Storage Class
The value of static variable persists until the end of the program. A variable can be declared static
using keyword: static. For example:
static int i;
Here, i is a static variable.
Example to demonstrate the static variable
#include <stdio.h>
void Check();
int main(){
Check();
Check();
Check();
}
void Check(){
static int count=0;
printf("%d\t",count);
count+=5;
}
Output
0 5 10
During first function call, it will display 0. Then, during second function call, variable c will not be
initialized to 0 again, as it is static variable. So, 5 is displayed in second function call and 10 in third
call.
If variable c had been automatic variable, the output would have been:
0 0 0
Q.32 Explain how you can define the data by using ‘typedef’ statement ?Give the suitable
example.
Ans: Typedef is used to define new data type for an existing data type. It provides an alternative
name for standard data type. It is used for self documenting the code by allowing descriptive names.
(for belter understanding) for the standard data type. The C programming language provides a
keyword called typedef, which you can use to give a type a new name.
The general format is:
typedef existing datatype new datatype;
For example:
typedef float real;
Now, in a program one can use datatype real instead of float.
Therefore, the following statement is valid:
real amount;
After this type definitions, the identifier BYTE can be used as an abbreviation for the type unsigned
char, for example:.
By convention, uppercase letters are used for these definitions to remind the user that the type name
is really a symbolic abbreviation, but you can use lowercase, as follows:
typedef unsigned char byte;
You can use typedef to give a name to user defined data type as well. For example you can use
typedef with structure to define a new data type and then use that data type to define structure
variables directly as follows:
// Structure using typedef:
#include <stdio.h>
#include <string.h>
typedef struct student
{
int id;
char name[20];
float percentage;
} status;
int main()
{
status record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
return 0;
}
Q.33 Explain in brief the use of enumerated data types with example
Ans: Enumerated Data Type
It has the following features:
It is user defined.
It works if you know in advance a finite list of values that a data type can take.
The list cannot be input by the user or output on the screen.
For example:
enum months { jan, feb, mar, apr, may};
enum days { sun, mon, tue, wed, thu };
enum toys { cycle, bicycle, scooter };
The enum specifier defines the set of all names that will be permissible values of
the type called members which are stored internally as integer constant. The first
name was given the integer value 0, the second value 1 and so on.
Program
#include< stdio.h>
void main()
{
int i;
enum month {JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,DEC};
clrscr();
for(i=JAN;i<=DEC;i++)
printf("\n%d",i);
}
Output :
01234567891011
Q34 Explain in brief arithmetic operations perform on pointers.OR pointer arithmetic.
Ans:You can perform a limited number of arithmetic operations on pointers. These operations are:
Increment and decrement
Addition and subtraction
Comparison
Assignment
The increment (++) operator increases the value of a pointer by the size of the data object the pointer
refers to. For example, if the pointer refers to the second element in an array, the ++ makes the
pointer refer to the third element in the array.
The decrement (--) operator decreases the value of a pointer by the size of the data object the pointer
refers to. For example, if the pointer refers to the second element in an array, the -- makes the pointer
refer to the first element in the array.
You can add an integer to a pointer but you cannot add a pointer to a pointer.
If the pointer p points to the first element in an array, the following expression causes the pointer to
point to the third element in the same array:
p = p + 2;
If you have two pointers that point to the same array, you can subtract one pointer from the other.
This operation yields the number of elements in the array that separate the two addresses that the
pointers refer to.
You can compare two pointers with the following operators: ==, !=, <, >, <=, and >=.
Program to illustrate the use of pointers in arithmetic operations in C Programming
main()
{
int a, b, *p1, *p2, x, y, z;
a = 12;
b = 4;
p1 = &a;
p2 = &b;
x = *p1 * *p2 - 6;
y = 4* - *p2 / *p1 + 10;
printf("Address of a = %u\n", p1);
printf("Address of b = %u\n", p2);
printf("\n");
printf("a = %d, b = %d\n", a, b);
printf("x = %d, y = %d\n", x, y);
*p2 = *p2 + 3;
*p1 = *p2 - 5;
z = *p1 * *p2 - 6;
printf("\na = %d, b = %d,", a, b);
printf(" z = %d\n", z);
}
Output :
Address of a = 4020
Address of b = 4016
a = 12, b = 4
x = 42, y = 9
a = 2, b = 7, z = 8
Q35 Write a C program to create a file called emp.rec and store information
about a person(File handling)
Ans: /*C program to create a file called emp.rec and store information
about a person, in terms of his name, age and salary.*/
#include <stdio.h>
void main()
{
FILE *fp;
char name[20];
int age;
float salary;

/* open for writing */


fp = fopen("emp.rec", "w");
if (fp == NULL)
{
printf("File does not exists \n");
return;
}
printf("Enter the name \n");
scanf("%s", name);
fprintf(fp, "Name = %s\n", name);
printf("Enter the age\n");
scanf("%d", &age);
fprintf(fp, "Age = %d\n", age);
printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fp, "Salary = %.2f\n", salary);
fclose(fp);
}
Output:
Enter the name
raj
Enter the age
40
Enter the salary
4000000
Q.36 What is a structure ? Explain.
OR
What is the syntax of accessing data members of the structure?
Ans: Structure is the collection of variables of different types under a single name for better handling.
For example: You want to store the information about person about his/her name, citizenship number
and salary. You can create these information separately but, better approach will be collection of
these information under single name because all these information are related to person.
Keyword struct is used for creating a structure.
Syntax of structure
struct structure_name
{ data_type member1;
data_type member2;
.
.
data_type memeber;
};
We can create the structure for a person as mentioned above as:
struct person
{
char name[50];
int cit_no;
float salary;
};
This declaration above creates the derived data type struct person.
Structure variable declaration
When a structure is defined, it creates a user-defined type but, no storage is allocated. For the above
structure of person, variable can be declared as:
struct person
{
char name[50];
int cit_no;
float salary;
};
void main()
{ /*Inside main function*/
struct person p1, p2, p[20];
}
Another way of creating sturcture variable is:
struct person
{
char name[50];
int cit_no;
float salary;
}p1 ,p2 ,p[20];
In both cases, 2 variables p1, p2 and array p having 20 elements of type struct person are created.
Accessing members of a structure
There are two types of operators used for accessing members of a structure.
Member operator(.)
Structure pointer operator(->)
Any member of a structure can be accessed as: structure_variable_name.member_name
Suppose, we want to access salary for variable p2. Then, it can be accessed as:p2.salary
Example of structure 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 number: %d\n",s.roll);
printf("Marks: %.2f\n",s.marks);
return 0;
}
Output:
Enter information of students:
Enter name:Neha
Enter roll number:5
Enter marks:85.2
Displaying information
Name:Neha
Roll number:5
Marks:85.2
Q37 What is array of structure? Explain with example.
Ans: Structure is used to store information of one particular object but if we need to store information
of number of objects then array of structure is used.
Example to Store Information of 10 students Using array of Structure
#include <stdio.h>
struct student{
char name[50];
int roll;
float marks;
};
void main()
{
struct student s[10];
int i;
printf("Enter information of students:\n");
for(i=1;i<=10;i++)
{
printf("\nFor roll number %d\n",i);
printf("Enter name: ");
scanf("%s",s[i].name);
printf("Enter marks: ");
scanf("%f",&s[i].marks);
printf("\n");
}
printf(" Displaying information of students:\n\n");
for(i=1;i<=10;i++)
{
printf("\n Information for roll number %d:\n",i);
printf("Name: ");
puts(s[i].name);
printf("Marks: %.1f",s[i].marks);
}
getch();
}
Output
Enter information of students:
For roll number 1
Enter name: Sneha
Enter marks: 98
For roll number 2
Enter name: Varsha
Enter marks: 89
.
.
.
Displaying information of students:
Information for roll number 1:
Name: Sneha
Marks: 98
.
.
Q37 How is structure different from array? OR Differentiate between structure and array.
Ans: Both the arrays and structures are classified as structured data types as they provide a
mechanism that enable us to access and manipulate data in a relatively easy manner. But they differ
in a number of ways listed in table below:

Arrays Structures

1. An array is a collection of related 1. Structure can have elements of


data elements of same type. different types

2. An array is a derived data type 2. A structure is a programmer-defined


data type

3. Any array behaves like a built-in 3. But in the case of structure, first we
data types. All we have to do is to have to design and declare a data
declare an array variable and use it. structure before the variable of that
type are declared and used.

4.Array allocates static memory and 4.Structures allocate dynamic memory


uses index / subscript for accessing and uses (.) operator for accessing the
elements of the array. member of a structure.

5.Array is a base pointer.. 5.Structure is not a pointer


** it points to a particular memory
location..

Q38 What is nesting of structure? OR structure within structure.


Ans: Structures can be used as structures within structures. It is also called as 'nesting of structures'.
Syntax:
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
-----------
-----------
<data-type> element n;

struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
-----------
-----------
<data-type> element n;
}inner_struct_var;
}outer_struct_var;
Example :
struct stud_Res
{
int rno;
char nm[50];
char std[10];

struct stud_subj
{
char subjnm[30];
int marks;
}subj;
}result;
In above example, the structure stud_Res consists of stud_subj which itself is a structure with two
members. Structure stud_Res is called as 'outer structure' while stud_subj is called as 'inner structure.'
The members which are inside the inner structure can be accessed as follow :
result.subj.subjnm
result.subj.marks
/* Program to demonstrate nested structures.
#include <stdio.h>
#include <conio.h>
struct stud_Result
{
int rno;
char std[10];
struct stud_Marks
{
char subj_nm[30];
int subj_mark;
}marks;
}res;

void main()
{
clrscr();
printf("\n\t Enter Roll Number : ");
scanf("%d",&res.rno);
printf("\n\t Enter Standard : ");
scanf("%s",res.std);
printf("\n\t Enter Subject Code : ");
scanf("%s",result.marks.subj_nm);
printf("\n\t Enter Marks : ");
scanf("%d",&result.marks.subj_mark);
printf("\n\n\t Roll Number : %d",res.rno);
printf("\n\n\t Standard : %s",res.std);
printf("\nSubject Code : %s",res.marks.subj_nm);
printf("\n\n\t Marks : %d",res.marks.subj_mark);
getch();
}
Output :
Enter Roll Number : 1
Enter standard : B.Sc(CS)-I
Enter subject code : CS01
Enter marks : 80
Roll Number : 1
Standard : B.Sc(CS)-I
Subject code : CS01
Q.39 What is union? Explain.
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 in very similar was as you did while defining
structure. The union statement defines a new data type, with more than one member for your
program. The format of the union statement is as follows:
union <union tag>
{
member definition;
member definition;
...
member definition;
} [one or more union variables];
Ex. 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.
This means that a single variable ie. same memory location can be used to store multiple types of
data.
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. You would use union keyword to define variables of union type. Following is the example to
explain usage of union:
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. Following is the example which will
display total memory size occupied by the above union:
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
void main( )
{
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
getch();
}
Q.40 What is the difference Between Stucture and Union

Structure Union
i. Access Members
We can access all the members of structure at
Only one member of union can be accessed at anytime.
anytime.
ii. Memory Allocation
Allocates memory for variable which variable require
Memory is allocated for all variables.
more memory.
iii. Initialization
All members of structure can be initialized Only the first member of a union can be initialized.
iv. Keyword
'struct' keyword is used to declare structure. 'union' keyword is used to declare union.
v. Syntax
struct struct_name union union_name
{ {
structure element 1; union element 1;
structure element 2; union element 2;
---------- ----------
---------- ----------
structure element n; union element n;
}struct_var_nm; }union_var_nm;
vi. Example
struct item_mst union item_mst
{ {
int rno; int rno;
char nm[50]; char nm[50];
}it; }it;
OR
Difference Between Stucture and Union
BASIS OF
STRUCTURE UNION
COMPARISON

Basic The separate memory location is All members of the 'union'

allotted to each member of the share the same memory

'structure'. location.

Declaration struct struct_name{ union u_name{

type element1; type element1;

type element2; type element2;

. .

. .

} variable1, variable2, ...; } variable1, variable2, ...;

keyword 'struct' 'union'

Size Size of Structure= sum of size of all the Size of Union=size of the

data members. largest members.

Store Value Stores distinct values for all the Stores same value for all the

members. members.

At a Time A 'structure' stores multiple values, of A 'union' stores a single value

the different members, of the at a time for all members.


BASIS OF
STRUCTURE UNION
COMPARISON

'structure'.

Way of Viewing Provide single way to view each Provide multiple way to to

memory location. view same memory location.

Anonymous feature No Anonymous feature. Anonymous union can be

declared.
Q.41 What are the different modes of files(File modes)?
Ans :The file modes are as follows,

Mode Description

r Opens an existing text file for reading purpose.

Opens a text file for writing, if it does not exist then a new file is created.
w
Here your program will start writing content from the beginning of the file.

Opens a text file for writing in appending mode, if it does not exist then a new
a file is created. Here your program will start appending content in the existing
file content.

r+ Opens a text file for reading and writing both.

Opens a text file for reading and writing both. It first truncate the file to zero
w+
length if it exists otherwise create the file if it does not exist.

Opens a text file for reading and writing both. It creates the file if it does not
a+ exist. The reading will start from the beginning but writing can only be
appended.

Q.42. Explain the following string handling functions:


i)strlen()
II)strcpy()
III)strcat()
IV)strupr()
V)strlwr()

VI)Strcmp():Comparison occurs between a first string (str1) with a second string (str2).

On comparing the two string, the values return by a function strcmp() are:

o If, str1 is equal to str2 then Return value = 0


o If, str1 is greater than str2 then Return value > 0
o If, str1 is less than str2 then Return value < 0

#include<stdio.h>
#include <string.h>
int main(){
char str1[20],str2[20];
printf("Enter 1st string: ");
gets(str1);//reads string from console
printf("Enter 2nd string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
}

Q.43 What is Type casting?


Ans: Type casting is a way to convert a variable from one data type to another data type. For
example, if you want to store a 'long' value into a simple integer then you can type cast 'long' to 'int'.
You can convert the values from one type to another explicitly using the cast operator as follows −
(type_name) expression
Consider the following example where the cast operator causes the division of one integer variable by
another to be performed as a floating-point operation −
#include <stdio.h>
main() {
int sum = 17, count = 5;
double mean;
mean = (double) sum / count;
printf("Value of mean : %f\n", mean );
}

When the above code is compiled and executed, it produces the following result −
Value of mean : 3.400000
It should be noted here that the cast operator has precedence over division, so the value of sum is first
converted to type double and finally it gets divided by count yielding a double value.
Type conversions can be implicit which is performed by the compiler automatically, or it can be
specified explicitly through the use of the cast operator. It is considered good programming practice
to use the cast operator whenever type conversions are necessary.
Q.44 Write a program to accept an integer value. Pass this value to two functions - one to
compute square value, and the other to compute cube value.
#include <stdio.h>
int square(int);
int cube(int);
int main()
{
int a;
printf("Enter a number :");
scanf("%d",&a);
int b=square(a);
printf("\nSquare= %d",b);
b=cube(a);
printf("\nCube= %d",b);
getch();
}
int square(int x)
{
return x*x;
}
int cube(int x)
{
return x*x*x;
}
Q.45 Explain ‘C’ PREPROCESSOR DIRECTIVES:
Ans: ‘C’ Preprocessor Directives
Before a C program is compiled in a compiler, source code is processed by a program called
preprocessor. This process is called preprocessing.
Commands used in preprocessor are called preprocessor directives and they begin with “#” symbol.
Below is the list of preprocessor directives that C programming language offers.

Preprocesso
r Syntax/Description

Syntax: #define
This macro defines constant value and can be any of the basic data types.

1. #include <stdio.h>
2. #define MIN(a,b) ((a)<(b)?(a):(b))
3. void main() { printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));
4. }
Macro

Syntax: #include <file_name>


Header file The source code of the file “file_name” is included in the main program at the
inclusion specified place.

Conditional Syntax: #ifdef, #endif, #if, #else, #ifndef


compilation Set of commands are included or excluded in source program before compilation
with respect to the condition.

Syntax: #undef, #pragma


Other #undef is used to undefine a defined macro variable. #Pragma is used to call a
directives function before and after main function in a C program.

Q.46. Explain the following


1. #define
You can define a macro in C using #define preprocessor directive.
A macro is a fragment of code that is given a name. You can use that fragment of code in your
program by using the name. For example,
#define c 299792458 // speed of light
Here, when we use c in our program, it's replaced by 3.1415.
Example 1: Using #define preprocessor
#include <stdio.h>
#define PI 3.1415
int main()
{
float radius, area;
printf("Enter the radius: ");
scanf("%d", &radius);
// Notice, the use of PI
area = PI*radius*radius;
printf("Area=%.2f",area);
return 0;
}
2.#ifdef Directive
#ifdef MACRO
conditional codes
#endif
Q.47 .What is the difference between text files and binary files?
Ans: All files can be categorized into one of two file formats — binary or text. The two file types
may look the same on the surface, but they encode data differently. While both binary and text files
contain data stored as a series of bits (binary values of 1s and 0s), the bits in text files represent
characters, while the bits in binary files represent custom data.
Text Files: While text files contain only textual data, binary files may contain both textual and
custom binary data.
Text files are more restrictive than binary files since they can only contain textual data. However,
unlike binary files, they are less likely to become corrupted. While a small error in a binary file may
make it unreadable, a small error in a text file may simply show up once the file has been opened.
Binary Files
Binary files typically contain a sequence of bytes, or ordered groupings of eight bits. When creating a
custom file format for a program, a developer arranges these bytes into a format that stores the
necessary information for the application. Binary file formats may include multiple types of data in
the same file, such as image, video, and audio data. This data can be interpreted by supporting
programs, but will show up as garbled text in a text editor. Below is an example of a .PNG image file
opened in an image viewer and a text editor.
Q.48. Explain following Binary functions
1)Fread()
2) fwrite()
There are two functions, that can be used for binary input and output −
size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);
size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);
Both of these functions should be used to read or write blocks of memories - usually arrays or
structures. The functions fread/fwrite are used for reading/writing data from/to the file opened by
fopen function. These functions accept three arguments. The first argument is a pointer to buffer used
for reading/writing the data. The data read/written is in the form of ‘nmemb’ elements each ‘size’
bytes long.In case of success, fread/fwrite return the number of bytes actually read/written from/to
the stream opened by fopen function. In case of failure, a lesser number of byes (then requested to
read/write) is returned.

rewind() function

The rewind() function sets the file pointer at the beginning of the stream. It is useful if you have to
use stream many times.

Syntax:

void rewind(FILE *stream)

File: file.txt

this is a simple text

File: rewind.c
fclose(fp);

#include<stdio.h>

#include<conio.h>

void main()

FILE *fp;

char c;

clrscr();

fp=fopen("file.txt","r");

while((c=fgetc(fp))!=EOF){

printf("%c",c);

rewind(fp);/*moves the file pointer at beginning of the file */

while((c=fgetc(fp))!=EOF){

printf("%c",c);

getch();

Output:

this is a simple textthis is a simple text

As you can see, rewind() function moves the file pointer at beginning of the file that is why "this is
simple text" is printed 2 times. If you don't call rewind() function, "this is simple text" will be printed
only once.

ftell() function

The ftell() function returns the current file position of the specified stream. We can use ftell()
function to get the total size of a file after moving file pointer at the end of file. We can use
SEEK_END constant to move the file pointer at the end of file.

Syntax:long int ftell(FILE *stream)


#include <stdio.h>

#include <conio.h>

void main (){

FILE *fp;

int length;

clrscr();

fp = fopen("file.txt", "r");

fseek(fp, 0, SEEK_END);

length = ftell(fp);

fclose(fp);

printf("Size of file: %d bytes", length);

getch();

Output:

Size of file: 21 bytes

C fseek() function

The fseek() function is used to set the file pointer to the specified offset. It is used to write data into
file at desired location.

Syntax:

1. int fseek(FILE *stream, long int offset, int whence)

There are 3 constants used in the fseek() function for whence: SEEK_SET, SEEK_CUR and
SEEK_END.

#include <stdio.h>

void main(){

FILE *fp;
fp = fopen("myfile.txt","w+");

fputs("This is a pleasant Morning", fp);

fseek( fp, 7, SEEK_SET );

fputs("Sanjeev Kapoor", fp);

fclose(fp);

myfile.txt

This is Sanjeev Kapoor

You might also like