BCA 2nd Sem - Prog in C
BCA 2nd Sem - Prog in C
UNIT-I
C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972. It was
designed and written by a man named Dennis Ritchie. C is a computer programming
language. That means that you can use C to create lists of instructions for a computer to
follow. C is one of thousands of programming languages currently in use. C has been around
for several decades and has won widespread acceptance because it gives programmers
maximum control and efficiency. C is an easy language to learn. It is a bit more cryptic in its
style than some other languages, but you get beyond that fairly quickly. Possibly why C
seems so popular is because it is reliable, simple and easy to use. Moreover, in an industry
where newer languages, tools and technologies emerge and vanish day in and day out, a
language that has survived for more than 3 decades has to be really good.
What is algorithm?
An algorithm is a procedure or step-by-step instruction for solving a problem. They form the
foundation of writing a program.
• Input
• Tasks to be preformed
• Output expected
Write an algorithm that perform addition of two numbers and display the result of the
operation.
Algorithm :
1. START
2. INPUT A,B
3. C=A+B
4. PRINT C
5. STOP
There are 5 important characteristics or properties for a well defined algorithm. These are :-
Flowchart : Flow chart is very important tool by which we can understand the flow of
algorithm and program very easily . It is pictorial representation of step by step solution of a
problem. Programmer often uses it as a program planning tool for visually organizing step
necessary to solve a problem. It uses boxes of different shapes that denotes different type
of instruction. The set of rules that define how a particular problem can be solved in finite
number of steps is known as algorithm. A good algorithm help us to create a good program
A Flowchart is a diagram that uses graphic symbols to depict the nature and flow of the
steps in a process. Another name for this tool is "flow diagram."
Q1.) WRITE AN ALGORITHM AND DRAW A FLOWCHART FOR THE ADDITION OF TWO NUMBERS
WHICH ARE INPUT BY YOU AND DISPLAY THEIR SUM.
1. Starts
2. INPUT A,B
3. C=A+B
4. PRINT C
5. STOP
Control Structures in C :
Control Structures is used to control the flow of a program it includes decision control structure,
loop control structure, and case control control structure. To send the control out of sequence of
statements or from one part of program to another part we use control structure.
Decision Control Structure: There are several programming situation where we need to take
decisions, C language too must be able to perform different sets of actions depending on the
circumstances. C has three major decision making instructions the if statement, the if-
else statement, and the switch statement.
The If Statement: C uses the keyword if to implement the decision control instruction. The general
form of if statement or its syntax looks like this:
if ( this condition is true )
or
statement ;
statement ;
statement ;
The If-else Statement: The if statement by itself will execute a single statement, or a group of
statements, when the expression following if evaluates to true. It does nothing when the expression
evaluates to false. We can execute a statement or a group of statements if the expression evaluates
to evaluates to false. The general form of if-else statement or its syntax looks like this:
if ( condition )
do this ;
and this ;
else
do this ;
and this ;
Or
if ( condition )
do this ;
else
and this;
Why is modular programming important?
As programs grow in size, it becomes important to break them into separate parts (modules)
that communicate with rest of the program through a few well defined interfaces.
If we decompose the program into modules well is we can code each module
independently. Also if change happens we can localize changes to a particular module
without impacting the rest of the programs.
Character set of C :
character:- It denotes any alphabet, digit or special symbol used to represent information.
Use:- These characters can be combined to form variables. C uses constants, variables,
operators, keywords and expressions as building blocks to form a basic C program.
Character set:- The character set is the fundamental raw material of any language and
they are used to represent information. Like natural languages, computer language will also
have well defined character set, which is useful to build the programs.
ALPHABETS
Uppercase letters A-Z
Lowercase letters a-z
DIGITS
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
C Identifiers :
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;
Identifier names must be different from keywords.We 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.
Keywords in C :
A keyword is a reserved word. You cannot use it as a variable name, constant name, etc.
There are only 32 reserved words (keywords) in the C language.
Data Types in C :
A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.
There are the following data types in C language.
C Preprocessor Directives :
The C preprocessor is a micro processor that is used by compiler to transform your code
before compilation. It is called micro preprocessor because it allows us to add macros.
A macro is a segment of code which is replaced by the value of macro. Macro is defined by
#define directive. There are two types of macros:
1. Object-like Macros
2. Function-like Macros
Object-like Macros :
The object-like macro is an identifier that is replaced by value. It is widely used to represent
numeric constants. For example:
#define PI 3.14
Here, PI is the macro name which will be replaced by the value 3.14.
Function-like Macros :
C Functions :
In c, we can divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. A function can be
called multiple times to provide reusability and modularity to the C program. In other
words, we can say that the collection of functions creates a program. The function is also
known as procedure or subroutine in other programming languages.
Advantage of functions in C :
o By using functions, we can avoid rewriting same logic/code again and again in a
program.
o We can call C functions any number of times in a program and from any place in a
program.
o We can track a large C program easily when it is divided into multiple functions.
o Reusability is the main achievement of C functions.
o However, Function calling is always a overhead in a C program.
The syntax of creating function in c language is given below:
The gets() and puts() are declared in the header file stdio.h. Both the functions are involved
in the input/output operations of the strings.
C gets() function :
The gets() function enables the user to enter some characters followed by the enter key. All
the characters entered by the user get stored in a character array. The null character is
added to the array to make it a string. The gets() allows the user to enter the space-
separated strings. It returns the string entered by the user.
char[] gets(char[]);
C puts() function
The puts() function is very much similar to printf() function. The puts() function is used to
print the string on the console which is previously read by using gets() or scanf() function.
The puts() function returns an integer value representing the number of characters being
printed on the console. Since, it prints an additional newline character with the string, which
moves the cursor to the new line on the console, the integer value returned by puts() will
always be equal to the number of characters present in the string plus 1.
int puts(char[])
fprintf() function
The fprintf() function is used to write set of characters into file. It sends formatted output to
a stream.
C Operators :
An operator is simply a symbol that is used to perform operations. There can be many types
of operations like arithmetic, logical, bitwise, etc.
o Arithmetic Operators
o Relational Operators
o Shift Operators
o Logical Operators
o Bitwise Operators
o Ternary or Conditional Operators
o Assignment Operator
do-while loop in C :
The do-while loop continues until a given condition satisfies. It is also called post tested
loop. It is used when it is necessary to execute the loop at least once
1. do{
2. //code to be executed
3. }while(condition);
while loop in C :
The while loop in c is to be used in the scenario where we don't know the number of
iterations in advance. The block of statements is executed in the while loop until the
condition specified in the while loop is satisfied. It is also called a pre-tested loop.
1. while(condition){
2. //code to be executed
3. }
for loop in C
The for loop is used in the case where we need to execute some part of the code until the
given condition is satisfied. The for loop is also called as a per-tested loop. It is better to use
for loop if the number of iteration is known in advance.
1. for(initialization;condition;incr/decr){
2. //code to be executed
3. }
Types of Functions :
1. Library Functions: are the functions which are declared in the C header files such as
scanf(), printf(), gets(), puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the C programmer,
so that he/she can use it many times. It reduces the complexity of a big program and
optimizes the code.
UNIT-III
C Array :
An array is defined as the collection of similar type of data items stored at contiguous
memory locations. Arrays are the derived data type in C programming language which can
store the primitive type of data such as int, char, double, float, etc. It also has the capability
to store the collection of derived data types, such as pointers, structure, etc. The array is the
simplest data structure where each data element can be randomly accessed by using its
index number.
Advantage of C Array :
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Declaration of C Array :
data_type array_name[array_size];
The two-dimensional array can be defined as an array of arrays. The 2D array is organized as
matrices which can be represented as the collection of rows and columns. However, 2D
arrays are created to implement a relational database lookalike data structure. It provides
ease of holding the bulk of data at once which can be passed to any number of functions
wherever required.
data_type array_name[rows][columns];
int twodimen[4][3];
Here, 4 is the number of rows, and 3 is the number of columns.
In C, there are various general problems which requires passing more than one variable of
the same type to a function. For example, consider a function which sorts the 10 elements
in ascending order. Such a function requires 10 numbers to be passed as the actual
parameters from the main function. Here, instead of declaring 10 different numbers and
then passing into the function, we can declare and initialize an array and pass that into the
function. This will resolve all the complexity since the function will now work for any
number of values.
Syntax :
Function name(arrayname);
C Strings :
The string can be defined as the one-dimensional array of characters terminated by a null
('\0'). The character array or the string is used to manipulate text such as word or sentences.
Each character in the array occupies one byte of memory, and the last character must
always be 0. The termination character ('\0') is important in a string since it is the only way
to identify where the string ends. When we define a string as char s[10], the character s[10]
is implicitly initialized with the null in the memory.
1. By char array
2. By string literal
Syntax :
char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
We can also define the string by the string literal in C language. For example:
char ch[]="IITM";
POINTERS
C Pointers
The pointer in C language is a variable which stores the address of another variable. This
variable can be of type int, char, array, function, or any other pointer. The size of the pointer
depends on the architecture. However, in 32-bit architecture the size of a pointer is 2 byte.
Consider the following example to define a pointer which stores the address of an integer.
1. int n = 10;
2. int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type i
nteger.
Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known as
indirection pointer used to dereference a pointer.
EXAMPLE :
1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %x \n",p); // p contains the address of the number therefore
printing p gives the address of number.
7. printf("Value of p variable is %d \n",*p); // As we know that * is used to dereference a point
er therefore if we print *p, we will get the value stored at the address contained by p.
8. return 0;
9. }
Pointer to array :
1. int arr[10];
2. int *p[10]=&arr; // Variable p of type pointer is pointing to the address of an integer array ar
r.
Pointer to a function
1) Pointer reduces the code and improves the performance, it is used to retrieving strings,
trees, etc. and used with arrays, structures, and functions.
3) It makes you able to access any memory location in the computer's memory.
C Union
Like structure, Union in c language is a user-defined data type that is used to store the
different type of elements.
At once, only one member of the union can occupy the memory. In other words, we can say
that the size of the union in any instance is equal to the size of its largest element.
Defining union
The union keyword is used to define the union. Let's see the syntax to define union in c.
1. union employee
2. { int id;
3. char name[50];
4. float salary;
5. };
C STRUCTURE :
In C, there are cases where we need to store multiple attributes of an entity. It is not
necessary that an entity has all the information of one type only. It can have different
attributes of different data types. For example, an entity Student may have its name (string),
roll number (int), marks (float). To store such type of information regarding an entity
student, we have the following approaches:
o Construct individual arrays for storing names, roll numbers, and marks.
o Use a special data structure to store the collection of different data types.
o Structure in c is a user-defined data type that enables us to store the collection of
different data types. Each element of a structure is called a member. Structures ca;
simulate the use of classes and templates as it can store various information
o The struct keyword is used to define the structure.
1. struct structure_name
2. {
3. data_type member1;
4. data_type member2;
5. .
6. .
7. data_type memeberN;
8. };
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:
Example :
1. struct employee
2. { int id;
3. char name[50];
4. float salary;
5. };
p1.id
Nested Structure in C
Structure can be nested in two ways :
1. By separate structure
2. By Embedded structure
STORAGE CLASSES IN C :
Storage classes in C are used to determine the lifetime, visibility, memory location, and
initial value of a variable. There are four types of storage classes in C
o Automatic
o External
o Static
o Register
extern RAM Zero Global Till the end of the main program Maybe declared
anywhere in the program
static RAM Zero Local Till the end of the main program, Retains value
between multiple functions call
Automatic :
o Automatic variables are allocated memory automatically at runtime.
o The visibility of the automatic variables is limited to the block in which they are
defined.
The scope of the automatic variables is limited to the block in which they are
defined.
o The automatic variables are initialized to garbage by default.
o The memory assigned to automatic variables gets freed upon exiting from the block.
o The keyword used for defining automatic variables is auto.
o Every local variable is automatic in C by default.
Example :
1. #include <stdio.h>
2. int main()
3. {
4. int a; //auto
5. char b;
6. float c;
7. printf("%d %c %f",a,b,c); // printing initial default value of automatic variables a, b, and c.
8. return 0;
9. }
Static :
o The variables defined as static specifier can hold their value between the multiple
function calls.
o Static local variables are visible only to the function or the block in which they are
defined.
o A same static variable can be declared many times but can be assigned at only one
time.
o Default initial value of the static integral variable is 0 otherwise null.
o The visibility of the static global variable is limited to the file in which it has declared.
o The keyword used to define static variable is static.
EXAMPLE :
1. #include<stdio.h>
2. static char c;
3. static int i;
4. static float f;
5. static char s[100];
6. void main ()
7. {
8. printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f will be printed.
9. }
Register :
o The variables defined as the register is allocated the memory into the CPU registers
depending upon the size of the memory remaining in the CPU.
o We can not dereference the register variables, i.e., we can not use &operator for the
register variable.
o The access time of the register variables is faster than the automatic variables.
o The initial default value of the register local variables is 0.
o The register keyword is used for the variable which should be stored in the CPU
register. We can store pointers into the register, i.e a register can store the address
of a variable.
o Static variables can not be stored into the register since we can not use more than
one storage specifier for the same variable.
EXAMPLE:
o #include <stdio.h>
o int main()
o {
o register int a; // variable a is allocated memory in the CPU register. The initial default
value of a is 0.
o printf("%d",a);
o }
External :
o The external storage class is used to tell the compiler that the variable defined as
extern is declared with an external linkage elsewhere in the program.
o The variables declared as extern are not allocated any memory. It is only declaration
and intended to specify that the variable is declared elsewhere in the program.
o The default initial value of external integral type is 0 otherwise null.
o We can only initialize the extern variable globally, i.e., we can not initialize the
external variable within any block or method.
o An external variable can be declared many times but can be initialized at only once.
o If a variable is declared as external then the compiler searches for that variable to be
initialized somewhere in the program which may be extern or static. If it is not, then
the compiler will show an error.
EXAMPLE :
1. #include <stdio.h>
2. int main()
3. {
4. extern int a;
5. printf("%d",a);
6. }
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.
The fclose() function is used to close a file. The file must be closed after performing all the
operations on it. The syntax of fclose() function is given below:
The fscanf() function is used to read set of characters from file. It reads a word from the file
and returns EOF at the end of file.
Syntax :
The fputc() function is used to write a single character into file. It outputs a character to a
stream. Syntax :
The fgetc() function returns a single character from the file. It gets a character from the
stream. It returns EOF at the end of file.
C PROGRAMMING APPLICATIONS :
Bubble Sort :
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the
adjacent elements if they are in wrong order. Bubble sort in C to arrange numbers in
ascending order, we can modify it for descending order and can also sort strings. The bubble
sort algorithm isn't efficient as its average-case complexity is O(n2) and worst-case
complexity is O(n2).
Bubble sort program in C
#include <stdio.h>
int main()
{
int array[100], n, c, d, swap;
return 0;
}
SEARCHING :
LINEAR SEARCH :
Linear search in C to find whether a number is present in an array. If it's present, then at
what location it occurs. It is also known as a sequential search. It is straightforward and
works as follows: we compare each element with the element to search until we find it or
the list ends.
Linear search program in C
#include <stdio.h>
int main()
{
int array[100], search, c, n;
return 0;
}
BINARY SEARCH :
Binary search in C language to find an element in a sorted array. If the array isn't sorted, you
must sort it using a sorting technique such as merge sort. If the element to search is present
in the list, then we print its location. The program assumes that the input numbers are
in ascending order.s
#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];
first = 0;
last = n - 1;
middle = (first+last)/2;
return 0;
}