Programming in C 2
Programming in C 2
PROGRAMMING IN C
SEMESTER – I
PREPARED BY
Table of Content
II DECISION MAKING IN C 17
III ARRAYS IN C 27
V INTRODUCTION TO C POINTERS 57
2
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
UNIT-I
Semicolon ;
Semicolon ; is used to mark the end of a statement and beginning of another statement. Absence of
semicolon at the end of any statement, will mislead the compiler to think that this statement is not yet
finished and it will add the next consecutive statement after it, which may lead to compilation(syntax)
error.
#include
int main()
{
printf("Hello,World")
return 0;
}
In the above program, we have omitted the semicolon from the printf("...") statement, hence the
compiler will think that starting from printf up till the semicolon after return 0 statement, is a single
statement and this will lead to compilation error.
3
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
Comments
Comments are plain simple text in a C program that are not compiled by the compiler. We write
comments for better understanding of the program. Though writing comments is not compulsory, but
it is recommended to make your program more descriptive. It makes the code more readable.
There are two ways in which we can write comments.
Example of comments:
// This is a comment
/* This is a comment */
/* This is a long
and valid comment */
// this is not
a valid comment
4
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
do If static while
When we declare a variable or any function in C language program, to use it we must provide a
name to it, which identified it throughout the program, for example:
5
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
Character set
In C language characters are grouped into the following categories,
Operators in C Language
C language supports a rich set of built-in operators. An operator is a symbol that tells the compiler to
perform a certain mathematical or logical manipulation. Operators are used in programs to manipulate
data and variables.
C operators can be classified into following types:
• Arithmetic operators
• Relational operators
• Logical operators
• Bitwise operators
• Assignment operators
• Conditional operators
• Special operators
Arithmetic operators
C supports all the basic arithmetic operators. The following table shows all the basic arithmetic
operators.
Operator Description
6
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
% remainder of division
Relational operators
The following table shows all relation operators supported by C.
Operator Description
> Check if operand on the left is greater than operand on the right
Logical operators
C language supports following 3 logical operators. Suppose a = 1 and b = 0,
|| Logical OR (a || b) is true
7
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
Bitwise operators
Bitwise operators perform manipulations of data at bit level. These operators also perform shifting
of bits from right to left. Bitwise operators are not applied to float or double (These are datatypes, we
will learn about them in the next tutorial).
Operator Description
| Bitwise OR
^ Bitwise exclusive OR
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
The bitwise shift operator, shifts the bit value. The left operand specifies the value to be shifted and
the right operand specifies the number of positions that the bits in the value have to be shifted. Both
operands have the same precedence.
8
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
Example:
a = 0001000
b=2
a << b = 0100000
a >> b = 0000010
Assignment Operators
Assignment operators supported by C language are as follows.
= assigns values from right side operands to left side operand a=b
+= adds right operand to the left operand and assign the result to a+=b is same as
left a=a+b
-= subtracts right operand from the left operand and assign the a-=b is same as a=a-
result to left operand b
*= multiply left operand with the right operand and assign the a*=b is same as
result to left operand a=a*b
/= divides left operand with the right operand and assign the a/=b is same as
result to left operand a=a/b
%= calculate modulus using two operands and assign the result to a%=b is same as
left operand a=a%b
Conditional operator
The conditional operators in C language are known by two more names
1. Ternary Operator
2. ?: Operator
9
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
It is actually the if condition that we use in C language decision making, but using conditional
operator, we turn the if condition statement into a short and simple operator.
The syntax of a conditional operator is:
expression 1? expression 2: expression 3
Explanation:
• The question mark "?" in the syntax represents the if part.
• The first expression (expression 1) generally returns either true or false, based on which it is
decided whether (expression 2) will be executed or (expression 3)
• If (expression 1) returns true then the expression on the left side of " : " i.e. (expression 2) is
executed.
• If (expression 1) returns false then the expression on the right side of " : " i.e. (expression 3)
is executed.
Special operator
sizeof Returns the size of a variable sizeof(x) return size of the variable x
& Returns the address of a variable &x ; return address of the variable x
10
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
Integer type
Integers are used to store whole numbers.
Size and range of Integer type on 16-bit machine:
11
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
Character type
Character types are used to store characters value.
Size and range of Integer type on 16-bit machine
Void Type
Void type means no value. This is usually used to specify the type of functions which returns nothing.
We will get acquainted to this datatype as we start learning more advanced topics in C language, like
functions, pointers etc.
Variables in C Language
The naming of an address is known as variable. Variable is the name of memory location. Unlike
constant, variables are changeable, we can change value of a variable during execution of a program.
A programmer can choose a meaningful variable name. Example: total, height, age, etc.
Datatype of Variable
A variable in C language must be given a type, which defines what type of data the variable will
hold. It can be:
12
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
int a;
float b, c;
Initializing a variable means to provide it with a value. A variable can be initialized and defined in
a single statement, like:
int a = 10;
Let's write a program in which we will use some variables.
#include <stdio.h>
int main ()
/* variable definition: */
int a, b;
/* actual initialization */
a = 7;
13
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
b = 14;
c = a + b;
return 0;
Sum is : 21
Identifier Variable
Identifier is the name given to a variable, While, variable is used to name a memory
function etc. location which stores data.
An identifier can be a variable, but not all All variable names are identifiers.
identifiers are variables.
Example: Example:
// a variable // int variable
int studytonight; int a;
// or, a function // float variable
int studytonight() { float a;
..
}
14
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
We can also limit the number of digits or characters that can be input or output, by adding a
number with the format string specifier, like "%1d" or "%3s", the first one means a single numeric
digit and the second one means 3 characters, hence if you try to input 42, while scanf() has "%1d", it
will take only 4 as input. Same is the case for output.
15
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
The getchar() function reads a character from the terminal and returns it as an integer. This
function reads only single character at a time. The putchar() function displays the character passed to
it on the screen and returns the same character. This function too displays only a single character at
a time. In case you want to display more than one characters, use putchar() method in a loop.
#include <stdio.h>
void main( )
{
int c;
printf("Enter a character");
c = getchar();
putchar(c);
}
When you will compile the above code, it will ask you to enter a value. When you will enter the
value, it will display the value you have entered.
gets() & puts() functions
The gets() function reads a line from stdin(standard input) . The puts()function writes the
to stdout.
#include<stdio.h>
void main() {
char str[100];
printf("Enter a string");
gets( str );
puts(str );
getch();
When you will compile the above code, it will ask you to enter a string. When you will enter the
string, it will display the value you have entered.
16
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
UNIT-II
Decision making in C
Decision making is about deciding the order of execution of statements based on certain conditions
or repeat a group of statements until certain specified conditions are met. C language handles
decision-making by supporting the following statements,
• if statement
• switch statement
• conditional operator statement (? : operator)
• goto statement
1. Simple if statement
2. if....else statement
3. Nested if....else statement
4. Using else if statement
Simple if statement
The general form of a simple if statement is,
if(expression)
{
statement inside;
}
statement outside
If the expression returns true, then the statement-inside will be executed, otherwise statement-
inside is skipped and only the statement-outside is executed.
Example:
#include <stdio.h>
void main( )
{
int x, y;
x = 15;
y = 13;
if (x > y )
{
printf("x is greater than y");
}
}
x is greater than y
17
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
if...else statement
void main( )
{
int x, y;
x = 15;
y = 18;
if (x > y )
{
printf("x is greater than y");
}
else
{
printf("y is greater than x");
}
}
y is greater than x
18
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
else
{
statement block3;
}
if expression is false then statement-block3 will be executed, otherwise the execution continues and
enters inside the first if to perform the check for the next if block, where if expression 1 is true
the statement-block1 is executed otherwise statement-block2 is executed.
Example:
#include <stdio.h>
void main( )
{
int a, b, c;
printf("Enter 3 numbers...");
scanf("%d%d%d",&a, &b, &c);
if(a > b)
{
if(a > c)
{
printf("a is the greatest");
}
else
{
printf("c is the greatest");
}
}
else
{
if(b > c)
{
printf("b is the greatest");
}
else
{
printf("c is the greatest");
}
}
}
else if ladder
The general form of else-if ladder is,
if(expression1)
{
statement block1;
}
else if(expression2)
19
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
{
statement block2;
}
else if(expression3)
{
statement block3;
} else default statement;
The expression is tested from the top (of the ladder) downwards. As soon as a true condition is found,
the statement associated with it is executed.
Example:
void main( )
{
int a;
printf("Enter a number...");
scanf("%d", &a);
if(a%5 == 0 && a%8 == 0)
{
printf("Divisible by both 5 and 8");
}
else if(a%8 == 0)
{
printf("Divisible by 8");
}
else if(a%5 == 0)
{
printf("Divisible by 5");
}
else
{
printf("Divisible by none");
}
}
Switch statement in C
When you want to solve multiple option type problems, switch statement is used.
Switch statement is a control statement that allows us to choose only one choice among the many
given choices. The expression in switch evaluates to return an integral value, which is then compared
to the values present in different cases. It executes that block of code which matches the case value.
If there is no match, then default block is executed (if present).
The general form of switch statement is,
switch(expression)
{
case value-1:
block-1;
20
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
break;
case value-2:
block-2;
break;
case value-3:
block-3;
break;
default:
default-block;
break;
}
#include<stdio.h>
void main( )
{
int a, b, c, choice;
while(choice != 3)
{
printf("\n 1. Press 1 for addition");
printf("\n 2. Press 2 for subtraction");
printf("\n Enter your choice");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter 2 numbers");
scanf("%d%d", &a, &b);
c = a + b;
printf("%d", c);
break;
case 2:
printf("Enter 2 numbers");
scanf("%d%d", &a, &b);
c = a - b;
printf("%d", c);
break;
21
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
default:
printf("you have passed a wrong key");
printf("\n press any key to continue");
}
}
}
How it Works
The below diagram depicts a loop execution,
As per the above diagram, if the Test Condition is true, then the loop is executed, and if it is false
then the execution breaks out of the loop. After the loop is successfully executed the execution again
starts from the Loop entry and again checks for the Test condition, and this keeps on repeating.
The sequence of statements to be executed is kept inside the curly braces { } known as the Loop
body. After every execution of the loop body, condition is verified, and if it is found to be true the
loop body is executed again. When the condition check returns false, the loop body is not executed,
and execution breaks out of the loop.
22
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
Types of Loop
There are 3 types of Loop in C language, namely:
• while loop
• for loop
• do while loop
while loop
while loop can be addressed as an entry control loop. It is completed in 3 steps.
• Variable initialization.(e.g int x = 0;)
• condition(e.g while(x <= 10))
• Variable increment or decrement ( x++ or x-- or x = x + 2 )
Syntax :
variable initialization;
while(condition)
{
statements;
variable increment or decrement;
}
#include<stdio.h>
void main( )
{
int x;
x = 1;
while(x <= 10)
{
printf("%d\t", x);
/* below statement means, do x = x+1, increment x by 1*/
x++;
}
}
1 2 3 4 5 6 7 8 9 10
for loop
for loop is used to execute a set of statements repeatedly until a particular condition is satisfied. We
can say it is an open-ended loop.
23
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
Syntax:
for(initialization; condition; increment/decrement)
{
statement-block;
}
In for loop, we have exactly two semicolons, one after initialization and second after the condition.
In this loop we can have more than one initialization or increment/decrement, separated using comma
operator. But it can have only one condition.
#include<stdio.h>
void main( )
{
int x;
for(x = 1; x <= 10; x++)
{
printf("%d\t", x);
}
}
1 2 3 4 5 6 7 8 9 10
#include<stdio.h>
void main( )
24
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
{
int i, j;
/* first for loop */
for(i = 1; i < 5; i++)
{
printf("\n");
/* second for loop inside the first */
for(j = i; j > 0; j--)
{
printf("%d", j);
} }
}
1
21
321
4321
54321
do while loop
In some situations, it is necessary to execute body of the loop before testing the condition. Such
situations can be handled with the help of do-while loop. do statement evaluates the body of the loop
first and at the end, the condition is checked using while statement. It means that the body of the loop
will be executed at least once, even though the starting condition inside while is initialized to be false.
General syntax is,
do
{
.....
.....
}
while(condition);
#include<stdio.h>
void main()
{
int a, i;
a = 5;
i = 1;
do
{
printf("%d\t", a*i);
i++;
25
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
}
while(i <= 10);
}
5 10 15 20 25 30 35 40 45 50
2) continue statement
It causes the control to go directly to the test-condition and then continue the loop process. On
encountering continue, cursor leave the current cycle of loop, and starts with the next cycle.
26
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
UNIT-III
Arrays in C
In C language, arrays are referred to as structured data types. An array is defined as finite ordered
collection of homogenous data, stored in contiguous memory locations. (collection of elements of
same data type)
Here the words,
• finite means data range must be defined.
• ordered means data must be stored in continuous memory addresses.
• homogenous means data must be of similar data type.
Declaring an Array
Like any other variable, arrays must be declared before they are used. General form of array
declaration is,
data-type variable-name[size];
int arr[10];
Here int is the data type, arr is the name of the array and 10 is the size of array. It means array arr can
only contain 10 elements of int type.
Index of an array starts from 0 to size-1 i.e. first element of arr array will be stored at arr[0] address
and the last element will occupy arr[9].
Initialization of an Array
After an array is declared it must be initialized. Otherwise, it will contain garbagevalue(any random
value). An array can be initialized at either compile time or at runtime.
27
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
Compile time initialization of array elements is same as ordinary variable initialization. The general
form of initialization of array is,
data-type array-name[size] = { list of values };
One important thing to remember is that when you will give more initializer(array elements) than the
declared array size than the compiler will give an error.
#include<stdio.h>
void main()
{
int i;
int arr[] = {2, 3, 4}; // Compile time array initialization
for(i = 0 ; i < 3 ; i++)
{
printf("%d\t",arr[i]);
}
}
234
An array can also be initialized at runtime using scanf() function. This approach is usually used for
initializing large arrays, or to initialize arrays with user specified values. Example,
#include<stdio.h>
void main()
{
int arr[4];
int i, j;
printf("Enter array element");
for(i = 0; i < 4; i++)
{
scanf("%d", &arr[i]); //Run time array initialization
}
for(j = 0; j < 4; j++)
{
28
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
printf("%d\n", arr[j]);
}
}
/* Example */
int a[3][4];
Note: We have not assigned any row value to our array in the above example. It means we can
initialize any number of rows. But we must always specify number of columns, else it will give a
compile time error. Here, a 2*3 multi-dimensional matrix is created.
void main()
{
int arr[3][4];
int i, j, k;
printf("Enter array element");
29
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
data_type array_name[size1][size2]....[sizeN];
Three-dimensional array:
int three_d[10][20][30];
Total number of elements that can be stored in a multidimensional array can be calculated by
multiplying the size of all the dimensions.
For example:
The array int x[10][20] can store total (10*20) = 200 elements.
Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.
30
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
one-dimensional array of characters in C language. These are often used to create meaningful and
readable programs.
For example: The string "hello world" contains 12 characters including '\0' character which is
automatically added by the compiler at the end of the string.
Remember that when you initialize a character array by listing all of its characters separately then
you must supply the '\0' character explicitly.
Some examples of illegal initialization of character array are,
char ch[3] = "hell"; // Illegal
char str[4];
str = "hell"; // Illegal
void main()
{
char str[20];
printf("Enter a string");
scanf("%[^\n]", &str); //scanning the whole string, including the white spaces
printf("%s", str);
}
Another method to read character string with white spaces from terminal is by using
the gets() function.
char text[20];
gets(text);
printf("%s", text);
31
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
Method Description
1) strcat() function
strcat("hello", "world");
strcat() function will add the string "world" to "hello" i.e., it will ouput helloworld.
2)strlen() function
strlen() function will return the length of the string passed to it.
int j;
j = strlen("studytonight");
printf("%d",j);
12
3) strcmp() function
strcmp() function will return the ASCII difference between first unmatching character of two strings.
32
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
int j;
j = strcmp("study", "tonight");
printf("%d",j);
-1
4) strcpy() function
#include<stdio.h>
#include<string.h>
int main()
{
char s1[50];
char s2[50];
printf("%s\n", s2);
return(0);
}
StudyTonight
5) strrev() function
#include<stdio.h>
int main()
{
char s1[50];
33
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
• strncpy( ) function copies portion of contents of one string into another string.
• Example:
strncpy ( str1, str2, n) – It copies first n characters of str2 into str1.
If destination string length is less than source string, entire source string value won’t be copied
into destination string.
In this program, only 5 characters from source string “fresh2refresh” is copied into target string using
strncpy( ) function.
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = "fresh2refresh" ;
char target[20]= "" ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
strncpy ( target, source, 5 ) ;
printf ( "\ntarget string after strcpy( ) = %s", target ) ;
return 0;
}
COMPILE & RUN
OUTPUT:
source string = fresh2refresh
target string =
target string after strncpy( ) = fresh
2) strncat() function
• strncat( ) function concatenates (appends) portion of one string at the end of another string.
Example:
strncat ( str1, str2, n ); – First n characters of str2 is concatenated at the end of str1.
34
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = "fresh2refresh" ;
char target[ ]= "C tutorial" ;
Example:
strncmp ( str1, str2, n );
35
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
3)strstr() function
It can be used to locate a substring in a string.
Example:
strstr ( str1, str2);
searches str2 is contained in str1.
#include <stdio.h>
#include<string.h>
int main()
{
char str1[30] = "Learning C is awesome";
char str2 [15] = "C";
char *st;
st = strstr(str1, str2);
printf("%s", st);
return 0;
}
OUTPUT:
C is awesome
36
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
UNIT-IV
Function definition
A function definition ,also known as function implementation shall include the following elements
1. function name
2. function type
3. list of parameters
Syntax
function body
The function body contains the declarations and the statements(algorithm) necessary for performing
the required task. The body is enclosed within curly braces { ... } and consists of three parts.
37
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
The datatype of the value returned using the return statement should be same as the return type
mentioned at function declaration and definition. If any of it mismatches, you will get compilation
error.
Calling a function
When a function is called, control of the program gets transferred to the function.
functionName(argument1, argument2,...);
In the example above, the statement multiply(i, j); inside the main() function is function call.
38
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
It is possible to have a function with parameters but no return type. It is not necessary, that if a
function accepts parameter(s), it must return a result too.
While declaring the function, we have declared two parameters a and b of type int. Therefore, while
calling that function, we need to pass two arguments, else we will get compilation error. And the two
arguments passed should be received in the function definition, which means that the function header
in the function definition should have the two parameters to hold the argument values. These received
arguments are also known as formal parameters. The name of the variables while declaring, calling
and defining a function can be different.
Function Declaration
General syntax for function declaration is,
returntype functionName(type1 parameter1, type2 parameter2,...);
Like any variable or an array, a function must also be declared before its used. Function declaration
informs the compiler about the function name, parameters is accepted, and its return type. The actual
body of the function can be defined separately. It's also called as Function Prototyping. Function
declaration consists of 4 parts.
• return type
• function name
• parameter list
• terminating semicolon
returntype
When a function is declared to perform some sort of calculation or any operation and is expected to
provide with some result at the end, in such cases, a return statement is added at the end of function
body. Return type specifies the type of value(int, float, char, double) that function is expected to
return to the program which called the function.
Note: In case your function doesn't return any value, the return type would be void.
39
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
functionName
Function name is an identifier and it specifies the name of the function. The function name is any
valid C identifier and therefore must follow the same naming rules like other variables in C language.
parameter list
The parameter list declares the type and number of arguments that the function expects when it is
called. Also, the parameters in the parameter list receives the argument values when the function is
called. They are often referred as formal parameters.
include<stdio.h>
int multiply(int a, int b); // function declaration
int main()
{
int i, j, result;
printf("Please enter 2 numbers you want to multiply...");
scanf("%d%d", &i, &j);
40
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
#include<stdio.h>
void greatNum(); // function declaration
int main()
{
greatNum(); // function call
return 0;
}
void greatNum() // function definition
{
int i, j;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
if(i > j) {
printf("The greater number is: %d", i);
}
else {
printf("The greater number is: %d", j);
}
}
#include<stdio.h>
int greatNum(); // function declaration
int main()
{
int result;
result = greatNum(); // function call
printf("The greater number is: %d", result);
return 0;
}
int greatNum() // function definition
{
int i, j, greaterNum;
printf("Enter 2 numbers that you want to compare...");
41
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
#include<stdio.h>
void greatNum(int a, int b); // function declaration
int main()
{
int i, j;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
greatNum(i, j); // function call
return 0;
}
void greatNum(int x, int y) // function definition
{
if(x > y) {
printf("The greater number is: %d", x);
}
else {
printf("The greater number is: %d", y);
}
}
42
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
int i, j, result;
printf("Enter 2 numbers that you want to compare...");
What is Recursion?
Recursion is a special way of nesting functions, where a function calls itself inside it. We must have
certain conditions in the function to break out of the recursion, otherwise recursion will occur infinite
times.
function1()
{
// function1 body
function1();
// function1 body
}
Example: Factorial of a number using Recursion
#include<stdio.h>
int factorial(int x); //declaring the function
void main()
{
int a, b;
printf("Enter a number...");
scanf("%d", &a);
b = factorial(a); //calling the function named factorial
printf("%d", b);
}
int factorial(int x) //defining the function
{
int r = 1;
if(x == 1)
return 1;
else
43
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
return r;
}
How to pass Array to a Function in C
Whenever we need to pass a list of elements as argument to any function in C language, it is preferred
to do so using an array. But how can we pass an array as argument to a function? Let's see how it’s
done.
2. Or, we can have a pointer in the parameter list, to hold the base address of our array.
To understand how this is done, let's write a function to find out average of all the elements of the
array and print it.
We will only send in the name of the array as argument, which is nothing but the address of the
starting element of the array, or we can say the starting memory address.
#include<stdio.h>
float findAverage(int marks[]);
int main()
{
float avg;
int marks[] = {99, 90, 96, 93, 95};
avg = findAverage(marks); // name of the array is passed as argument.
printf("Average marks = %.1f", avg);
return 0;
}
float findAverage(int marks[])
{
int i, sum = 0;
float avg;
for (i = 0; i <= 4; i++) {
sum += marks[i];
}
avg = (sum / 5);
return avg; }
94.6
44
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
Here again, we will only pass the name of the array as argument.
#include<stdio.h>
void displayArray(int arr[3][3]);
int main()
{
int arr[3][3], i, j;
printf("Please enter 9 numbers for the array: \n");
for (i = 0; i < 3; ++i)
{
for (j = 0; j < 3; ++j)
{
scanf("%d", &arr[i][j]);
}
}
// passing the array as argument
displayArray(arr);
return 0;
}
void displayArray(int arr[3][3])
{
int i, j;
printf("The complete array is: \n");
for (i = 0; i < 3; ++i)
{
// getting cursor to new line
printf("\n");
for (j = 0; j < 3; ++j)
{
// \t is used to provide tab space
printf("%d\t", arr[i][j]);
}
}
}
45
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
7
8
9
The complete array is:
123
456
789
Passing Strings to Function
Strings can be passed to a function in a similar way as arrays.
Example:
#include <stdio.h>
void displayString(char str[]);
int main()
{ char str[50];
printf("Enter string: ");
gets(str);
displayString(str); // Passing string to a function.
return 0;
}void displayString(char str[])
{ printf("String Output: ");
puts(str); }
1. Call by Value
2. Call by Reference
Call by Value
Calling a function by value means, we pass the values of the arguments which are stored or copied
into the formal parameters of the function. Hence, the original values are unchanged only the
parameters inside the function changes.
46
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
#include<stdio.h>
Call by Reference
In call by reference, we pass the address(reference) of a variable as argument to any function. When
we pass the address of any variable as argument, then the function will have access to our variable,
as it now knows where it is stored and hence can easily update its value.
In this case the formal parameter can be taken as a reference or a pointer(don't worry about pointers,
we will soon learn about them), in both the cases they will change the values of the original variable.
#include<stdio.h>
void calc(int *p); // function taking pointer as argument
int main()
{
int x = 10;
calc(&x); // passing address of 'x' as argument
printf("value of x is %d", x);
return(0);
}
void calc(int *p) //receiving the address in a reference pointer variable
{
*p = *p + 10;
}
value of x is 20
47
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
In C language, each variable has a storage class which decides the following things:
• scope i.e where the value of the variable would be available inside a program.
• default initial value i.e if we do not explicitly initialize that variable, what will be its default
initial value.
• lifetime of that variable i.e for how long will that variable exist.
1. Automatic variables
2. External variables
3. Static variables
4. Register variables
#include<stdio.h>
void main(){
int detail;
// or
auto int details; //Both are same
}
48
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
One important thing to remember about global variable is that their values can be changed by any
function in the program.
#include<stdio.h>
int number; // global variable
void main()
{
number = 10;
printf("I am in main function. My value is %d\n", number);
fun1(); //function calling, discussed in next topic
fun2(); //function calling, discussed in next topic
}
/* This is function 1 */
fun1()
{
number = 20;
printf("I am in function fun1. My value is %d", number);
}
/* This is function 1 */
fun2()
{
printf("\nI am in function fun2. My value is %d", number);
}
I am in function main. My value is 10
I am in function fun1. My value is 20
I am in function fun2. My value is 20
Here the global variable number is available to all three functions and thus, if one function changes
the value of the variable, it gets changed in every function.
Note: Declaring the storage class as global or external for all the variables in a program can waste a
lot of memory space because these variables have a lifetime till the end of the program. Thus,
variables, which are not needed till the end of the program, will still occupy the memory and thus,
memory will be wasted.
extern keyword : The extern keyword is used with a variable to inform the compiler that this
variable is declared somewhere else. The extern declaration does not allocate storage for variables.
49
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
int main()
{
a = 10; //Error: cannot find definition of variable 'a'
printf("%d", a);
}
Example using extern in same file
int main()
{
extern int x; //informs the compiler that it is defined somewhere else
x = 10;
printf("%d", x);
}
int x; //Global variable x
3) Static variables
Scope: Local to the block in which the variable is defined
Default initial value: 0(Zero).
Lifetime: Till the whole program doesn't finish its execution.
A static variable tells the compiler to persist/save the variable until the end of program.
Instead of creating and destroying a variable every time when it comes into and goes out of
scope, static variable is initialized only once and remains into existence till the end of the program.
A static variable can either be internal or external depending upon the place of declaration. Scope
of internal static variable remains inside the function in which it is defined. External
static variables remain restricted to scope of file in which they are declared.
They are assigned 0 (zero) as default value by the compiler.
#include<stdio.h>
void test(); //Function declaration (discussed in next topic)
int main()
{
test();
test();
test();
}
void test()
{
static int a = 0; //a static variable
a = a + 1;
printf("%d\t",a);
}
123
50
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
4) Register variable
Scope: Local to the function in which it is declared.
Default initial value: Any random value i.e garbage value
Lifetime: Till the end of function/method block, in which the variable is defined.
Register variables inform the compiler to store the variable in CPU register instead of memory.
Register variables have faster accessibility than a normal variable. Generally, the frequently used
variables are kept in registers. But only a few variables can be placed inside registers. One application
of register storage class can be in using loops, where the variable gets used a number of times in the
program, in a very short span of time.
NOTE: We can never get the address of such variables.
Syntax :
register int number;
Note: Even though we have declared the storage class of our variable number as register, we cannot
surely say that the value of the variable would be stored in a register. This is because the number of
registers in a CPU are limited. Also, CPU registers are meant to do a lot of important work. Thus,
sometimes they may not be free. In such scenario, the variable works as if its storage class is auto.
• static - when we want the value of the variable to remain same every time.
• register - variables that are used in our program very oftenly.
• external - variables that are being used by almost all the functions in the program.
• If we do not have the purpose of any of the above-mentioned storage classes, then we should
use the automatic storage class.
C Structures
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.
For example: If I have to write a program to store Student information, which will have Student's
name, age, branch, permanent address, father's name etc, which included string values, integer values
etc, how can I use arrays for this problem, I will require something which can hold data of different
types together.
In structure, data is stored in form of records.
51
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
Defining a structure
struct keyword is used to define a structure. struct defines a new data type which is a collection of
primary and derived datatypes.
Syntax:
struct [structure_tag]
{
//member variable 1
//member variable 2
//member variable 3
...
}[structure_variables];
As you can see in the syntax above, we start with the struct keyword, then it's optional to provide
your structure a name, we suggest you to give it a name, then inside the curly braces, we have to
mention all the member variables, which are nothing but normal C language variables of different
types like int, float, array etc.
After the closing curly brace, we can specify one or more structure variables, again this is optional.
Note: The closing curly brace in the structure type declaration must be followed by a semicolon(;).
Example
struct Student
{
char name[25];
int age;
char branch[10];
// F for female and M for male
char gender;
};
Here struct Student declares a structure to hold the details of a student which consists of 4 data fields,
namely name, age, branch and gender. These fields are called structure elements or members.
Each member can have different datatype, like in this case, name is an array of chartype and age is
of int type etc. Student is the name of the structure and is called as the structure tag.
52
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
};
struct Student S1, S2; //declaring variables of struct Student
struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
}S1, S2;
Here S1 and S2 are variables of structure Student. However, this approach is not much recommended.
#include<stdio.h>
#include<string.h>
struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
};
int main()
{
struct Student s1;
53
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
/*
s1 is a variable of Student type and
age is a member of Student
*/
s1.age = 18;
/*
using string function to add name
*/
strcpy(s1.name, "Viraj");
/*
displaying the stored values
*/
printf("Name of Student 1: %s\n", s1.name);
printf("Age of Student 1: %d\n", s1.age);
return 0;
}
Name of Student 1: Viraj
Age of Student 1: 18
We can also use scanf() to give values to structure members through terminal.
Array of Structure
We can also declare an array of structure variables. in which each element of the array will represent
a structure variable. Example : struct employee emp[5];
The below program defines an array emp of size 5. Each element of the array emp is of
type Employee.
54
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
#include<stdio.h>
struct Employee
{
char ename[10];
int sal;
};
C Unions
Unions are conceptually similar to structures. The syntax to declare/define a union is also similar to
that of a structure. The only differences are in terms of storage. In structure each member has its
own storage location, whereas all members of union use a single shared memory location which is
equal to the size of its largest data member.
This implies that although a union may contain many members of different types, it cannot handle
all the members at the same time. A union is declared using the union keyword.
55
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
union item
{
int m;
float x;
char c;
}It1;
This declares a variable It1 of type union item. This union contains three members each with a
different data type. However only one of them can be used at a time. This is due to the fact that only
one location is allocated for all the union variables, irrespective of their size. The compiler allocates
the storage that is large enough to hold the largest variable type in the union.
In the union declared above the member x requires 4 bytes which is largest amongst the members for
a 16-bit machine. Other members of union will share the same memory address.
Example
#include <stdio.h>
union item
{
int a;
float b;
char ch; -26426
}; 20.1999
int main( ) z
{
union item it;
it.a = 12;
it.b = 20.2;
it.ch = 'z';
printf("%d\n", it.a);
printf("%f\n", it.b);
printf("%c\n", it.ch);
return 0;
}
56
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
UNIT-V
INTRODUCTION TO C POINTERS
A Pointer in C language is a variable which holds the address of another variable of same data type.
Pointers are used to access memory and manipulate the address.
Before we start understanding what pointers are and what they can do, let's start by understanding
what does "Address of a memory location" means?
Address in C
Whenever a variable is defined in C language, a memory location is assigned for it, in which its value
will be stored. We can easily check this memory address, using the & symbol.
If var is the name of the variable, then &var will give its address.
Let's write a small program to see memory address of any variable that we define in our program.
#include<stdio.h>
void main()
{
int var = 7;
printf("Value of the variable var is: %d\n", var);
printf("Memory address of the variable var is: %x\n", &var);
}
Value of the variable var is: 7
Memory address of the variable var is: bcc7a00
You must have also seen in the function scanf(), we mention &var to take user input for any
variable var.
scanf("%d", &var);
This is used to store the user inputted value to the address of the variable var.
Concept of Pointers
Whenever a variable is declared in a program, system allocates a location i.e an address to that
variable in the memory, to hold the assigned value. This location has its own address number, which
we just saw above.
Let us assume that system has allocated memory location 80F for a variable a.
int a = 10;
57
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
We can access the value 10 either by using the variable name a or by using its address 80F.
The question is how we can access a variable using its address? Since the memory addresses are also
just numbers, they can also be assigned to some other variable. The variables which are used to hold
memory addresses are called Pointer variables.
A pointer variable is therefore nothing but a variable which holds an address of some other variable.
And the value of a pointer variable gets stored in another memory location.
58
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
void main()
{
int a = 10;
int *ptr; //pointer declaration
ptr = &a; //pointer initialization
}
Pointer variable always point to variables of same data type. Let's have an example to showcase this:
#include<stdio.h>
void main()
{
float a;
int *ptr;
ptr = &a; // ERROR, type mismatch
}
If you are not sure about which variable's address to assign to a pointer variable while declaration, it
is recommended to assign a NULL value to your pointer variable. A pointer which is assigned
a NULL value is called a NULL pointer.
59
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
#include <stdio.h>
int main()
{
int *ptr = NULL;
return 0;
}
int main()
{
int a, *p; // declaring the variable and pointer
a = 10;
p = &a; // initializing the pointer
1. While declaring/initializing the pointer variable, * indicates that the variable is a pointer.
2. The address of any variable is given by preceding the variable name with Ampersand &.
3. The pointer variable stores the address of a variable. The declaration int *adoesn't mean
that a is going to contain an integer value. It means that a is going to contain the address of a
variable storing integer value.
4. To access the value of a certain address stored by a pointer variable, * is used. Here, the * can
be read as 'value at'.
int main()
{
int i = 10; // normal integer variable storing value 10
int *a; // since '*' is used, hence its a pointer variable
60
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
a = &i;
printf("Address of variable i is %u\n", a);
printf("Value at the address, which is stored by pointer variable a is %d\n", *a);
return 0;
}
void main()
{
float a;
int *ptr;
ptr = &a; // ERROR, type mismatch
}
If you are not sure about which variable's address to assign to a pointer variable while declaration, it
is recommended to assign a NULL value to your pointer variable. A pointer which is assigned
a NULL value is called a NULL pointer.
#include <stdio.h>
int main()
{
int *ptr = NULL;
return 0;
}
int main()
{
int m = 10, n = 20;
printf("m = %d\n", m);
printf("n = %d\n\n", n);
61
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
File Input/output in C
A file represents a sequence of bytes on the disk where a group of related data is stored. File is created
for permanent storage of data. It is a readymade structure.
In C language, we use a structure pointer of file type to declare a file.
FILE *fp;
C provides a number of functions that helps to perform basic file operations. Following are the
functions,
Function description
62
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
mode description
63
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
Closing a File
The fclose() function is used to close an already opened file.
General Syntax :
int fclose( FILE *fp);
Here fclose() function closes the file and returns zero on success, or EOF if there is an error in
closing the file. This EOF is a constant defined in the header file stdio.h.
int main()
{
FILE *fp;
64
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
char ch;
fp = fopen("one.txt", "w");
printf("Enter data...");
while( (ch = getchar()) != EOF) {
putc(ch, fp);
}
fclose(fp);
fp = fopen("one.txt", "r");
while( (ch = getc(fp)! = EOF)
printf("%c",ch);
// closing the file pointer
fclose(fp);
return 0;
}
Reading and Writing to File using fprintf() and fscanf()
#include<stdio.h>
struct emp
{
char name[10];
int age;
};
void main()
{
struct emp e;
FILE *p,*q;
p = fopen("one.txt", "a");
q = fopen("one.txt", "r");
printf("Enter Name and Age:");
scanf("%s %d", e.name, &e.age);
fprintf(p,"%s %d", e.name, e.age);
fclose(p);
do
{
fscanf(q,"%s %d", e.name, e.age);
printf("%s %d", e.name, e.age);
}
while(!feof(q));
}
In this program, we have created two FILE pointers and both are refering to the same file but in
different modes.
fprintf() function directly writes into the file, while fscanf() reads from the file, which can then be
printed on the console using standard printf() function.
65
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
• fseek(): It is used to move the reading control to different positions using fseek function.
• ftell(): It tells the byte location of current position of cursor in file pointer.
• rewind(): It moves the control to beginning of the file.
Error Handling in C
C language does not provide any direct support for error handling. However, a few methods and
variables defined in error.h header file can be used to point out error using the return statement in a
function. In C language, a function returns -1 or NULL value in case of any error and a global
variable errno is set with the error code. So, the return value can be used to check error while
programming.
What is errno?
Whenever a function call is made in C language, a variable named errno is associated with it. It is a
global variable, which can be used to identify which type of error was encountered while function
execution, based on its value.
3 No such process
5 I/O error
66
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
10 No child processes
11 Try again
12 Out of memory
13 Permission denied
C language uses the following functions to represent error messages associated with errno:
• perror(): returns the string passed to it along with the textual representation of the current errno
value.
• strerror() is defined in string.h library. This method returns a pointer to the string
representation of the current errno value.
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main ()
{
FILE *fp;
/*
If a file, which does not exist, is opened,
we will get an error
*/
fp = fopen("IWillReturnError.txt", "r");
printf("Value of errno: %d\n ", errno);
printf("The error message is : %s\n", strerror(errno));
perror("Message from perror");
67
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
return 0;
}
Value of errno: 2
The error message is: No such file or directory
Message from perror: No such file or directory
68