C Programming
C Programming
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 के दशक के प्रारं भ में यूनिक्स
ऑपरे टिग
ं सिस्टम के लिए बेल लैब्स में विकसित किया गया था।
Fixed number of keywords, including a set of control primitives, such as if, for, while, switch
and do while
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.
Control of function and object visibility to other files via extern and static attributes
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.
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.
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
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.
Case Use only lowercase. Lower and upper cases, both are allowed.
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.
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.
C – DATA TYPES:
There are four data types in C language. They are,
For example:
char ch = 'a';
// some code
ch = 'l';
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,
For example:
(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.
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.
1. Arithmetic operators
+
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
++
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
== 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 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
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
-----------------
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 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
4. Assignment operators
There are following assignment operators supported by C language:
Simple assignment operator, Assigns values from right C = A + B will assigne value of
=
side operands to left side operand A + B into C
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.
pre-increment
post-increment
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.
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
In pre-decrement first decrement the value of variable and then used inside the expression
(initialize into another variable).
Syntax
--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
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.
Operators Categories:
All the operators we have discussed above can be categorised into following categories:
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.
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.
Primary Expression
() [] . -> expr++ expr-- left-to-right
Operators
*/%
+-
>> <<
== !=
Binary Operators left-to-right
&
&&
||
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:
if(condition)
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 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.
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;
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.
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:
This process goes on until the test expression is false. When the test expression is false, the loop
terminates.
while (testExpression)
{
// statements inside the body of the loop
}
#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);
#include <stdio.h>
int main()
{
double number, sum = 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
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.
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.
#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).
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
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 −
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
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;
}
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];
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);
Q9. WAP to find whether inserted number is palindrome or not.
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':
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.
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) {
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.
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.
इसलिए अनिवार्य रूप से, फ़ंक्शन प्रोटोटाइप फ़ंक्शन के इनपुट / आउटपुट इंटरफ़ेस को निर्दिष्ट करता है यानी फ़ंक्शन
को क्या दे ना है और फ़ंक्शन से क्या अपेक्षा करनी है ।
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.
}
Related Function
Data Types
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;
}
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
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;
}
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.
#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:
Drawbacks of pointers in c:
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.
new_address= current_address + i * size_of(data type)
32-bit
64-bit
#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
64-bit
#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
64-bit
#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
64-bit
#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;
}
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.
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.
Q6. WAP C program to count vowels and consonants in a string using pointer
Ans:
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.
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:
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;
};
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;
If no. of variables are fixed, use 2nd approach. It saves your code to declare a variable in main()
function.
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;
}
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;
}
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.
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.
Bit filed Bit filed can not be defined in an Bit field can be defined in a structure.
array.
User-defined Arrays are not user-defined they are Structure is a user-defined datatype.
directly declared.
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
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 *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);
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:
fgetc()
Using
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() function is used to read formatted data from a file. In a C program, we use
fscanf() as below.
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);
ftell function is used to get current position of the file pointer. In a C program, we
use ftell() as below.
ftell(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.
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>
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>
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"
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>
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();
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 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