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

C Programming

This document discusses C programming language. It defines C as a high-level, general-purpose programming language ideal for developing firmware or portable applications. It was originally developed at Bell Labs for the Unix operating system. The document then lists some important features of C like keywords, operators, and modularity. It also discusses how C programs are compiled and executed. Several popular C compilers are listed. Finally, the document covers applications of C, advantages, and disadvantages.

Uploaded by

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

C Programming

This document discusses C programming language. It defines C as a high-level, general-purpose programming language ideal for developing firmware or portable applications. It was originally developed at Bell Labs for the Unix operating system. The document then lists some important features of C like keywords, operators, and modularity. It also discusses how C programs are compiled and executed. Several popular C compilers are listed. Finally, the document covers applications of C, advantages, and disadvantages.

Uploaded by

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

Aditya Kumar, Asst. Professor, Mobile No.

8791178099
Unit-1

Q1. Define C language, its features and also discuss its advantages and disadvantages?
Ans. C is a high-level and general-purpose programming language that is ideal for developing
firmware or portable applications. Originally intended for writing system software, C was developed at
Bell Labs by Dennis Ritchie for the Unix Operating System in the early 1970s.

C belongs to the structured, procedural paradigms of languages. It is proven, flexible and powerful
and may be used for a variety of different applications. Although high level, C and assembly language
share many of the same attributes.

c एक उच्च-स्तरीय और सामान्य-उद्देश्य वाली प्रोग्रामिंग भाषा है जो फर्मवेयर या पोर्टेबल अनुप्रयोगों को विकसित करने के
लिए आदर्श है । मूल रूप से सिस्टम सॉफ्टवेयर लिखने के लिए सी, डेनिस रिची द्वारा 1970 के दशक के प्रारं भ में यूनिक्स
ऑपरे टिग
ं सिस्टम के लिए बेल लैब्स में विकसित किया गया था।

Some of C's most important features include:

 Fixed number of keywords, including a set of control primitives, such as if, for, while, switch
and do while

 Multiple logical and mathematical operators, including bit manipulators

 Multiple assignments may be applied in a single statement.

 Function return values are not always required and may be ignored if unneeded.

 Typing is static. All data has type but may be implicitly converted.

 Basic form of modularity, as files may be separately compiled and linked

 Control of function and object visibility to other files via extern and static attributes

How 'C' Works?

C is a compiled language. A compiler is a special tool that compiles the program and converts it into
the object file which is machine readable. After the compilation process, the linker will combine
different object files and creates a single executable file to run the program. The following diagram
shows the execution of a 'C' program

सी एक संकलित भाषा है । एक कंपाइलर एक विशेष उपकरण है जो प्रोग्राम को संकलित करता है और इसे ऑब्जेक्ट
फ़ाइल में परिवर्तित करता है जो मशीन पठनीय है । संकलन प्रक्रिया के बाद, लिंकर विभिन्न ऑब्जेक्ट फ़ाइलों को
संयोजित करे गा और प्रोग्राम को चलाने के लिए एक single execution योग्य फ़ाइल बनाता है ।
Aditya Kumar, Asst. Professor, Mobile No. 8791178099

Nowadays, various compilers are available online, and you can use any of those compilers. The
functionality will never differ and most of the compilers will provide the features required to execute
both 'C' and 'C++' programs.

Following is the list of popular compilers available online:

 Clang compiler
 MinGW compiler (Minimalist GNU for Windows)
 Portable 'C' compiler
 Turbo C

Applications of c programming
1. 'C' language is widely used in embedded systems.
2. It is used for developing system applications.
3. It is widely used for developing desktop applications.
4. Most of the applications by Adobe are developed using 'C' programming language.
5. It is used for developing browsers and their extensions. Google's Chromium is built using 'C'
programming language.
6. It is used to develop databases. MySQL is the most popular database software which is built
using 'C'.
7. It is used in developing an operating system. Operating systems such as Apple's OS X,
Microsoft's Windows, and Symbian are developed using 'C' language. It is used for developing
desktop as well as mobile phone's operating system.
8. It is used for compiler production.
9. It is widely used in IOT applications.

Advantages of C Language
1. C language is a building block for many other currently known languages. C language has
variety of data types and powerful operators. Due to this, programs written in C language are
efficient, fast and easy to understand.
2. C is highly portable language. This means that C programs written for one computer can
easily run on another computer without any change or by doing a little change.
3. There are only 32 keywords in ANSI C and its strength lies in its built-in functions. Several
standard functions are available which can be used for developing programs.
4. Another important advantage of C is its ability to extend itself. A C program is basically a
collection of functions that are supported by the C library this makes us easier to add our own
functions to C library. Due to the availability of large number of functions, the programming
task becomes simple.
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
5. C language is a structured programming language. This makes user to think of a problem in
terms of function modules or blocks. Collection of these modules makes a complete program.
This modular structure makes program debugging, testing and maintenance easier.

Disadvantages of C Language
1. C does not have concept of OOPs, that’s why C++ is developed.
2. There is no runtime checking in C language.
3. There is no strict type checking. For example, we can pass an integer value.
4. For the floating data type.
5. C doesn’t have the concept of namespace.
6. C doesn’t have the concept of constructor or destructor.

Q2. What are identifiers and keywords explain it with suitable example?
Ans: Identifier refers to name given to entities such as variables, functions, structures etc.

Identifiers must be unique. They are created to give a unique name to an entity to identify it during the
execution of the program.

For example:

int money;
double accountBalance;
Here, money and accountBalance are identifiers.

Also remember, identifier names must be different from keywords. You cannot use int as an identifier
because int is a keyword.

Rules for naming identifiers

1. A valid identifier can have letters (both uppercase and lowercase letters), digits and underscores.
2. The first letter of an identifier should be either a letter or an underscore.
3. You cannot use keywords as identifiers.
4. There is no rule on how long an identifier can be. However, you may run into problems in some
compilers if the identifier is longer than 31 characters.

You can choose any name as an identifier if you follow the above rule, however, give meaningful
names to identifiers that make sense. 

Keywords are specific reserved words in C each of which has a specific feature associated with it.
Almost all of the words which help us use the functionality of the C language are included in the list of
keywords. So you can imagine that the list of keywords is not going to be a small one!
There are a total of 32 keywords in C:
auto break case char const continue
default do double else enum extern
float for goto if int long
register return short signed sizeof static
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
struct switch typedef union unsigned void
volatile while

Difference between Keyword and Identifier


BASIS FOR
COMPARISO KEYWORD IDENTIFIER
N

Basic Keywords are the reserved words of a Identifiers are the user defined names of
language. variable, function and labels.

Use Specify the type/kind of entity. Identify the name of a particular entity.

Format Consider only letters. Consider letters, underscore, digits.

Case Use only lowercase. Lower and upper cases, both are allowed.

Symbol No special symbol, punctuation is used. No punctuation or special symbol except


'underscore' is used.

Classification Keywords are not further classified. Identifier are classified into 'external
name' and 'internal name'.

Starting letter It always starts with a lowercase letter. First character can be a uppercase,
lowercase letter or underscore.

Example int, char, if, while, do, class etc. Test, count1, high_speed, etc.

Q3. What is data type and explain their types?

Ans. A data type is a type of data. Of course, that is rather circular definition, and also not very
helpful. Therefore, a better definition of a 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. Some common data types include integers, floating point numbers, and characters.
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
 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.

 Size of variable, constant and array are determined by data types.

C – DATA TYPES:
There are four data types in C language. They are,

Types Data Types

Basic data types int, char, float, double

Enumeration data type enum

Derived data type pointer, array, structure, union

Void data type void


BASIC DATA TYPES IN C LANGUAGE:

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 datatype.
 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.
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
FLOATING POINT DATA TYPE:
Floating point data type consists of 2 types. They are,
 float
 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 datatype is from 1E–37 to 1E+37.

ENUMERATION DATA TYPE IN C LANGUAGE:


 Enumeration data type consists of named integer constants as a list.
 It start with 0 (zero) by default and value is incremented by 1 for the sequential identifiers in the
list.
 Enum syntax in C:
enum identifier [optional{ enumerator-list }];
 Enum example in C: 

enum month { Jan, Feb, Mar }; or


/* Jan, Feb and Mar variables will be assigned to 0, 1 and 2 respectively by default */
enum month { Jan = 1, Feb, Mar };
/* Feb and Mar variables will be assigned to 2 and 3 respectively by default */
enum month { Jan = 20, Feb, Mar };
/* Jan is assigned to 20. Feb and Mar variables will be assigned to 21 and 22 respectively by
default */

DERIVED DATA TYPE IN C LANGUAGE:


 Array, pointer, structure and union are called derived data type in C language.
 To know more about derived data types, please visit “C – Array” , “C – Pointer” , “C –
Structure” and “C – Union” topics in this tutorial.
4. VOID DATA TYPE IN C LANGUAGE:
 Void is an empty data type that has no value.
 This can be used in functions and pointers.
 Please visit “C – Function” topic to know how to use void data type in function with simple call
by value and call by reference example programs.

Q4. What is variable and constant with example?


Ans: Variables
In programming, a variable is a container (storage area) to hold data.To indicate the storage area,
each variable should be given a unique name (identifier). Variable names are just the symbolic
representation of a memory location.
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
प्रोग्रामिंग में , वेरिएबल नाम डेटा रखने के लिए एक स्टोरे ज एरिया है । स्टोरे ज क्षेत्र को इंगित करने के लिए, प्रत्येक
वेरिएबल को एक विशिष्ट नाम दिया जाना चाहिए। वेरिएबल नाम केवल एक स्मति
ृ स्थान का प्रतीकात्मक प्रतिनिधित्व
है ।

For example:

int playerScore = 95;

Here, playerScore is a variable of int type. Here, the variable is assigned an integer value 95.The


value of a variable can be changed, hence the name variable.

char ch = 'a';

// some code
ch = 'l';

Rules for naming a variable


1. A variable name can have only letters (both uppercase and lowercase letters), digits and
underscore.
2. The first letter of a variable should be either a letter or an underscore.
3. There is no rule on how long a variable name (identifier) can be. However, you may run into
problems in some compilers if the variable name is longer than 31 characters.

Constants
If you want to define a variable whose value cannot be changed, you can use the const keyword. This
will create a constant. For example,

const double PI = 3.14;


Notice, we have added keyword const.
Here, PI is a symbolic constant; its value cannot be changed.
const double PI = 3.14;
PI = 2.9; //Error

A symbol which has a fixed numerical value is called a constant.

For example:

2, 5, 0, -3, -7, 2/7, 7/9 etc., are constants.

Number of days in a week represents a constant.

In the expression 5x + 7, the constant term is 7.

Examples on Constants and Variables:


Aditya Kumar, Asst. Professor, Mobile No. 8791178099
(i) In 2a, 2 is a constant and a is a variable.

(ii) In -7mn, -7 is a constant and m and n are variables.

(iii) In 3x, 3 is constant and x is variable but together 3x is a variable.

(iv) If 3 is a constant and x is a variable, then 3 + x, 3 - x, 3/x, 3x, x/3, etc., are also variables.

So, we conclude that the combination of a constant and a variable is always a variable.

Q5. What are different types of operators in C?

Ans: Operators are the symbols which tell the computer to execute certain mathematical or logical
operations.  A mathematical or logical expression is generally formed with the help of an operator. C
programming offers a number of operators which are classified into 7 categories viz.

ऑपरे टर वे प्रतीक हैं जो कंप्यट


ू र को कुछ गणितीय या तार्कि क कार्यों को निष्पादित करने के लिए कहते हैं। एक गणितीय
या तार्कि क अभिव्यक्ति आम तौर पर एक ऑपरे टर की मदद से बनाई जाती है । C प्रोग्रामिंग कई ऑपरे टरों को प्रदान
करता है जिन्हें 7 श्रेणियों में वर्गीकृत किया गया है
1. Arithmetic operators
2. Relational operators / Logical operators
3. Bitwise operators
4. Assignment operators
5. Increment and Decrement operators
6. Conditional operators
7. Special operators

1. Arithmetic operators

There are following arithmetic operators supported by C language:

Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example

+
Adds two operands A + B will give 30

-
Subtracts second operand from the first A - B will give -10

*
Multiply both operands A * B will give 200
Aditya Kumar, Asst. Professor, Mobile No. 8791178099

/
Divide numerator by denumerator B / A will give 2

% Modulus Operator and remainder of after an integer


B % A will give 0
division

++
Increment operator, increases integer value by one A++ will give 11

--
Decrement operator, decreases integer value by one A-- will give 9

2. Relational/Logical operators

There are following logical operators supported by C language

Assume variable A holds 10 and variable B holds 20 then

Operator Description Example

== Checks if the value of two operands is equal or not, if yes then (A == B) is not
condition becomes true. true.

!= Checks if the value of two operands is equal or not, if values are


(A != B) is true.
not equal then condition becomes true.

> Checks if the value of left operand is greater than the value of
(A > B) is not true.
right operand, if yes then condition becomes true.

< Checks if the value of left operand is less than the value of right
(A < B) is true.
operand, if yes then condition becomes true.

>= Checks if the value of left operand is greater than or equal to the (A >= B) is not
value of right operand, if yes then condition becomes true. true.

<= Checks if the value of left operand is less than or equal to the
(A <= B) is true.
value of right operand, if yes then condition becomes true.

&& Called Logical AND operator. If both the operands are non zero
(A && B) is true.
then then condition becomes true.
Aditya Kumar, Asst. Professor, Mobile No. 8791178099

|| Called Logical OR Operator. If any of the two operands is non


(A || B) is true.
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 !(A && B) is false.
make false.

3. Bitwise operators
Bitwise operator works on bits and performs bit by bit operation.

Assume if A = 60; and B = 13; Now in binary format they will be as follows:

A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A  = 1100 0011

There are following Bitwise operators supported by C language

Operator Description Example

Binary AND Operator copies a bit to the result if it exists (A & B) will give 12 which is
&
in both operands. 0000 1100

Binary OR Operator copies a bit if it exists in eather (A | B) will give 61 which is


|
operand. 0011 1101

Binary XOR Operator copies the bit if it is set in one (A ^ B) will give 49 which is
^
operand but not both. 0011 0001

Binary Ones Complement Operator is unary and has the (~A ) will give -60 which is
~
efect of 'flipping' bits. 1100 0011
Aditya Kumar, Asst. Professor, Mobile No. 8791178099

Binary Left Shift Operator. The left operands value is


A << 2 will give 240 which is
<< moved left by the number of bits specified by the right
1111 0000
operand.

Binary Right Shift Operator. The left operands value is


A >> 2 will give 15 which is
>> moved right by the number of bits specified by the right
0000 1111
operand.

4. Assignment operators
There are following assignment operators supported by C language:

Operator Description Example

Simple assignment operator, Assigns values from right C = A + B will assigne value of
=
side operands to left side operand A + B into C

Add AND assignment operator, It adds right operand to C += A is equivalent to C = C +


+=
the left operand and assign the result to left operand A

Subtract AND assignment operator, It subtracts right


C -= A is equivalent to C = C -
-= operand from the left operand and assign the result to
A
left operand

Multiply AND assignment operator, It multiplies right


C *= A is equivalent to C = C *
*= operand with the left operand and assign the result to
A
left operand

Divide AND assignment operator, It divides left operand


C /= A is equivalent to C = C /
/= with the right operand and assign the result to left
A
operand

Modulus AND assignment operator, It takes modulus


C %= A is equivalent to C = C
%= using two operands and assign the result to left
%A
operand

<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator C &= 2 is same as C = C & 2


Aditya Kumar, Asst. Professor, Mobile No. 8791178099

^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2

|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2

5. Increment and Decrement operators

Increment Operators are used to increased the value of the variable by one and Decrement
Operators are used to decrease the value of the variable by one in C programs.

Either increment and decrement operator are used on a single operand or variable, so it is called as
a unary operator. Unary operators are having higher priority than the other operators it means unary
operators are executed before other operators.

Syntax

++ // increment operator
-- // decrement operator
Note: Increment and decrement operators are can not apply on constant.

Type of Increment Operator

 pre-increment
 post-increment

pre-increment (++ variable)

In pre-increment first increment the value of variable and then used inside the expression (initialize
into another variable).

Syntax

++ variable;

In above program first increase the value of i and then used value of i into expression.

post-increment (variable ++)

In post-increment first value of variable is used in the expression (initialize into another variable)
and then increment the value of variable.

Syntax

Variable++;
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
Type of Decrement Operator
 pre-decrement
 post-decrement

Pre-decrement (-- variable)

In pre-decrement first decrement the value of variable and then used inside the expression
(initialize into another variable).

Syntax

--Variable;

post-decrement (variable --)

In Post-decrement first value of variable is used in the expression (initialize into another variable)
and then decrement the value of variable.

6. Misc Operators

There are few other operators supported by C Language.

Operator Description Example

sizeof() Returns the size of an variable. sizeof(a), where a is interger, will return 4.

& Returns the address of a variable. &a; will give actual address of the variable.

* Pointer to a variable. *a; will pointer to a variable.

?: Conditional Expression (a>b)? a : b ( i.e if(a>b) then a else b)

Operators Categories:

All the operators we have discussed above can be categorised into following categories:

 Postfix operators, which follow a single operand.


 Unary prefix operators, which precede a single operand.

 Binary operators, which take two operands and perform a variety of arithmetic and logical
operations.

 The conditional operator (a ternary operator), which takes three operands and evaluates either
the second or third expression, depending on the evaluation of the first expression.

 Assignment operators, which assign a value to a variable.

 The comma operator, which guarantees left-to-right evaluation of comma-separated


expressions.
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
Q6. What is meant by precedence of operators in C?

Ans: Operator precedence describes the order in which C reads expressions. For example, the
expression a=4+b*2 contains two operations, an addition and a multiplication. Does the C compiler evaluate 4+b first,
then multiply the result by 2, or does it evaluate b*2 first, then add 4 to the result? The operator precedence chart
contains the answers. Operators higher in the chart have a higher precedence, meaning that the C compiler evaluates
them first. Operators on the same line in the chart have the same precedence, and the "Associativity" column on the
right gives their evaluation order.

Operator Precedence Chart

Operator Type Operator Associativity

Primary Expression
() [] . -> expr++ expr-- left-to-right
Operators

Unary Operators * & + - ! ~ ++expr --expr(typecast) sizeof right-to-left

*/%

+-

>> <<

< > <= >=

== !=
Binary Operators left-to-right
&

&&

||

Ternary Operator ?: right-to-left

Assignment Operators = += -= *= /= %= >>= <<= &= ^= |= right-to-left

Comma , left-to-right

Unit-2
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
Q1. What is decision control structure in c language?
Ans: The decision control statements are the decision making statements that decides the order
of execution of statements based on the conditions. In the decision making statements the
programmer specify which conditions are to be executed or tested with the statements to be
executed if the condition is true or false.

There are 4 types of decision making control statements in C language. They are,
1. if statements
2. if else statements
3. nested if statements
4. Switch case

1. The if Statement

C uses the keyword if to implement the decision control instruction. The general form of if statement
looks like this:

//for single statement

if(condition)

statement;

//for multiple statement

if(condition)

block of statement;

Here the condition can be any valid expression including a relational expression. We can even use
arithmetic expressions in the if statement. For example all the following if statements are valid

if (3 + 2 % 5)

printf("This works");

The expression (3 + 2 % 5) evaluates to 5 and since 5 is non-zero it is considered to be true. Hence


the printf("This works"); gets executed.

2. The if-else Statement

The if statement by itself will execute a single statement, or a group of statements, when the
expression following if evaluates to true. It does nothing when the expression evaluates to false. Can
we execute one group of statements if the expression evaluates to true and another group of
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
statements if the expression evaluates to false? Of course! This is what is the purpose of the else
statement that is demonstrated as
if (expression)
{
block of statement;
}
else
statement;

Note

 The group of statements after if up to and not including the else is called an if block. Similarly,
the statements after the else form the else block.

 Notice that the else is written exactly below the if. The statements in the if block and those in
the else block have been indented to the right.
 Had there been only one statement to be executed in the if block and only one statement in
the else block we could have dropped the pair of braces.
 As with the if statement, the default scope of else is also the statement immediately after
the else. To override this default scope a pair of braces as shown in the above "Multiple
Statements within if" must be used.

3. The nested if-else Statement

If we write an entire if-else construct within either the body of the if statement or the body of


an else statement. This is called "nesting" of ifs. This is demonstrated as -

if (expression1)
statement;
else
{
if (expression2)
statement;
else
{
block of statement;
}
}
The else-if is the most general way of writing a multi-way decision.

if(expression1)

statement;
else if(expression2)
statement;
else if(expression3)
statement;
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
else if(expression4)
{
block of statement;
}
else
statement;

The expressions are evaluated in order; if an expression is true, the "statement" or "block of


statement" associated with it is executed, and this terminates the whole chain. As always, the code
for each statement is either a single statement, or a group of them in braces. The last else part
handles the "none of the above" or default case where none of the other conditions is satisfied.

5. Switch Statements or Control Statements

The switch statement is a multi-way decision that tests whether an expression matches one of a


number of constant integer values, and branches accordingly. The switch statement that allows us to
make a decision from the number of choices is called a switch, or more correctlya switch-case-
default, since these three keywords go together to make up the switch statement.
switch (expression)
{
case constant-expression:
statement1;
statement2;
break;
case constant-expression:
statement;
break;
...
default:
statement;
}

 In switch…case command, each case acts like a simple label. A label determines a point in


program which execution must continue from there. Switch statement will choose one
of case sections or labels from where the execution of the program will continue. The program will
continue execution until it reaches break command.

 break statements have vital rule in switch structure. If you remove these statements, program
execution will continue to next case sections and all remaining case sections until the end
of switch block will be executed (while most of the time we just want one case section to be run).

 default section will be executed if none of the case sections match switch comparison.

Q2. What is the iteration statement?


Aditya Kumar, Asst. Professor, Mobile No. 8791178099
Ans: Iteration is the process where a set of instructions or statements is executed repeatedly for a
specified number of time or until a condition is met. These statements also alter the control flow of the
program and thus can also be classified as control statements in C Programming Language.

Iteration statements are most commonly known as loops. Also the repetition process in C is done by
using loop control instruction. There are three types of looping statements:
 For Loop
 While Loop
 Do-while loop

for Loop
The syntax of the for loop is:

for (initializationStatement; testExpression; updateStatement)


{
// statements inside the body of loop
}

How for loop works?


 The initialization statement is executed only once.
 Then, the test expression is evaluated. If the test expression is evaluated to false, the forloop is
terminated.
 However, if the test expression is evaluated to true, statements inside the body of forloop are
executed, and the update expression is updated.
 Again the test expression is evaluated.

This process goes on until the test expression is false. When the test expression is false, the loop
terminates.

for loop Flowchart


Aditya Kumar, Asst. Professor, Mobile No. 8791178099
Example : for loop
# Print numbers from 1 to 10
#include <stdio.h>
int main() {
int i;
for (i = 1; i < 11; ++i)
{
printf("%d ", i);
}
return 0;
}
Output
1 2 3 4 5 6 7 8 9 10
while Loop

The syntax of the while loop is:

while (testExpression)
{
// statements inside the body of the loop
}

How while loop works?


 The while loop evaluates the test expression inside the parenthesis ().
 If the test expression is true, statements inside the body of while loop are executed. Then, the
test expression is evaluated again.
 The process goes on until the test expression is evaluated to false.
 If the test expression is false, the loop terminates (ends).

Flowchart of while loop


Aditya Kumar, Asst. Professor, Mobile No. 8791178099

Example: while loop


// Print numbers from 1 to 5

#include <stdio.h>
int main()
{
int i = 1;

while (i <= 5)
{
printf("%d\n", i);
++i;
}

return 0;
}

Output
1
2
3
4
5
Here, we have initialized i to 1.
1. When i is 1, the test expression i <= 5 is true. Hence, the body of the while loop is executed.
This prints 1 on the screen and the value of i is increased to 2.
2. Now, i is 2, the test expression i <= 5 is again true. The body of the while loop is executed
again. This prints 2 on the screen and the value of i is increased to 3.
3. This process goes on until i become 6. When i is 6, the test expression i <= 5 will be false and
the loop terminates.

do...while loop
The do..while loop is similar to the while loop with one important difference. The body
of do...while loop is executed at least once. Only then, the test expression is evaluated.
The syntax of the do...while loop is:

do
{
// statements inside the body of the loop
}
while (testExpression);

How do...while loop works?


 The body of do...while loop is executed once. Only then, the test expression is evaluated.
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
 If the test expression is true, the body of the loop is executed again and the test expression is
evaluated.
 This process goes on until the test expression becomes false.
 If the test expression is false, the loop ends.
Flowchart of do...while Loop

Example do...while loop


// Program to add numbers until the user enters zero

#include <stdio.h>
int main()
{
double number, sum = 0;

// the body of the loop is executed at least once


do
{
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
}
while(number != 0.0);

printf("Sum = %.2lf",sum);

return 0;
}

Output
Enter a number: 1.5
Enter a number: 2.4
Enter a number: -3.4
Enter a number: 4.2
Enter a number: 0
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
Sum = 4.70

Q3. Explain break; continue; and goto statement.

Ans:
C break
The break statement ends the loop immediately when it is encountered. Its syntax is:

break;

The break statement is almost always used with if...else statement inside the loop.

How break statement works?

Example : break statement


// Program to calculate the sum of a maximum of 10 numbers
// If a negative number is entered, the loop terminates
# include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;
for(i=1; i <= 10; ++i)
{
printf("Enter a n%d: ",i);
scanf("%lf",&number);
// If the user enters a negative number, the loop ends
if(number < 0.0)
{
break;
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf",sum);
return 0;
}
Output
Enter a n1: 2.4
Enter a n2: 4.5
Enter a n3: 3.4
Enter a n4: -3
Sum = 10.30

This program calculates the sum of a maximum of 10 numbers. Why a maximum of 10 numbers? It's
because if the user enters a negative number, the break statement is executed. This will end
the for loop, and the sum is displayed.

C continue
The continue statement skips the current iteration of the loop and continues with the next iteration. Its
syntax is:
continue;
The continue statement is almost always used with the if...else statement.

How continue statement works?

#include <stdio.h>
int main()
{
for (int j=0; j<=8; j++)
{
if (j==4)
{
/* The continue statement is encountered when
* the value of j is equal to 4.
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
*/
continue;
}
/* This print statement would not execute for the
* loop iteration where j ==4 because in that case
* this statement would be skipped.
*/
printf("%d ", j);
}
return 0;
}
Output:
01235678

Value 4 is missing in the output, why? When the value of variable j is 4, the program encountered a
continue statement, which makes the control to jump at the beginning of the for loop for next iteration,
skipping the statements for current iteration (that’s the reason printf didn’t execute when j is equal to
4).

Q4. What is storage class and types?

Ans: A storage class defines the scope (visibility) and life-time of variables and/or functions within a
C Program. They precede the type that they modify. We have four different storage classes in a C
program-

 auto
 register
 static
 extern

The auto Storage Class


The auto storage class is the default storage class for all local variables.
{
int mount;
auto int month;
}
The example above defines two variables with in the same storage class. 'auto' can only be used
within functions, i.e., local variables.

The register Storage Class


Aditya Kumar, Asst. Professor, Mobile No. 8791178099
The register storage class is used to define local variables that should be stored in a register instead
of RAM. This means that the variable has a maximum size equal to the register size (usually one
word) and can't have the unary '&' operator applied to it (as it does not have a memory location).
{
register int miles;
}
The register should only be used for variables that require quick access such as counters. It should
also be noted that defining 'register' does not mean that the variable will be stored in a register. It
means that it MIGHT be stored in a register depending on hardware and implementation restrictions.
The static Storage Class
The static storage class instructs the compiler to keep a local variable in existence during the life-
time of the program instead of creating and destroying it each time it comes into and goes out of
scope. Therefore, making local variables static allows them to maintain their values between function
calls.
The static modifier may also be applied to global variables. When this is done, it causes that
variable's scope to be restricted to the file in which it is declared.
In C programming, when static is used on a global variable, it causes only one copy of that member
to be shared by all the objects of its class.
#include <stdio.h>
/* function declaration */
void func(void);
static int count = 5; /* global variable */
main() {
while(count--) {
func();
}
return 0;
}
/* function definition */
void func( void ) {
static int i = 5; /* local static variable */
i++;
printf("i is %d and count is %d\n", i, count);
}
When the above code is compiled and executed, it produces the following result −
i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0

The extern Storage Class


Aditya Kumar, Asst. Professor, Mobile No. 8791178099
The extern storage class is used to give a reference of a global variable that is visible to ALL the
program files. When you use 'extern', the variable cannot be initialized however, it points the variable
name at a storage location that has been previously defined.
When you have multiple files and you define a global variable or function, which will also be used in
other files, then extern will be used in another file to provide the reference of defined variable or
function. Just for understanding, extern is used to declare a global variable or function in another file.
The extern modifier is most commonly used when there are two or more files sharing the same
global variables or functions as explained below.
First File: main.c
#include <stdio.h>
int count ;
extern void write_extern();
main() {
count = 5;
write_extern();
}
Second File: support.c
#include <stdio.h>
extern int count;
void write_extern(void) {
printf("count is %d\n", count);
}
Here, extern is being used to declare count in the second file, where as it has its definition in the first
file, main.c. Now, compile these two files, It will produce the executable program a.out. When this
program is executed, it produces the following result −
count is 5

Q5. What is array? How do you declare and Initializing an array in C?


Ans: Arrays a kind of data structure that 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.
Or
C Array is a collection of variables belongings to the same data type. You can store group of data of
same data type in an array.
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.
Aditya Kumar, Asst. Professor, Mobile No. 8791178099

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 −
double balance[10];
Here balance is a variable array which is sufficient to hold up to 10 double numbers.
Initializing Arrays
You can initialize an array in C either one by one or using a single statement as follows −
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
The number of values between braces { } cannot 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 −
double 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 the 5th element in the array with a value of 50.0. All arrays have 0 as
the index of their first element which is also called the base index and the last index of an array will
be total size of the array minus 1. Shown below is the pictorial representation of the 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 −
double salary = balance[9];
The above statement will take the 10 th element from the array and assign the value to salary
variable.
#include <stdio.h>
int main () {
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
/* 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

Q6. What are the different types of arrays?


Ans: In c programming language, arrays are classified into two types. They are as follows...
1. Single Dimensional Array / One Dimensional Array
2. Multi Dimensional Array

Single Dimensional Array


In c programming language, single dimensional arrays are used to store list of values of same
datatype. In other words, single dimensional arrays are used to store a row of values. In single
dimensional array, data is stored in linear form. Single dimensional arrays are also called as  one-
dimensional arrays, Linear Arrays or simply 1-D Arrays.
data_type varname[size];

Rules For Declaring One Dimensional Array


 An array variable must be declared before being used in a program.
 The declaration must have a data type(int, float, char, double, etc.), variable name,
and subscript.
 The subscript represents the size of the array. If the size is declared as 10,
programmers can store 10 elements.
 An array index always starts from 0. For example, if an array variable is declared as
s[10], then it ranges from 0 to 9.
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
 Each array element stored in a separate memory location.

EX.
#include <stdio.h>
int main()
{
int s[5] = {89, 76, 98, 91, 84}, i;
printf("\n---Students marks details--- ");
for(i = 0; i < 5; i++)
{
printf("\ns%d = %d ", i + 1, s[i]);
}
return 0;
}

Two Dimensional / Multi Dimensional Array

An array of arrays is called as multi dimensional array. In simple words, an array created with more
than one dimension (size) is called as multi dimensional array. Multi dimensional array can be of two
dimensional array or three dimensional array or four dimensional array or more...

Most popular and commonly used multi dimensional array is two dimensional array. The 2-D arrays
are used to store data in the form of table. We also use 2-D arrays to create mathematical matrices.

data_type varname[size1][size2];

Initialisation of Two Dimensional Array


int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
or
int matrix[3][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9};

Ex.
#include <stdio.h>
int main()
{
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, i, j;
for(i = 0; i < 3; i++)
{
for(j = 0; j < 3; j++)
{
printf("%2d ", matrix[i] [j]);
}
printf("\n");
}
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
return 0;
}
Q7. WAP to search an element ina one dimensional arrays.
Ans.
#include <stdio.h> for (c = 0; c < n; c++)
#include<conio.h> {
void main() if (array[c] == search) /* If required element is
{ found */
int array[100], search, c, n; {
printf("%d is present at location %d.\n",
printf("Enter number of elements in array\n"); search, c+1);
scanf("%d", &n); break;
}
printf("Enter %d integer(s)\n", n); }
if (c == n)
for (c = 0; c < n; c++) printf("%d isn't present in the array.\n", search);
scanf("%d", &array[c]);
getch();
printf("Enter a number to search\n"); }
scanf("%d", &search);

Q8 WAP to perform matrix multiplication of two integer types arrays.


Ans:.
#include<stdio.h>     printf("multiply of the matrix=\n");    
#include<stdlib.h>   for(i=0;i<r;i++)    
int main(){   {    
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;     for(j=0;j<c;j++)    
system("cls");   {    
printf("enter the number of row=");     mul[i][j]=0;    
scanf("%d",&r);     for(k=0;k<c;k++)    
printf("enter the number of column=");     {    
scanf("%d",&c);     mul[i][j]+=a[i][k]*b[k][j];    
printf("enter the first matrix element=\n");     }    
for(i=0;i<r;i++)     }    
{     }    
for(j=0;j<c;j++)     //for printing result    
{     for(i=0;i<r;i++)    
scanf("%d",&a[i][j]);     {    
}     for(j=0;j<c;j++)    
}     {    
printf("enter the second matrix element=\n");  printf("%d\t",mul[i][j]);    
for(i=0;i<r;i++)     }    
{     printf("\n");    
for(j=0;j<c;j++)     }    
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
{     getch();  
scanf("%d",&b[i][j]);     }  
}    
}    

  
Q9. WAP to find whether inserted number is palindrome or not.

#include <stdio.h>  while (t != 0)


     {
int main()       reverse = reverse * 10;
{       reverse = reverse + t%10;
   int n, reverse = 0, t;       t = t/10;
     }
printf("Enter a number to check if it is a palindrome    if (n == reverse)
or not\n");       printf("%d is a palindrome number.\n", n);
   scanf("%d", &n);    else
        printf("%d isn't a palindrome number.\n", n);
   t = n;     return 0;
}

Q10. C program to print following Pyramid:


*
**
***
****
*****
Ans.
#include<stdio.h> for(j=0;j<=i;j++)
{
int main() printf("*");
{ }
int i,j; printf("\n");
}
for(i=0; i< 5; i++) return 0;
{ }

Q11.C program to print following Pyramid:


*****
****
***
**
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
*
#include<stdio.h> for(j=0;j<=i;j++)
{
int main() printf("*");
{ }
int i,j; printf("\n");
}
for(i=5; i>=0; i--) return 0;
{ }

Q12. C program to print following Pyramid:


        *
       * *
      * * *
     * * * *
    * * * * *
#include<stdio.h> for(j=0;j<=i;j++)
int main() {
{ printf("* ");
int i,j; }
int space=4;
/*run loop (parent loop) till number of rows*/ printf("\n");
for(i=0;i< MAX;i++) space--; /* decrement one space after
{ one row*/
/*loop for initially space, before star printing*/ }
for(j=0;j< space;j++) return 0;
{ }
printf(" ");
}

Q12. C program to find the biggest of three numbers


Ans:
#include <stdio.h> printf("num1 is the greatest among
three \n");
void main() }
{ else
int num1, num2, num3; {
printf("num3 is the greatest among
printf("Enter the values of num1, num2 and three \n");
num3\n"); }
scanf("%d %d %d", &num1, &num2, &num3); }
printf("num1 = %d\tnum2 = %d\tnum3 = %d\n", else if (num2 > num3)
num1, num2, num3); printf("num2 is the greatest among three
if (num1 > num2) \n");
{ else
if (num1 > num3) printf("num3 is the greatest among three
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
{ \n");
}
Q13. WAP to check whether a character is VOWEL or CONSONANT using switch.

Ans:
#include <stdio.h> case 'a':
case 'e':
int main() case 'i':
{ case 'o':
char ch; case 'u':
printf("%c is a VOWEL.\n",ch);
printf("Enter a character: "); break;
scanf("%c",&ch);             default:
printf("%c is a CONSONANT.\n",ch);
//condition to check character is alphabet or }
not }
if((ch>='A' && ch<='Z') || (ch>='a' && ch<='z')) else
{ {
//check for VOWEL or CONSONANT printf("%c is not an alphabet.\n",ch);
switch(ch) }
{
case 'A': return 0;
case 'E': }
case 'I':
case 'O':
case 'U':

Q14. How is 2d array stored in memory?


Ans. A 2D array’s elements are stored in continuous memory locations. It can be represented in
memory using any of the following two ways:

1. Column-Major Order
2. Row-Major Order

1. Column-Major Order:
In this method the elements are stored column wise, i.e. m elements of first column are stored in first
m locations, m elements of second column are stored in next m locations and so on. E.g.
A 3 x 4 array will stored as below:
Aditya Kumar, Asst. Professor, Mobile No. 8791178099

2. Row-Major Order:

In this method the elements are stored row wise, i.e. n elements of first row are stored in first n
locations, n elements of second row are stored in next n locations and so on. E.g.

A 3 x 4 array will stored as below:

Unit-3
Q1. What do you mean by function in c programming?
Ans: A function is a group of statements that together perform a task. Every C program has at least
one function, which is main(), and all the most trivial programs can define additional functions.
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
You can divide up your code into separate functions. How you divide up your code among different
functions is up to you, but logically the division is such that each function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.

एक फ़ंक्शन स्टे टमें ट्स का एक समूह है जो एक साथ एक कार्य करता है । प्रत्येक C प्रोग्राम में कम से कम एक फ़ंक्शन
होता है , जो मुख्य है (), और सभी सबसे तुच्छ प्रोग्राम अतिरिक्त फ़ंक्शन को परिभाषित कर सकते हैं।
आप अपने कोड को अलग-अलग कार्यों में विभाजित कर सकते हैं। आप विभिन्न कार्यों के बीच अपने कोड को कैसे
विभाजित करते हैं, यह आपके ऊपर है , लेकिन तार्कि क रूप से विभाजन ऐसा है कि प्रत्येक फ़ंक्शन एक विशिष्ट कार्य
करता है ।
एक फ़ंक्शन declaration एक फ़ंक्शन के नाम, रिटर्न प्रकार और parameters के बारे में संकलक को बताता है । एक
फ़ंक्शन परिभाषा फ़ंक्शन का वास्तविक निकाय प्रदान करती है ।
The C standard library provides numerous built-in functions that your program can call. For
example, strcat() to concatenate two strings, memcpy() to copy one memory location to another
location, and many more functions.
A function can also be referred as a method or a sub-routine or a procedure, etc.

Defining a Function
The general form of a function definition in C programming language is as follows −
return_type function_name( parameter list ) {
body of the function
}
A function definition in C programming consists of a function header and a function body. Here are
all the parts of a function −
 Return Type − A function may return a value. The return_type is the data type of the value
the function returns. Some functions perform the desired operations without returning a value.
In this case, the return_type is the keyword void.
 Function Name − This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
 Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value
to the parameter. This value is referred to as actual parameter or argument. The parameter
list refers to the type, order, and number of the parameters of a function. Parameters are
optional; that is, a function may contain no parameters.
 Function Body − The function body contains a collection of statements that define what the
function does.

Example
Given below is the source code for a function called max(). This function takes two parameters
num1 and num2 and returns the maximum value between the two −
/* function returning the max between two numbers */
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
int max(int num1, int num2) {

/* local variable declaration */


int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}
Function Declarations
A function declaration tells the compiler about a function name and how to call the function. The
actual body of the function can be defined separately.
A function declaration has the following parts −
return_type function_name( parameter list );
For the above defined function max(), the function declaration is as follows −
int max(int num1, int num2);

Calling a Function
While creating a C function, you give a definition of what the function has to do. To use a function,
you will have to call that function to perform the defined task.
When a program calls a function, the program control is transferred to the called function. A called
function performs a defined task and when its return statement is executed or when its function-
ending closing brace is reached, it returns the program control back to the main program.
To call a function, you simply need to pass the required parameters along with the function name,
and if the function returns a value, then you can store the returned value. For example –
/* calling a function to get max value */ int max(int num1, int num2) {
ret = max(a, b); /* local variable declaration */
int result;
printf( "Max value is : %d\n", ret );
if (num1 > num2)
return 0; result = num1;
} else
result = num2;
/* function returning the max between two
numbers */ return result;
}
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
Q2. What is function prototype and its purpose?
Ans: The Function prototype serves the following purposes –

1) It tells the return type of the data that the function will return.
2) It tells the number of arguments passed to the function.
3) It tells the data types of the each of the passed arguments.
4) Also it tells the order in which the arguments are passed to the function.

फ़ंक्शन प्रोटोटाइप निम्नलिखित उद्देश्यों को पूरा करता है -

1) यह डेटा के रिटर्न प्रकार को बताता है कि फ़ंक्शन वापस आ जाएगा।


2) यह फ़ंक्शन को दिए गए तर्कों की संख्या बताता है ।
3) यह पारित तर्कों में से प्रत्येक के डेटा प्रकार बताता है ।
4) इसके अलावा यह उस क्रम को बताता है जिसमें फ़ंक्शन को argument दिए जाते हैं।

Therefore essentially, function prototype specifies the input/output interface to the function i.e. what to
give to the function and what to expect from the function.

इसलिए अनिवार्य रूप से, फ़ंक्शन प्रोटोटाइप फ़ंक्शन के इनपुट / आउटपुट इंटरफ़ेस को निर्दिष्ट करता है यानी फ़ंक्शन
को क्या दे ना है और फ़ंक्शन से क्या अपेक्षा करनी है ।

Prototype of a function is also called signature of the function.


Example
#include <stdio.h> int addNumbers(int a,int b) // function definition
int addNumbers(int a, int b); // function prototype {
int main() int result;
{ result = a+b;
int n1,n2,sum; return result; // return statement
printf("Enters two numbers: "); }
scanf("%d %d",&n1,&n2);
sum = addNumbers(n1, n2); // function call
printf("sum = %d",sum);
return 0;
}

Q3. What's the difference between actual arguments and formal arguments?
Ans: Actual arguments:
The arguments that are passed in a function call are called actual arguments. These arguments are
defined in the calling function.
Formal arguments:
The formal arguments are the parameters/arguments in a function declaration. The scope of formal
arguments is local to the function definition in which they are used. Formal arguments belong to the
called function. Formal arguments are a copy of the actual arguments. A change in formal arguments
would not be reflected in the actual arguments.
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
Example:
#include <stdio.h> /* called function */
void sum(int i, int j, int k); /* formal arguments*/
/* calling function */ void sum(int i, int j, int k)
int main() {
{ int s;
int a = 5; s = i + j + k;
// actual arguments printf("sum is %d", s);
sum(3, 2 * a, a); }
return 0; Here 3,2*a,a are actual arguments and i,j,k are
formal arguments.
}

Actual vs Formal Parameters

The Actual parameters are the values that


The Formal Parameters are the variables defined by the
are passed to the function when it is
function that receives values when the function is called.
invoked.

 Related Function

The actual parameters are passed by the


The formal parameters are in the called function.
calling function.

Data Types

In actual parameters, there is no


In formal parameters, the data types of the receiving
mentioning of data types. Only the value
values should be included.
is mentioned.

Q4.What is the difference between call by value and call by reference in C language?

Ans: There are two ways to pass arguments/parameters to function calls -- call by value and call by

reference.

Let's understand call by value and call by reference in c language one by one.

Call by value in C

 In call by value method, the value of the actual parameters is copied into the formal
parameters. In other words, we can say that the value of the variable is used in the function
call in the call by value method.
 In call by value method, we can not modify the value of the actual parameter by the formal
parameter.
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
 In call by value, different memory is allocated for actual and formal parameters since the value
of the actual parameter is copied into the formal parameter.
 The actual parameter is the argument which is used in the function call whereas formal
parameter is the argument which is used in the function definition.

#include<stdio.h>
void change(int num) {
printf("Before adding value inside function num=%d \n",num);
num=num+100;
printf("After adding value inside function num=%d \n", num);
}
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(x);//passing value in function
printf("After function call x=%d \n", x);
return 0;
}

Call by reference in C

 In call by reference, the address of the variable is passed into the function call as the actual
parameter.
 The value of the actual parameters can be modified by changing the formal parameters since
the address of the actual parameters is passed.
 In call by reference, the memory allocation is similar for both formal parameters and actual
parameters. All the operations in the function are performed on the value stored at the address
of the actual parameters, and the modified value gets stored at the same address.

#include<stdio.h>
void change(int *num) {
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
printf("Before adding value inside function num=%d \n",*num);
(*num) += 100;
printf("After adding value inside function num=%d \n", *num);
}
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(&x);//passing reference in function
printf("After function call x=%d \n", x);
return 0;
}

No Call by value Call by reference


.

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

2 Changes made inside the function is Changes made inside the function validate
limited to the function only. The values of outside of the function also. The values of
the actual parameters do not change by the actual parameters do change by
changing the formal parameters. changing the formal parameters.

3 Actual and formal arguments are created Actual and formal arguments are created at
at the different memory location the same memory location

Q5. WAP to find cube of a number using function


Ans:
#include <stdio.h> c = cube(num);

/* Function declaration */ printf("Cube of %d is %.2f", num, c);


double cube(double num);
return 0;
int main() }
{
int num; /**
double c; * Function to find cube of any number
*/
/* Input number to find cube from user */ double cube(double num)
printf("Enter any number: "); {
scanf("%d", &num); return (num * num * num);
}
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
Q6. WAP to find prime numbers in given range using functions
Ans:
#include <stdio.h> if(isPrime(lowerLimit))
int isPrime(int num); {
void printPrimes(int lowerLimit, int upperLimit); printf("%d, ", lowerLimit);
int main() }
{ lowerLimit++;
int lowerLimit, upperLimit; }
}
printf("Enter the lower and upper limit to list
primes: "); int isPrime(int num)
scanf("%d%d", &lowerLimit, &upperLimit); {
printPrimes(lowerLimit, upperLimit); int i;

return 0; for(i=2; i<=num/2; i++)


} {
void printPrimes(int lowerLimit, int upperLimit) if(num % i == 0)
{ {
printf("All prime number between %d to %d return 0;
are: ", lowerLimit, upperLimit); }
}
while(lowerLimit <= upperLimit)
{ return 1;
}

Q7. WAP to find maximum and minimum using functions


Ans:
#include <stdio.h> printf("\nMaximum = %d\n", maximum);
printf("Minimum = %d", minimum);
int max(int num1, int num2);
int min(int num1, int num2); return 0;
int main() }
{ int max(int num1, int num2)
int num1, num2, maximum, minimum; {
return (num1 > num2 ) ? num1 : num2;
/* Input two numbers from user */ }
printf("Enter any two numbers: ");
scanf("%d%d", &num1, &num2); /**
* Find minimum between two numbers.
maximum = max(num1, num2); // Call */
maximum function int min(int num1, int num2)
minimum = min(num1, num2); // Call minimum {
function return (num1 > num2 ) ? num2 : num1;
}

Q8. How to pass arrays to a function in C Programming?

Ans: Just like variables, array can also be passed to a function as an argument
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
.
Passing array to function using call by value method

As we already know in this type of function call, the actual parameter is copied to the formal
parameters.

#include <stdio.h>
void disp( char ch)
{
printf("%c ", ch);
}
int main()
{
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
for (int x=0; x<10; x++)
{
/* I’m passing each element one by one using subscript*/
disp (arr[x]);
}

return 0;
}

Passing array to function using call by reference


When we pass the address of an array while calling a function then this is called function call by
reference. When we pass an address as an argument, the function declaration should have a pointer
as a parameter to receive the passed address.
#include <stdio.h>
void disp( int *num)
{
printf("%d ", *num);
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
for (int i=0; i<10; i++)
{
/* Passing addresses of array elements*/
disp (&arr[i]);
}
return 0;
}

Pass an entire array to a function as an argument?

In the above example, we have passed the address of each array element one by one using a for
loop in C. However you can also pass an entire array to a function like this:
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
Note: The array name itself is the address of first element of that array. For example if array name is
arr then you can say that arr is equivalent to the &arr[0].

#include <stdio.h>
void myfuncn( int *var1, int var2)
{
for(int x=0; x<var2; x++)
{
printf("Value of var_arr[%d] is: %d \n", x, *var1);
/*increment pointer for next element fetch*/
var1++;
}
}
int main()
{
int var_arr[] = {11, 22, 33, 44, 55, 66, 77};
myfuncn(var_arr, 7);
return 0;
}

Unit4
Q1. What is a pointer in C with example?
Ans: Pointers in C language is a variable that stores/points the address of another variable. A Pointer
in C is used to allocate memory dynamically i.e. at run time. The pointer variable might be belonging
to any of the data type such as int, float, char, double, short etc.
Pointer Syntax : data_type *var_name; Example : int *p;  char *p; Where, * is used to denote that “p”
is pointer variable and not a normal variable.

KEY POINTS TO REMEMBER ABOUT POINTERS IN C:


 Normal variable stores the value whereas pointer variable stores the address of the variable.
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
 The content of the C pointer always be a whole number i.e. address.
 Always C pointer is initialized to null, i.e. int *p = null.
 The value of null pointer is 0.
 & symbol is used to get the address of the variable.
 * symbol is used to get the value of the variable that the pointer is pointing to.
 If a pointer in C is assigned to NULL, it means it is pointing to nothing.
 Two pointers can be subtracted to know how many elements are available between these two
pointers.
 But, Pointer addition, multiplication, division are not allowed.
 The size of any pointer is 2 byte (for 16 bit compiler).

#include <stdio.h>
int main()
{
int *ptr, q;
q = 50;
/* address of q is assigned to ptr */
ptr = &q;
/* display q's value using ptr variable */
printf("%d", *ptr);
return 0;
}
Advantages of pointers in c:

 Pointers provide direct access to memory


 Pointers provide a way to return more than one value to the functions
 Reduces the storage space and complexity of the program
 Reduces the execution time of the program
 Provides an alternate way to access array elements
 Pointers can be used to pass information back and forth between the calling function and called
function.
 Pointers allows us to perform dynamic memory allocation and de-allocation.
 Pointers helps us to build complex data structures like linked list, stack, queues, trees, graphs etc.
 Pointers allows us to resize the dynamically allocated memory block.
 Addresses of objects can be extracted using pointers

Drawbacks of pointers in c:

 Uninitialized pointers might cause segmentation fault.


 Dynamically allocated block needs to be freed explicitly.  Otherwise, it would lead to memory leak.
 Pointers are slower than normal variables.
 If pointers are updated with incorrect values, it might lead to memory corruption.
 Basically, pointer bugs are difficult to debug.  Its programmer’s responsibility to use pointers
effectively and correctly.
Aditya Kumar, Asst. Professor, Mobile No. 8791178099

Q3. What is pointer arithmetic explain with example?

Ans. We can perform arithmetic operations on the pointers like addition, subtraction, etc. However,
as we know that pointer contains the address, the result of an arithmetic operation performed on the
pointer will also be a pointer if the other operand is of type integer. In pointer-from-pointer subtraction,
the result will be an integer value. Following arithmetic operations are possible on the pointer in C
language:

 Increment
 Decrement
 Addition
 Subtraction
 Comparison

Incrementing Pointer in C

If we increment a pointer by 1, the pointer will start pointing to the immediate next location. This is
somewhat different from the general arithmetic since the value of the pointer will get increased by the
size of the data type to which the pointer is pointing.

We can traverse an array by using the increment operation on a pointer which will keep pointing to
every element of the array, perform some operation on that, and update itself in a loop.

The Rule to increment the pointer is given below:

new_address= current_address + i * size_of(data type)  

Where i is the number by which the pointer get increased.

32-bit

For 32-bit int variable, it will be incremented by 2 bytes.

64-bit

For 64-bit int variable, it will be incremented by 4 bytes.

#include<stdio.h>  
int main(){  
int number=50;        
int *p;//pointer to int      
p=&number;//stores the address of number variable        
printf("Address of p variable is %u \n",p);        
p=p+1;        
printf("After increment: Address of p variable is %u \n",p); // in our case, p will get incremented by 4 b
ytes.      
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
return 0;  
}    

Decrementing Pointer in C

Like increment, we can decrement a pointer variable. If we decrement a pointer, it will start pointing to
the previous location. The formula of decrementing the pointer is given below:

new_address= current_address - i * size_of(data type)  

32-bit

For 32-bit int variable, it will be decremented by 2 bytes.

64-bit

For 64-bit int variable, it will be decremented by 4 bytes.

#include <stdio.h>            
void main(){            
int number=50;        
int *p;//pointer to int      
p=&number;//stores the address of number variable        
printf("Address of p variable is %u \n",p);        
p=p-1;       
printf("After decrement: Address of p variable is %u \n",p); // P will now point to the immidiate previou
s location.         
}      

C Pointer Addition

We can add a value to the pointer variable. The formula of adding value to pointer is given below:

new_address= current_address + (number * size_of(data type))  

32-bit

For 32-bit int variable, it will add 2 * number.

64-bit

For 64-bit int variable, it will add 4 * number.

#include<stdio.h>  
int main(){  
int number=50;        
int *p;//pointer to int      
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
p=&number;//stores the address of number variable        
printf("Address of p variable is %u \n",p);        
p=p+3;   //adding 3 to pointer variable    
printf("After adding 3: Address of p variable is %u \n",p);       
return 0;  
}    

C Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. Subtracting any number from
a pointer will give an address. The formula of subtracting value from the pointer variable is given
below:

new_address= current_address - (number * size_of(data type))  

32-bit

For 32-bit int variable, it will subtract 2 * number.

64-bit

For 64-bit int variable, it will subtract 4 * number.

#include<stdio.h>  
int main(){  
int number=50;        
int *p;//pointer to int      
p=&number;//stores the address of number variable        
printf("Address of p variable is %u \n",p);        
p=p-3; //subtracting 3 from pointer variable    
printf("After subtracting 3: Address of p variable is %u \n",p);        
return 0;  
}    

Illegal arithmetic with pointers

There are various operations which can not be performed on pointers. Since, pointer stores address
hence we must ignore the operations which may lead to an illegal address, for example, addition, and
multiplication. A list of such operations is given below.

 Address + Address = illegal


 Address * Address = illegal
 Address % Address = illegal
 Address / Address = illegal
 Address & Address = illegal
 Address ^ Address = illegal
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
 Address | Address = illegal
 ~Address = illegal\

Q4. WAP C program to create, initialize, assign and access a pointer variable
Ans: C program to create, initialize, assign and access a pointer variable.

#include <stdio.h> printf("Using variable num:\n");


printf("value of num: %d\naddress of num:
int main() %u\n",num,&num);
{ //access value and address using pointer
int num; /*declaration of integer variable*/ variable num
int *pNum; /*declaration of integer pointer*/ printf("Using pointer variable:\n");
printf("value of num: %d\naddress of num:
pNum=& num; /*assigning address of num*/ %u\n",*pNum,pNum);
num=100; /*assigning 100 to variable
num*/ return 0;
//access value and address using variable }
num

Q5. C program to print a string character by character using pointer

/*C program to print a string using pointer.*/


//assign address of str to ptr
#include <stdio.h> ptr=str;
int main()
{ printf("Entered string is: ");
char str[100]; while(*ptr!='\0')
char *ptr; printf("%c",*ptr++);

printf("Enter a string: "); return 0;


gets(str); }

Q6. WAP C program to count vowels and consonants in a string using pointer
Ans:

#include <stdio.h> if(*ptr=='A' ||*ptr=='E' ||*ptr=='I' ||*ptr=='O' ||*ptr=='U' ||


int main() *ptr=='a' ||*ptr=='e' ||*ptr=='i' ||*ptr=='o' ||*ptr=='u')
{ cntV++;
char str[100]; else
char *ptr; cntC++;
int cntV,cntC;
//increase the pointer, to point next character
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
printf("Enter a string: "); ptr++;
gets(str); }

//assign address of str to ptr printf("Total number of VOWELS: %d, CONSONANT:


ptr=str; %d\n",cntV,cntC);
return 0;
cntV=cntC=0; }
while(*ptr!='\0')
{

Unit-5
Q1 what are structures in C programming?
Ans: Structure is a user-defined data type in C language which allows us to combine data of different
types together. Structure helps to construct a complex data type which is more meaningful. It is
somewhat similar to an Array, but an array holds data of similar type only. But structure on the other
hand, can store data of any type, which is practical more useful. Each element of a structure is called
a member.

The ,struct keyword is used to define the structure. Let's see the syntax to define the structure in c.

struct structure_name   
{  
    data_type member1;  
    data_type member2;  
    .  
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
    .  
    data_type memeberN;  
};  

struct employee  
{   int id;  
    char name[20];  
    float salary;  
};  
The following image shows the memory allocation of the structure employee that is defined in the
above example.

Here, struct is the keyword; employee is the name of the structure; id, name, and salary are the


members or fields of the structure. Let's understand it by the diagram given below:

Declaring structure variable

We can declare a variable for the structure so that we can access the member of the structure easily.
There are two ways to declare structure variable:

1. By struct keyword within main() function


2. By declaring a variable at the time of defining the structure.

1st way:
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
Let's see the example to declare the structure variable by struct keyword. It should be declared within
the main function.

struct employee  
{   int id;  
    char name[50];  
    float salary;  
};  

Now write given code inside the main() function.

struct employee e1, e2;  

The variables e1 and e2 can be used to access the values stored in the structure. Here, e1 and e2
can be treated in the same way as the objects in C++ and Java.

2nd way:

Let's see another way to declare variable at the time of defining the structure.

struct employee  
{   int id;  
    char name[50];  
    float salary;  
}e1,e2;  

Which approach is good


If number of variables are not fixed, use the 1st approach. It provides you the flexibility to declare the
structure variable many times.

If no. of variables are fixed, use 2nd approach. It saves your code to declare a variable in main()
function.

Accessing members of the structure

There are two ways to access structure members:

1. By. (member or dot operator)


2. By -> (structure pointer operator)

Let's see the code to access the id member of p1 variable by . (member) operator.

p1.id  

C Structure example

#include<stdio.h>  
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
#include <string.h>    
struct employee      
{   int id;      
    char name[50];      
}e1;  //declaring e1 variable for structure    
int main( )    
{    
   //store first employee information    
   e1.id=101;    
   strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array    
   //printing first employee information    
   printf( "employee 1 id : %d\n", e1.id);    
   printf( "employee 1 name : %s\n", e1.name);    
return 0;  
}    

Q2. What is array of structure explain with example?


Ans: C Structure is collection of different data types ( variables ) which are grouped together.
Whereas, array of structures is nothing but collection of structures. This is also called as structure
array in C.

An array of structres in C can be defined as the collection of multiple structures variables where each
variable contains information about different entities. The array of structures in C are used to store
information about multiple entities of different data types. The array of structures is also known as the
collection of structures.

Let's see an example of an array of structures that stores information of 5 students and prints it.
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
#include<stdio.h>  
#include <string.h>    
struct student{    
int rollno;    
char name[10];    
};    
int main(){    
int i;    
struct student st[5];    
printf("Enter Records of 5 students");    
for(i=0;i<5;i++){    
printf("\nEnter Rollno:");    
scanf("%d",&st[i].rollno);    
printf("\nEnter Name:");    
scanf("%s",&st[i].name);    
}    
printf("\nStudent Information List:");    
for(i=0;i<5;i++){    
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);    
}    
   return 0;    
}    

Q3. Differentiate between array and structures


Ans:
BASIS FOR
ARRAY STRUCTURE
COMPARISON

Basic An array is a collection of variables of A structure is a collection of variables


same data type. of different data type.

Syntax type array_name[size]; struct sruct_name{


type element1;
type element1;
.
.
} variable1, variable2, . .;

Memory Array elements are stored in Structure elements may not be stored
contiguous memory location. in a contiguous memory location.

Access Array elements are accessed by their Structure elements are accessed by
index number. their names.

Operator Array declaration and element Structure element accessing operator


accessing operator is "[ ]" (square is "." (Dot operator).
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
BASIS FOR
ARRAY STRUCTURE
COMPARISON

bracket).

Pointer Array name points to the first element Structure name does not point to the
in that array so, array name is a first element in that structure so,
pointer. structure name is not a pointer.

Objects Objects (instances) of an array can Structure objects (instance or


not be created. structure variable) can be created.

Size Every element in array is of same Every element in a structure is of


size. different data type.

Bit filed Bit filed can not be defined in an Bit field can be defined in a structure.
array.

Keyword There is no keyword to declare an "struct" is a keyword used to declare


array. the structure.

User-defined Arrays are not user-defined they are Structure is a user-defined datatype.
directly declared.

Accessing Accessing array element requires Accessing a structure elements


less time. require comparatively more time.

Searching Searching an array element takes Searching a structure element takes


less time. comparatively more time than an
array element.

Q3. What is file? Explain file handling in C?


Ans: File is a collection of bytes that is stored on secondary storage devices like disk. There are two
kinds of files in a system. They are,
1. Text files (ASCII)
2. Binary files
 Text files contain ASCII codes of digits, alphabetic and symbols.
 Binary file contains collection of bytes (0’s and 1’s). Binary files are compiled version of text
files.

In programming, we may require some specific input data to be generated several numbers of times.
Sometimes, it is not enough to only display the data on the console. The data to be displayed may be
very large, and only a limited amount of data can be displayed on the console, and since the memory
is volatile, it is impossible to recover the programmatically generated data again and again. However,
if we need to do so, we may store it onto the local file system which is volatile and can be accessed
every time. Here, comes the need of file handling in C.

File handling in C enables us to create, update, read, and delete the files stored on the local file
system through our C program. The following operations can be performed on a file.
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
o Creation of the new file
o Opening an existing file
o Reading from the file
o Writing to the file
o Deleting the file

BASIC FILE OPERATIONS IN C PROGRAMMING:

There are 4 basic operations that can be performed on any files in C programming language. They
are,

1. Opening/Creating a file
2. Closing a file
3. Reading a file
4. Writing in a file
Let us see the syntax for each of the above operations in a table:

File operation Declaration & Description

Declaration: FILE *fopen (const char *filename, const char *mode)

fopen() function is used to open a file to perform operations such as reading,


writing etc. In a C program, we declare a file pointer and use fopen() as below.
fopen() function creates a new file if the mentioned file name does not exist.

FILE *fp;
fp=fopen (“filename”, ”‘mode”);
Where,
fp – file pointer to the data type “FILE”.
filename – the actual file name with full path of the file.
fopen() – To mode – refers to the operation that will be performed on the file. Example: r, w, a,
open a file r+, w+ and a+. Please refer below the description for these mode of operations.

Declaration: int fclose(FILE *fp);

fclose() – To fclose() function closes the file that is being pointed by file pointer fp. In a C
close a file program, we close a file as below.
fclose (fp);

fgets() – To Declaration: char *fgets(char *string, int n, FILE *fp)


read a file
fgets function is used to read a file line by line. In a C program, we use fgets
function as below.
fgets (buffer, size, fp);
where,
buffer – buffer to  put the data in.
size – size of the buffer
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
fp – file pointer

Declaration:
int fprintf(FILE *fp, const char *format, …);fprintf() function writes string into a file
pointed by fp. In a C program, we write string into a file as below.
fprintf() – To fprintf (fp, “some data”); or
write into a file fprintf (fp, “text %d”, variable_name);

Q4. Explain various modes in file handling. What is the different file handling functions in C?
Ans: MODE OF OPERATIONS PERFORMED ON A FILE IN C LANGUAGE:
There are many modes in opening a file. Based on the mode of file, it can be opened for reading or
writing or appending the texts. They are listed below.

r – Opens a file in read mode and sets pointer to the first character in the  file. It returns null if file
does not exist.
w – Opens a file in write mode. It returns null if file could not be opened. If file exists, data are
overwritten.
a – Opens a file in append mode.  It returns null if file couldn’t be opened.
r+ – Opens a file for read and write mode and sets pointer to the first character in the file.
w+ – opens a file for read and write mode and sets pointer to the first character in the file.
a+ – Opens a file for read and write mode and sets pointer to the first character in the file. But, it
can’t modify existing contents.

There are many functions in the C library to open, read, write, search and close the file. A list of file
functions is given below:

No. Function Description

1 fopen() opens new or existing file

2 fprintf() write data into the file

3 fscanf() reads data from the file

4 fputc() writes a character into the file

5 fgetc() reads a character from file

6 fclose() closes the file

7 fseek() sets the file pointer to given position


Aditya Kumar, Asst. Professor, Mobile No. 8791178099
10 ftell() returns current position

11 rewind() sets the file pointer to the beginning of the file

fgetc()

Using

File Declaration & Description


operation

fgetc() fgetc() is used to obtain input from a file single character at a time. This function
returns the number of characters read by the function. It returns the character
present at position indicated by file pointer. After reading the character, the file
pointer is advanced to next character. If pointer is at end of file or if an error occurs
EOF file is returned by this function.
Syntax:
int fgetc(FILE *pointer)
pointer: pointer to a FILE object that identifies
the stream on which the operation is to be performed.

fputc() fputc() is used to write a single character at a time to a given file. It writes the given
character at the position denoted by the file pointer and then advances the file
pointer.
This function returns the character that is written in case of successful write
operation else in case of error EOF is returned.
Syntax:
int fputc(int char, FILE *pointer)
char: character to be written.
This is passed as its int promotion.
pointer: pointer to a FILE object that identifies the
stream where the character is to be written.

fscanf() Declaration: int fscanf(FILE *fp, const char *format, …)

fscanf() function is used to read formatted data from a file. In a C program, we use
fscanf() as below.

fscanf (fp, “%d”, &age);


Where, fp is file pointer to the data type “FILE”.
Age – Integer variable
This is for example only. You can use any specifiers with any data type as we use
in normal scanf() function.
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
fprintf() Declaration: int fprintf(FILE *fp, const char *format, …)

fprintf() function is used to write formatted data into a file. In a C program, we use
fprinf() as below.
fprintf (fp, “%s %d”, “var1”, var2);

Where, fp is file pointer to the data type “FILE”.


var1 – string variable
var2 – Integer variable
This is for example only. You can use any specifiers with any data type as we use
in normal printf() function.

ftell() Declaration: long int ftell(FILE *fp)

ftell function is used to get current position of the file pointer. In a C program, we
use ftell() as below.
ftell(fp);

rewind() Declaration: void rewind(FILE *fp)

rewind function is used to move file pointer position to the beginning of the file. In a
C program, we use rewind() as below.
rewind(fp);

Q5. WAP to create a file in c programming and store information about a person, in terms of
his name, age and salary.

#include <stdio.h> printf("Enter the name \n");


 void main() scanf("%s", name);
{ fprintf(fptr, "Name = %s\n", name);
FILE *fptr; printf("Enter the age\n");
char name[20]; scanf("%d", &age);
int age; fprintf(fptr, "Age = %d\n", age);
float salary; printf("Enter the salary\n");
  scanf("%f", &salary);
fptr = fopen("emp.rec", "w"); fprintf(fptr, "Salary = %.2f\n", salary);
  fclose(fptr);
if (fptr == NULL) }
{
printf("File does not exists \n");
return;
}
Aditya Kumar, Asst. Professor, Mobile No. 8791178099

Q6. Write a program in C to read an existing file.

#include <stdio.h> printf(" File does not exist or cannot


#include <stdlib.h> be opened.\n");
exit(0);
void main() }
{
FILE *fptr; printf("\n The content of the file %s is :\n",fname);
char fname[20]; str = fgetc(fptr);
char str; while (str != EOF)
printf("\n\n Read an existing file :\n"); {
printf("------------------------------\n"); printf ("%c", str);
printf(" Input the filename to be opened : "); str = fgetc(fptr);
scanf("%s",fname); }
fptr = fopen (fname, "r"); fclose(fptr);
if (fptr == NULL) printf("\n\n");
{ }

Q7 Write a program in C to Find the Number of Lines in a Text File.

#include <stdio.h> fptr = fopen(fname, "r");


if (fptr == NULL)
#define FSIZE 100 {
printf("Could not open file %s", fname);
int main() return 0;
{ }
FILE *fptr; // Extract characters from file and store in
int ctr = 0; character c
char fname[FSIZE]; for (c = getc(fptr); c != EOF; c = getc(fptr))
char c; if (c == '\n') // Increment count if this
printf("\n\n Read the file and count the number character is newline
of lines :\n"); ctr = ctr + 1;
fclose(fptr);
printf("--------------------------------------------------\n"); printf(" The lines in the file %s are : %d \n \n",
printf(" Input the file name to be opened : fname, ctr-1);
"); return 0;
scanf("%s",fname); }

Q8. Write a program in C to copy a file in another name.


#include <stdio.h> if(fptr2==NULL)
#include <stdlib.h> {
printf(" File does not found or error
void main() in opening.!!");
{ fclose(fptr1);
FILE *fptr1, *fptr2; exit(2);
char ch, fname1[20], fname2[20]; }
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
while(1)
printf("\n\n Copy a file in another name {
:\n"); ch=fgetc(fptr1);
printf("----------------------------------\n"); if(ch==EOF)
{
printf(" Input the source file name : "); break;
scanf("%s",fname1); }
else
fptr1=fopen(fname1, "r"); {
if(fptr1==NULL) fputc(ch, fptr2);
{ }
printf(" File does not found or error }
in opening.!!"); printf(" The file %s copied successfully in
exit(1); the file %s. \n\n",fname1,fname2);
} fclose(fptr1);
printf(" Input the new file name : "); fclose(fptr2);
scanf("%s",fname2); getchar();
fptr2=fopen(fname2, "w"); }

Q9 Write a program in C to merge two files and write it in a new file.


Ans:
#include <stdio.h> fnew=fopen(fname3, "w");
#include <stdlib.h>
if(fnew==NULL)
void main() {
{ // perror("Error Message ");
FILE *fold1, *fold2, *fnew; printf(" File does not exist or error in
char ch, fname1[20], fname2[20], fname3[30]; opening...!!\n");
printf("\n\n Merge two files and write it in a new exit(EXIT_FAILURE);
file :\n"); }
printf("---------------------------------\n"); while((ch=fgetc(fold1))!=EOF)
printf(" Input the 1st file name : "); {
scanf("%s",fname1); fputc(ch, fnew);
printf(" Input the 2nd file name : "); }
scanf("%s",fname2); while((ch=fgetc(fold2))!=EOF)
printf(" Input the new file name where to {
merge the above two files : "); fputc(ch, fnew);
scanf("%s",fname3); }
fold1=fopen(fname1, "r"); printf(" The two files merged into %s file
fold2=fopen(fname2, "r"); successfully..!!\n\n", fname3);
if(fold1==NULL || fold2==NULL) fclose(fold1);
{ fclose(fold2);
printf(" File does not exist or error in fclose(fnew);
opening!!\n"); }
exit(EXIT_FAILURE);
}

Q9. Explain command line argument in c language. What is argc and argv in C?
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
Ans: It is possible to pass some values from the command line to your C programs when they are
executed. These values are called command line arguments and many times they are important
for your program especially when you want to control your program from outside instead of hard
coding those values inside the code.
The command line arguments are handled using main() function arguments where argc refers to the
number of arguments passed, and argv[] is a pointer array which points to each argument passed to
the program.
argc and argv are used when you are starting a program from the command line, or want to pass
some variables to the program. (Dates back a bit!)
argc contains the number of arguments and argv is an array of pointers to the arguments which are
strings. EG: char *argv[]; 
The first argument is always the programs name.
For example, if you had a program called 'squareroot'. You could call it by: squareroot 4 squareroot
would have 2 in argc and two pointers, one to "squareroot" and one to "4" and it would return 2,
That is why main is declared as
int main(int argc, char *argv[]);

the return value is used by the calling program to see if the called program was ok. There is another
command line argument that sets enviroment variables, but that is only used by the real geeks and
hackers.

Following is a simple example which checks if there is any argument supplied from the command
line and take action accordingly −
#include <stdio.h>

int main( int argc, char *argv[] ) {

if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
When the above code is compiled and executed with single argument, it produces the following
result.
$./a.out testing
The argument supplied is testing
When the above code is compiled and executed with a two arguments, it produces the following
result.
$./a.out testing1 testing2
Too many arguments supplied.
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
When the above code is compiled and executed without passing any argument, it produces the
following result.
$./a.out
One argument expected
It should be noted that argv[0] holds the name of the program itself and argv[1] is a pointer to the first
command line argument supplied, and *argv[n] is the last argument. If no arguments are supplied,
argc will be one, and if you pass one argument then argc is set at 2.
You pass all the command line arguments separated by a space, but if argument itself has a space
then you can pass such arguments by putting them inside double quotes "" or single quotes ''. Let us
re-write above example once again where we will print program name and we also pass a command
line argument by putting inside double quotes −
#include <stdio.h>

int main( int argc, char *argv[] ) {

printf("Program name %s\n", argv[0]);

if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
When the above code is compiled and executed with a single argument separated by space but
inside double quotes, it produces the following result.
$./a.out "testing1 testing2"

Progranm name ./a.out


The argument supplied is testing1 testing2

Q10. What is a pre processor directive? Explain its types.


Ans: As the name suggests Preprocessors are programs that processes our source code before
compilation. There are a number of steps involved between writing a program and executing a
program in C. Let us have a look at these steps before we actually start learning about
Preprocessors.
Aditya Kumar, Asst. Professor, Mobile No. 8791178099

You can see the intermediate steps in the above diagram. The source code written by programmers
is stored in the file program.c. This file is then processed by preprocessors and an expanded source
code file is generated named program. This expanded file is compiled by the compiler and an object
code file is generated named program.obj . Finally the linker links this object code file to the object
code of the library functions to generate the executable file program.exe .
Preprocessor programs provides preprocessors directives which tell the compiler to preprocess the
source code before compiling. All of these preprocessor directive begins with a ‘#’ (hash) symbol.
This (‘#’) symbol at the beginning of a statement in a C/C++ program indicates that it is a pre-
processor directive. We can place these pre processor directives anywhere in our program. Examples
of some preprocessor directives are: #include, #define, #ifndef etc.
There are 4 main types of preprocessor directives:
1. Macros
2. File Inclusion
3. Conditional Compilation
4. Other directives
Let us now learn about each of these directives in details.
 Macros: Macros are piece of code in a program which is given some name. Whenever this
name is encountered by the compiler the compiler replaces the name with the actual piece of
code. The ‘#define’ directive is used to define a macro. Let us now understand macro definition
with the help of a program:
#include <iostream>

// macro definition
#define LIMIT 5
int main()
{
for (int i = 0; i < LIMIT; i++) {
std::cout << i << "\n";
}

return 0;
}
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
In the above program, when the compiler executes the word LIMIT it replaces it with 5. The word
‘LIMIT’ in macro definition is called macro template and ‘5’ is macro expansion.
Note: There is no semi-colon(‘;’) at the end of macro definition. Macro definitions do not need a semi-
colon to end.
Macros with arguments: We can also pass arguments to macros. Macros defined with arguments
works similarly as functions. Let us understand this with a program:
#include <iostream>

// macro with parameter


#define AREA(l, b) (l * b)
int main()
{
int l1 = 10, l2 = 5, area;

area = AREA(l1, l2);

std::cout << "Area of rectangle is: " << area;

return 0;
}
We can see from the above program that whenever the compiler finds AREA(l, b) in the program it
replaces it with the statement (l*b) . Not only this, the values passed to the macro template AREA(l,
b) will also be replaced in the statement (l*b). Therefore AREA(10, 5) will be equal to 10*5.
 File Inclusion: This type of preprocessor directive tells the compiler to include a file in the
source code program. There are two types of files which can be included by the user in the
program:
1. Header File or Standard files: These files contains definition of pre-defined functions
like printf(), scanf() etc. These files must be included for working with these functions.
Different function are declared in different header files. For example standard I/O
funuctions are in ‘iostream’ file whereas functions which perform string operations are in
‘string’ file.
Syntax:
2. #include< file_name >
where file_name is the name of file to be included. The ‘<‘ and ‘>’ brackets tells the
compiler to look for the file in standard directory.
3. user defined files: When a program becomes very large, it is good practice to divide it
into smaller files and include whenever needed. These types of files are user defined files.
These files can be included as:
4. #include"filename"
 Conditional Compilation: Conditional Compilation directives are type of directives which
helps to compile a specific portion of the program or to skip compilation of some specific part of
the program based on some conditions. This can be done with the help of two preprocessing
commands ‘ifdef‘ and ‘endif‘.
Syntax:
#ifdef macro_name
statement1;
statement2;
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
statement3;
.
.
.
statementN;
#endif
If the macro with name as ‘macroname‘ is defined then the block of statements will execute
normally but if it is not defined, the compiler will simply skip this block of statements.
 Other directives: Apart from the above directives there are two more directives which are not
commonly used. These are:
1. #undef Directive: The #undef directive is used to undefine an existing macro. This
directive works as:
2. #undef LIMIT
Using this statement will undefine the existing macro LIMIT. After this statement every
“#ifdef LIMIT” statement will evaluate to false.
3. #pragma Directive: This directive is a special purpose directive and is used to turn on
or off some features. This type of directives are compiler-specific i.e., they vary from
compiler to compiler. Some of the #pragma directives are discussed below:
 #pragma startup and #pragma exit: These directives helps us to specify the
functions that are needed to run before program startup( before the control passes to
main()) and just before program exit (just before the control returns from main()).
Note: Below program will not work with GCC compilers.
Look at the below program:
#include <stdio.h>

void func1();
void func2();

#pragma startup func1


#pragma exit func2

void func1()
{
printf("Inside func1()\n");
}

void func2()
{
printf("Inside func2()\n");
}

int main()
{
Aditya Kumar, Asst. Professor, Mobile No. 8791178099
void func1();
void func2();
printf("Inside main()\n");

return 0;
}
The above code will produce the output as given below when run on GCC compilers:
Inside main()
This happens because GCC does not supports #pragma startup or exit. However you can use the
below code for a similar output on GCC compilers.
#include <stdio.h>

void func1();
void func2();

void __attribute__((constructor)) func1();


void __attribute__((destructor)) func2();

void func1()
{
printf("Inside func1()\n");
}

void func2()
{
printf("Inside func2()\n");
}

int main()
{
printf("Inside main()\n");

return 0;
}
#pragma warn Directive: This directive is used to hide the warning message which are displayed
during compilation.
We can hide the warnings as shown below:
 #pragma warn -rvl: This directive hides those warning which are raised when a function which
is supposed to return a value does not returns a value.
 #pragma warn -par: This directive hides those warning which are raised when a function does
not uses the parameters passed to it.
 #pragma warn -rch: This directive hides those warning which are raised when a code is
unreachable. For example: any code written after the return statement in a function is
unreachable.
Aditya Kumar, Asst. Professor, Mobile No. 8791178099

You might also like