Complete C Notes
Complete C Notes
Machine Language
Machine language was the first programming language in the early days of computers.
The language which is understand by the computer hardware is called machine
language.
It consists of 0’s and 1’s.
Internally the computer consists of circuits which are made up of switches, transistors and
other electronic devices that can be in one of the two states: off or on, where off is
represented by 0 and on is represented by 1.
Assembly Language
Writing program in machine language is difficult.
The language which is represented using symbols or mnemonics is called as symbolic
language.
This language is not understandable by the computer. Hence, it must be translated to the
machine language using the assembler.
High Level Language
It is like natural language which can understandable by the programmer i.e., user.
The High-Level Language instructions are not understandable by the machine.
Compiler is used to convert High Level Language instructions into the Machine
Language instructions.
First High-Level Language is FORTRAN. Examples for High Level Languages are: C,
C++, JAVA, COBOL etc.,
Steps to Solve Logical and Numerical Problems
It is a multistep process that requires that:
1. Understand the problem
2. Develop Solution
Structure Chart
Algorithm / Pseudo code
Flowchart
3. Write the program
4. Test the program
Understand the problem
The first step in solving any problem is to understand it.
To solve any problem first you must understand the problem by reading the requirements
of the problem.
Once you understand it, review with user(customer) and system analyst.
Develop Solution
To develop a solution to a problem the following tools are needed.
1) Structure Chart:
It is also known as a hierarchy chart, shows the functional flow through your program.
It shows how the problem is broken into logical steps; each step will be a separate module.
It also shows the interaction between all the parts of your program. It is like the architect’s
blueprint.
The below two are used to design the individual parts of the program.
Algorithm / Pseudo Code
Flowchart
2) Algorithm: It is an ordered sequence of unambiguous and well-
defined instructions that perform some task and halts in finite time
Let's examine the four parts of this definition more closely.
1. Ordered Sequence: You can number the step.
2. Unambiguous and well-defined instructions: Each instruction should be clear, understand
without difficulty. Performs some task
3. Halts in finite time: Algorithm must terminate at some point.
Pseudo Code
Definition: English-like statements that follow a loosely defined syntax and are used to convey
the design of an algorithm.
Pseudo-code and Algorithm Construction
3) Assignment:
variable = "expression"
4) Input/Output:
5) Get/enter/read “variable", "variable", ...
6) Display/print "variable", "variable", ...
7) Conditional:
8) 1. if “condition"
1.1 (subordinate) statement 1
1.2 etc ...
9) 2. else
2.1 (subordinate) statement 2
2.2 etc ...
10) Iterative:
11) 3. while "condition"
3.1 (subordinate) statement 1
3.2 etc ...
Example1: To determine whether a student is passed or not
Example 2: Write an algorithm to determine a student’s final grade and indicate whether it is
passing or failing. The final grade is calculated as the average of four marks.
Flowchart to find the addition of two numbers Flowchart to find whether a given
year is a leap year or not
Start Start
c=a+b
if (year%4 = = 0)
Display C
Display non
Display leap year leap year
End
End
Syntax Errors
1) Spelling mistakes. 2) Missing out a colon or semicolon at end of a statement.
3) Missing out brackets. 4) Using upper case characters in key words e.g., IF
instead of if.
5) Missing out quotes. 6) Using tokens in the wrong order
Logical Errors
A logic error (or logical error) is a ‘bug’ or mistake in a program’s source code that
results in incorrect or unexpected behavior.
It is a type of runtime error that may simply produce the wrong output or may cause a
program to crash while running.
Creating and Running Programs
Creating and running programs takes place in 4 steps.
1. Writing and Editing the program.
2. Compiling.
3. Linking the program with the required library functions.
4. Executing the program.
2. Building a C Program
Example
Preprocessor Directives
⮚ The preprocessor directives provide instructions to the preprocessor, to include
functions from the system library, to define the symbolic constants and macro.
⮚ The preprocessor command always starts with symbol #. Example: #include<stdio.h>
⮚ Header file contains a collection of library files.
⮚ #include<stdio.h> includes the information about the standard input/output library.
⮚ The variables that are used in common by more than one function are called Global
Variables and are declared in global declaration section.
⮚ Every C program must have one main () function. All the statements of main are
enclosed in braces.
⮚ The program execution begins at main () function and ends at closing brace of the main
function.
⮚ C program can have any number of user-defined functions and they are generally placed
immediately after the main () function, although they may appear in any order.
⮚ All sections except the main () function may be absent when they are not required.
⮚ In the previous program, main () function returns an integer value to the operating
system.
⮚ Each statement in C program must end with; specifies that the instruction is ended.
⮚ A function can be called by its name, followed by a parenthesized list of arguments and
ended with semicolon.
⮚ In previous program main () function calls printf () function. Example: printf (“Hello
World! \n”);
Comments
⮚ To make the program more readable use the comments.
1)Block Comment:
/* Write a program to add two integer numbers */
Any characters between /* and */ are ignored by the compiler.
Comments may appear anywhere in a program.
/* and */ is used to comment the multiple lines of code which is ignored by the compiler.
Nested block comments are invalid like /* /* */
2)Line Comment:
⮚ To comment a single line, use two slashes //
/* Write a program to add two integer numbers */
#include<stdio.h> // It includes input, output header file
main ()
{
int a=10, b=20, c; // Variables declaration & initialization
c=a+b; // Adding two numbers
printf (“Sum of a and b=%d”, c);
return 0;
}
C Tokens:
In a passage of text, individual words and punctuation marks are called as tokens.
The compiler splits the program into individual units, are known as C tokens. C has six types of
tokens.
Character Set
⮚ Characters are used to form words, numbers and expressions.
⮚ Characters are categorized as
1)Letters 2) Digits 3) Special characters 4) White spaces.
Letters: (Upper Case and Lower Case)
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
Digits: 0123456789
Special Characters: ’"()*+-/:= !&$;<>%?,. ˆ#@˜‘{}[]\|
White Spaces: Blank Space, Horizontal Space, Carriage Return.
Identifiers
⮚ Identifiers are names given to various programming elements such as variables,
constants, and functions.
⮚ It should start with an alphabet or underscore, followed by the combinations of
alphabets and digits. ex: a=10 or _a=10valid, 1a=10 0r $a=10 invalid
⮚ No special character is allowed except underscore.
⮚ An Identifier can be of arbitrarily long. Some implementation of C recognizes only the
first 8 characters and some other recognize first 32 Characters.
The following are the rules for writing identifiers in C:
⮚ First character must be alphabetic character or underscore.
⮚ Must consist only of alphabetic characters, digits, or underscore.
⮚ Should not contain any special character, or white spaces. ex sum of invalid,
sum_ofvalid
⮚ Should not be C keywords.
⮚ Case matters (that is, upper and lowercase letters). Thus, the names count and Count
refer to two different identifiers. Because C is case sensitive.
Variables
Variable is a valid identifier which is used to store the value in the memory location, that
value varies during the program execution
⮚ When you create variables, the declaration gives them a symbolic name and the definition
reserves memory for them.
⮚ A variable’s type can be any of the data types, such as character, integer or real except
void.
⮚ C allows multiple variables of the same type to be defined in one statement. Example:
int a, b;
⮚ There are some restrictions on the variable names (same as identifiers):
Types of variables:
⮚ Global Variables: The variables which are declared at the starting of the
program are called as global variable. They are visible to all the parts of
the program.
⮚ Local Variables: The variables which are declared in a function are called
local variables to that function. These variables visible only within the
function
⮚ Variable declaration and definition:
⮚ Example: int a; a Variable name
#include<stdio.h>
main ()
c=a+b;
Constants
printf (“sum of a and b=%d\n”, c);
⮚ Constants
return 0; are data values that cannot be changed during the program execution.
Types of constants:
⮚ Character constants
1)Single character constants 2) string constants.
⮚ Numeric constants.
1)integer constant 2) real constants.
Type qualifier const
⮚ One way to use the constant is with memory constants. Memory constants use a C type
qualifier; const. This indicates that the data cannot be changed.
const type identifier= value;
const float pi=3.14;
#include<stdio.h>
void main ()
{
float area, radius=3.0;
const float pi=3.14;
area=pi*radius*radius;
printf (“area of a circle= %f”, area);
}
String constants
⮚ String is a collection of characters or sequence of characters enclosed in double
quotes.
⮚ The characters may be letters, numbers, special characters and blank space.
Example: “snist” “2011” “A”.
Backslash \escape characters
symbol .
Numeric Constants
integer constant: It is a sequence of digits that consists numbers from 0to 9.
Example: 23 -678 0 +78
Rules:
1. integer constant have at least one digit.
2. No decimal points.
3. No commas or blanks are allowed.
4. The allowable range for integer constant is -32768 to 32767.
To store the larger integer constants on 16-bit machine use the qualifiers such as U, L, UL.
Real constants: The numbers containing fractional parts like 3.14
Example:1.9099 -0.89 +3.14
Real constants are also expressed in exponential notation.Mantissa e exponent
⮚ A number is written as the combination of the mantissa, which is followed by
the prefix e or E, and the exponent.
Example: 87000000 = 8.7e7
- 550 = -5.5e2
0.00000000031 = 3.1e-10
Examples of real constants
Data types in C
⮚ Data types are used to indicate the type of value represented or stored in a variable, the
number of bytes to be reserved in memory, the range of values that can be represented in
memory, and the type of operation that can be performed on a particular data value.
⮚ ANSI C supports 3 categories of data types:
1)Built-in data types 2) Derived data types 3) User Defined data types
Built-in data types:
Built-in data types are also known as primitive data types. C uses the following
primitive data types.
int integer quantity
char character (stores a single character)
float floating point number
double floating-point number
Integer data type:
⮚ An integer number (also called whole number) has no fractional part or decimal point.
⮚ The keyword int is used to specify an integer variable.
⮚ It occupies 2 bytes (16 bits) or 4 bytes (32 bits), depending on the machine architecture.
⮚ 16-bit integer can have values in the range of -32768 to 32767
⮚ One bit is used for sign.
void data type:
⮚ Defines an empty data type which can then be associated with some data types. It is
useful with pointers.
Note: sizeof (short) ≤ sizeof (int) ≤ sizeof (long) ≤ sizeof (long long)
Character Data Type:
⮚ The shortest data type is character.
⮚ The keyword char is used to declare a variable of a character type.
⮚ It is stored in 1 byte in memory.
⮚ Corresponding integer values for all characters are defined in ASCII (American Standard
Code for Information Interchange).
⮚ Example: character constant ‘a’ has an int value 97, ‘b’ has 98, ‘A’ has 65 etc.
⮚ Character can have values in the range of -128 to 127.
Float datatype:
⮚ The keyword float is used to declare a variable of the type float.
⮚ The float type variable is usually stored in 32 bits, with 6 digits of precision.
⮚ A float variable can have values in the range of 3.4E-38 to 3.4 E+38.
double data type:
⮚ A floating point number can also be represented by the double data type.
⮚ The data type double is stored on most machines in 64 bits which is about 15 decimal
places of accuracy.
⮚ To declare a variable of the type double, use the keyword double.
⮚ A double variable can have values in the range of 1.7E-308 to +1.7E+308.
Type Modifiers:
⮚ The basic data types may have various modifiers (or qualifiers) preceding them, except
type ‘void’.
⮚ A modifier is used to alter the meaning of the base data type to fit the needs of various
situations more precisely.
⮚ The modifiers signed, unsigned, long, short may be applied to integer base types.
⮚ The modifiers unsigned and signed may be applied to characters.
⮚ The modifier long may also be applied to double.
⮚ The difference between signed and unsigned integers is in the way high-order bit (sign
bit) of the integer is interpreted.
⮚ If sign bit is 0, then the number is positive; if it is 1, then the number is negative.
Derived data types and User defined data types are the combination
of primitive data types. They are used to represent a collection of data.
They are: 1) Arrays 2) Pointers 3) Structures 4) Unions 5) Enumeration
Note: Number of bytes and range given to each data type is platform
dependent.
Data types in c
Formatted input/output
⮚ The data is to be arranged in a particular format. The data is input to and output from a
stream.
⮚ A stream is a source or destination of the data, it is associated with a physical device such
as terminals (keyboard, monitor).
⮚ C has two forms of streams: Text Stream and Binary Stream.
⮚ Text Stream consists of sequence of characters.
⮚ Binary Stream consists of a sequence of data in 0’s and 1’s.
⮚ A terminal keyboard and monitor can be associated only with a text stream.
⮚ A keyboard is a source for a text stream; a monitor is a destination for a text stream.
⮚ The data is formatted using the printf and scanf functions.
⮚ scanf () converts the text stream coming from the keyboard to data values (char, int, etc.,)
and stores them in the program variables.
⮚ printf () converts the data stored in variables into the text stream for output the keyboard.
printf () takes the set of data values and converts them to text stream using formatting
instructions contained in a format control string.
⮚ Format specifier specifies the data values type, size and display position.
⮚ Printf statement takes two arguments
1. Control String and
2. Data Values (Variables)
⮚ Control string contains the format specifiers and some text.
Syntax: printf (“control string”, var1, var2…, varn);
Example: int a=10, b=20;
printf (“a=%d b=%d”, a,b);
scanf(“control string”,&var1,&var2.. &varn);
⮚ control string includes format specifiers and specifies the field width.
⮚ scanf requires variable addresses in the address list.
Operators
⮚ C supports a rich set of operators.
⮚ An operator is a symbol that tells the computer to perform mathematical or logical
operations.
Operators are used in C to operate on data and variables.
expressio
Operators: Operands: x, y, z
X=Y+Z =, +
Relational Operators:
⮚ Relational operators are used to compare the relationship between two operands.
Syntax: exp1 relational operator exp2
⮚ The value of a relational expression is either one or zero.
⮚ It is one if the specified relation is true and zero if the relation is false.
⮚ Relational operators are used by if, while and for statements.
Logical Operators
⮚ Logical operators used to test more than one condition and make decision. Yields a value
either one or zero.
⮚ Syntax: operand1 logical operator operand2 or
logical operator operand
⮚ Example: (x<y) && (x= = 8)
Assignment Operators
⮚ Assignment operators are used to assign the result of an expression to a variable.
⮚ Assignment Operator is =
Syntax: variable = expression;
⮚ Types of assignment:
– Single Assignment Ex: a = 10;
– Multiple Assignment Ex: a=b=c=0;
– Compound Assignment Ex: c = a + b;
Special Operators
⮚ C supports the following special category of operators.
& Address operator
* Indirection operator
, Comma operator
sizeof () Size of operator
. and 🡪 Member selection Operators
comma operator:
⮚ It doesn’t operate on data but allows more than one expression to appear on the same
line.
Example: int i = 10, j = 20;
printf (%d %.2f %c”, a, f, c);
j = (i = 12, i + 8); //i is assigned 12 added to 8 produces 20
sizeof Operator:
⮚ It is a unary operator (operates on a single value).
⮚ Produces a result that represent the size in bytes.
Syntax: sizeof(datatype);
Example: int a = 5;
sizeof (a); //produces 2
sizeof(char); // produces 1
sizeof(int); // produces 2
Precedence and Association rules among operators
⮚ Precedence is used to determine the order in which different operators in a complex
expression are evaluated.
⮚ Associativity is used to determine the order in which operators with the same precedence
are valuated in a complex expression.
⮚ Every operator has a precedence.
⮚ The operators which has higher precedence in the expression is
evaluated first.
Example: a=8+4*2; a=?
#include<stdio.h>
void main ()
{ Output: x=11, a=11
a=10;
x=++a;
printf (“x=%d, a=%d”, x, a);
}
Unary expression: It is an expression which consists of unary operator followed by the operand
Binary Expressions:
⮚ In binary expression operator must be placed in between the two operands.
⮚ Both operands of the modulo operator (%) must be integral types.
The left operand in an assignment expression must be a single variable.
⮚ Compound statements are used to group the statements into a single executable unit.
⮚ It consists of one or more individual statements enclosed within the braces { }
Decision Control Structures
⮚ The decision is described to the computer as a conditional statement that can be answered
either true or false.
⮚ If the answer is true, one or more action statements are executed.
⮚ If the answer is false, then a different action or set of actions is executed.
Types of decision control structures:
1) If 2) if..else 3) nested if…else 4) else if ladder
5) dangling else 6) switch statement
Decision Control Statement: if
The general form of a simple if statement is:
if (condition)
statement-block;
Enter Example:
main ()
{
F
Conditi int a=10, b=20;
on
if(a>b)
T {
printf(“%d”,b);
Exit }
Decision Control Statement: if..else
if (condition1)
statements1;
else if (condition2)
statements2;
else if (condition3)
statements3;
else if (condition4)
statements4;
……
else if (condition n)
statements n;
else
default statement;
statement x;
Dangling else
To avoid dangling else problem place the inner if statement with in the curly braces.
Example1
⮚ If you want to execute only one case-label, C provides break statement.
⮚ It causes the program to jump out of the switch statement, that is go to the closing
braces (}) and continues the remaining code of the program.
⮚ If we add break to the last statement of the case, the general form of switch case is
as follows:
Example2 for switch statement:
Concept of a loop
⮚ The real power of computers is in their ability to repeat an operation or a series of
operations many times.
⮚ This repetition, called looping, is one of the basic structured programming concepts.
⮚ Each loop must have an expression that determines if the loop is done.
⮚ If it is not done, the loop repeats one more time; if it is done, the loop terminates.
While loop
⮚ The "while" loop is a generalized looping structure that employs a variable or expression
for testing the condition.
⮚ It is a repetition statement that allows an action to be repeated while some conditions
remain true.
⮚ The body of while statement can be a single statement or compound statements.
⮚ It doesn’t perform even a single operation if condition fails.
#include<stdio.h>
void main ()
scanf("%d",&n);
while (n! = 0)
do while
⮚ The “do while" loop is a repetition statement that allows an action to be done at least
once and then condition is tested.
⮚ On reaching do statement, the program proceeds to evaluate the body of the loop first.
⮚ At the end of the loop, condition statement is evaluated.
⮚ If the condition is true, it evaluates the body of the loop once again.
⮚ This process continues up to the condition becomes false.
Example 3: To print Fibonacci sequence for the given number.
#include<stdio.h>
void main ()
i=1;
do
c=a+b;
i++;
a=b;
#include} <stdio.h>
while(i<=10);
}void main ()
int i = 1, n=5;
do
printf (“ %d * %d = %d “, n, i, n*i);
i = i + 1;
} while ( i<= 5);
break
⮚ When a break statement is enclosed inside a block or loop, the loop is immediately
exited and program continues with the next statement immediately following the loop.
⮚ When loop are nested break only exit from the inner loop containing it.
The format of the break statement is:
continue
⮚ When a continue statement is enclosed inside a block or loop, the loop is
to be continued with the next iteration.
⮚ The continue statement tells the compiler, skip the following statements
and continue with the next iteration.
⮚ The format of the continue statement is:
Example 5: Program to demonstrate continue statement.
#include<stdio.h>
void main ()
{
int i;
for (i=1; i<=5; i++)
{
if (i = = 3)
continue;
printf (" %d”, i); output: 1 2 4 5
}
}
ARRAY
Array is the collection of similar data types or collection of similar entity stored in
contiguous memory location. Array of character is a string. Each data item of an array is
called an element. And each element is unique and located in separated memory location.
Each of elements of an array share a variable but each element having different index no.
known as subscript.
An array can be a single dimensional or multi-dimensional and number of subscripts
determines its dimension. And number of subscripts is always starts with zero. One
dimensional array is known as vector and two-dimensional arrays are known as matrix.
ADVANTAGES: array variable can store more than one value at a time where
other variable can store one value at a time.
Example: int a[100];
One Dimensional Arrays:
One dimensional array is a linear list consisting of related and similar data items.
In memory all the data items are stored in contiguous memory locations one after the
other.
Syntax for declaring One Dimensional Arrays:
elementType arrayName[size];
To declare an array, we just add an array size.
Example: int temp [5]; //Creates an array of 5 integer elements.
Example: double stockprice [31];
//Creates an array of 31 double elements.
Total size in byte for 1D array is:
Total bytes=size of (data type) * size of array.
Example: if an array declared is:
int [20];
Total byte= 2 * 20 =40 byte.
Initializing One Dimensional Arrays
Option 1: Initializing all memory locations:
If you know all the data at compile time, you can specify all your data within brackets:
int temp [5] = {75, 79, 82, 70, 68};
During compilation, 5 contiguous memory locations are reserved by the compiler for the
variable temp and all these locations are initialized as
shown below.
If the size of integer is 2 bytes, 10 bytes will be allocated for the variable temp.
Option 2: Initialization without size:
If you omit the size of an array, but specify an initial set of data, then the
compiler will automatically determine the size of an array.
int temp [] = {75, 79, 82, 70, 68};
Option 3 Partial Array Initialization:
If the number of values to be initialized is less than the size of the array, then the
elements are initialized in the order from 0th location.
The remaining locations will be initialized to zero automatically.
int temp [5] = {75, 79, 82};
OR
int c [][3] = {
{1,3,0},
{-1,5,9}
};
OR
-------
-------
{ temp=x [0];
} }
Character Arrays and Strings:
String is a sequence of characters.
If ‘\0’ is present after a series of characters in an array, then that array becomes a string
otherwise it is a character array.
Example:
char arr[] = {'a', 'b', 'c'}; //This is an array
char arr [] = {'a', 'b', 'c', '\0'}; //This is a string
Ragged Arrays
Each row in a two-dimensional array is itself an array. So, the rows can
have different lengths. Such an array is known as a ragged array.
For example,
int [][] matrix = {
{1, 2, 3, 4, 5},
{2, 3, 4, 5},
{3, 4, 5},
{4, 5},
{5}
};
Searching and Sorting
Searching is the process of finding a particular element in an array.
Sorting is the process of rearranging the elements in an array so that they are stored in
some well-defined order.
Linear Search:
A linear or sequential search of an array begins at the beginning of the array and
continues until the item is found or the entire array has been searched.
1)It is the basic searching technique 2) Very easy to implement
3)The array DOESN’T have to be sorted 4) Could be very slow.
5) All array elements must be visited if the search fails.
//Program to find a number in the array using sequential search.
main () {
int a [10], i, n, m, c=0;
printf ("Enter the size of an array: ");
scanf ("%d”, &n);
printf ("Enter the elements of the array: ");
for (i=0; i<=n-1; i++) {
scanf ("%d”, &a[i]);
}
printf ("Enter the number to be search: ");
scanf ("%d”, &m);
for (i=0; i<=n-1; i++) {
if(a[i]==m) {
c=1; Output:
Pass-1
32 51 27 85 66 23 13 57
no swap
32 27 51 85 66 23 13 57
32 27 51 85 66 23 13 57
no swap
32 27 51 66 85 23 13 57
32 27 51 66 23 85 13 57
32 27 51 66 23 13 85 57
32 27 51 66 23 13 57 85
Pass-2
27 32 51 66 23 13 57 85
27 32 51 66 23 13 57 85
no swap
27 32 51 66 23 13 57 85
no swap
27 32 51 23 66 13 57 85
27 32 51 23 13 66 57 85
27 32 51 23 13 57 66 85
//C program to sort the numbers using bubble sort
main() {
int arr[50],temp,i,j,n;
printf("\nEnter any Value less Than 50:");
scanf("%d",&n);
printf("\n\tEnter The Values into ARRAY: ");
Output:
for(i=0;i<n;i++)
scanf("%d",&arr[i]); Enter any Value less Than 50: 5
for(i=1;i<n;i++) {
Enter The Values into ARRAY: 1 5 0 3 2
for(j=0;j<n-i;j++) {
if(arr[j] >arr[j+1]) { Sorted Series: 0 1 2 3 5
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
printf(“\nSorted Series:");
for(i=0;i<n;i++) {
printf("\n %d",arr[i]);
}
}
Selection Sort
Procedure:
Selection sort involved scanning through the list to find (or select) the smallest element
and swap it with the first element.
The rest of the list is then search for the next smallest and swap it with the second
element.
This process is repeated until the rest of the list reduces to one element, by which time the
list is sorted.
The following table shows how selection sort works.
Example:
pass-1 11 33 44 55 88 66 22 77
pass-2 11 22 44 55 88 66 33 77
pass-3 11 22 33 55 88 66 44 77
pass-4 11 22 33 44 88 66 55 77
pass-5 11 22 33 44 55 66 88 77
pass-6 11 22 33 44 55 66 88 77
pass-7 11 22 33 44 55 66 77 88
pass-8 11 22 33 44 55 66 77 88
return loc;
}
Insertion Sort
Using insertion sort an element is inserted in correct location.
Procedure:
Begin with a sequence of n elements in arbitrary order
Initially assume the sorted segment contains the first element.
Let x be the next element to be inserted in sorted segment, pull x “out of the
way”, leaving a vacancy.
Repeatedly compare x to the element just to the left of the vacancy, and as long as
x is smaller, move that element into the vacancy, else put x in the vacancy.
Repeat the next element that has not yet examined.
Example:
Elements in array before swapping: 77 33 44 11 88 22 66 55
pass-1 77 33 44 11 88 22 66 55
pass-2 33 77 44 11 88 22 66 55
pass-3 33 44 77 11 88 22 66 55
pass-4 11 33 44 77 88 22 66 55
pass-5 11 33 44 77 88 22 66 55
pass-6 11 22 33 44 77 88 66 55
pass-7 11 22 33 44 66 77 88 55
pass-8 11 22 33 44 55 66 77 88
Elements in array after sorting: 11 22 33 44 55 66 77 88
printf ("\nEnter the size of array: "); for (k=0; k<n; k++)
printf("\n"); j=j-1;
Recursive implementation with the left most array entry selected as the pivot element
/*Write a c program to implement the quick sort*/
#include<stdio.h>
void quicksort (int [10], int, int);
int main () {
int x [20], size, i;
printf ("\nEnter size of the array: ");
scanf ("%d”, &size);
printf ("\nEnter %d elements: “, size);
for (i=0; i<size; i++)
scanf ("%d”, &x[i]);
quicksort (x,0, size-1);
printf ("\nSorted elements: ");
for (i=0; i<size; i++)
printf (" %d”, x[i]);
getch ();
return 0;
}
void quicksort (int x [10], int first, int last) {
int pivot, j, temp, i;
if(first<last) {
pivot=first; i=first; j=last;
while(i<j) {
while(x[i]<=x[pivot]&&i<last)
i++;
while(x[j]>x[pivot])
j--;
if(i<j) {
temp=x[i]; x[i]=x[j]; x[j]=temp;
}
}
temp=x[pivot];
x[pivot]=x[j];
x[j]=temp;
quicksort (x, first, j-1);
quicksort (x, j+1, last);
}
}
Merge Sort
In this method, the elements are divided into partitions until each partition has sorted
elements.
Then, these partitions are merged and the elements are properly positioned to get a fully
sorted list.
Procedure/Algorithm:
1. Split array A [0.n-1] into about equal halves and make copies of each half in arrays B and C.
2. Sort arrays B and C recursively.
3. Merge sorted arrays B and C into array A as follows:
3.1. Repeat the following until no elements remain in one of the arrays:
3.1.1 Compare the first elements in the remaining unprocessed portions of the arrays.
3.1.2 Copy the smaller of the two into A, while incrementing the index indicating the
unprocessed portion of that array.
3.2 Once all elements in one of the arrays are processed, copy the remaining unprocessed
elements from the other array into A.
Program
/*Program for merge sort*/
#include <stdio.h>
#include <conio.h>
void main ()
{
int i, n, a [100];
clrscr ();
printf ("\n Enter the size of the array:");
scanf ("%d”, &n);
printf ("\n Enter the elements:\n");
for (i = 0; i < n; i++)
scanf ("%d”, &a[i]);
mergesort (a,0, n-1);
printf ("\n Elements in sorted order:\n");
for (i = 0; i < n; i++)
printf ("%5d”, a[i]);
getch ();
}
void merge (int [], int, int, int);
void mergesort (int a [], int low, int high)
{
int mid;
if (low < high)
{
mid = (low + high)/2;
mergesort (a, low, mid);
mergesort (a, mid+1, high);
merge (a, low, high, mid);
}
}
void merge (int a [], int l, int h, int m) {
int c [100], i, j, k;
i = l; j = m + 1; k = l;
while (i <= m && j <= h) {
if(a[i] < a[j]) {
c[k] = a[i];
i++; k++;
}
else {
c[k] =a[j];
j++; k++;
}
}
while (i <= m)
c[k++] = a[i++];
while (j <= h)
c[k++] = a[j++];
for (i = l; i < k; i++)
a[i] = c[i];
}
Big O Notation Indicates, how hard an algorithm has to work to solve a problem.
Example 1:
C Strings
A string is a sequence of characters. A string literal is enclosed in double quotes.
Declaring a String:
The general form of declaration of a string variable is,
char string_name [size];
The size determines the number of characters in the string_name.
When the compiler assigns a character string to a character array, it automatically
supplies a null character (‘\0’) at the end of the string.
The size should be equal to the maximum number of characters in the string plus one
Initializing a String: This can be done in two ways.
1.char str1[7] =“Welcome”; 2.char str2[8]={‘W’,’e’,’l’,’c’,’o’,’m’,’e’,’\0’};
Memory for strings must be allocated before the string can be used.
Formatted input and output functions: scanf () and printf ()
scanf (): The string can be read using the scanf function with the format specifier %s.
Syntax for reading string using scanf function is scanf (“%s”, string_name);
printf (): The string can be print using printf () function with the format specifier %s
syntax: printf (“%s”, string_name);
Character I/O from keyboard:
To read characters from the keyboard and write to the screen, it takes the following form:
char c = getchar (); //reads one character from the keyboard
putchar(c); // display the character on the monitor
Un-formatted input functions: gets () and puts ()
C provides easy approach to read a string of characters using gets () function.
Syntax: gets (string_name);
The function accepts string from the keyboard. The string entered includes the white spaces. The
input will terminate only after pressing <Enter Key>.
Once the <Enter key > is pressed, a null character (\0) appended at the end of the string.
Advantage: It is capable of reading multiple words from the keyword.
To display the string on the screen we use a function puts ().
Syntax: puts(str);
Where str is a string variable containing a string value.
Print Days of the Week
String Handling library function
There are several string library functions used to manipulate string and the prototypes for these
functions are in header file “string.h”. Several string functions are.
strlen ()
This function return the length of the string. i.e., the number of characters in the string excluding
the terminating NULL character. It accepts a single argument which is pointer to the first
character of the string. For example, strlen(“suresh”); It return the value 6.
strcmp ()
This function is used to compare two strings. If the two-string match, strcmp () return a value 0
otherwise it returns a non-zero value. It compare the strings character by character and the
comparison stops when the end of the string is reached or the corresponding characters in the two
string are not same.
strcmp (s1, s2) return a value:
<0 when s1<s2
=0 when s1=s2
>0 when s1>s2
The exact value returned in case of dissimilar strings is not defined. We only know
that if s1<s2 then a negative value will be returned and if s1>s2 then a positive
value will be returned.
Strcpy ()
This function is used to copying one string to another string. The function strcpy (str1, str2)
copies str2 to str1 including the NULL character. Here str2 is the source string and str1 is the
destination string.
The old content of the destination string str1 are lost. The function returns a pointer
to destination string str1.
Strcat ()
This function is used to append a copy of a string at the end of the other string. If
the first string is “”Purva” and second string is “Belmont” then after using this function the
string becomes “PusvaBelmont”. The NULL character from str1 is moved and str2 is added at
the end of str1. The 2nd string str2 remains unaffected. A pointer to the first string str1 is
returned by the function.
FUNCTION
A function is a self-contained block of codes or sub programs with a set of statements
that perform some specific task or coherent task when it is called.
It is something like to hiring a person to do some specific task like, every six months
servicing a bike and hand over to it.
Any ‘C’ program contain at least one function i.e., main ().
There are basically two types of function those are
1. Library function
Example: abs (a) function gives the absolute value of a, available in
<math.h>
pow (x, y) function computes x power y. available in <math.h>
printf () and scanf () performs I/O functions and etc..,
System defined function can’t be modified, it can only read and can be used. These functions are
supplied with every C compiler Source of these library function are pre complied and only object
code get used by the user by linking to the code by linker
//local declarations
……
//statements
……
return (expression);
return-type:
Specifies the type of value that a function returns using the return statement.
It can be any valid data type. If no data type is specified the function is assumed to return
an integer result.
function-name:
Must follow same rules of variable names in C.
No two functions have the same name in a C program.
argument declaration:
It is a comma-separated list of variables that receive the values of the argument when
function is called. If there is no argument declaration the bracket consists of keyword
void.
Function Declaration (or) Prototype:
Function declaration is also known as function prototype. It informs the
compiler
about three thing, those are name of the function, number and type of
argument
received by the function and the type of value returned by the function.
While declaring the name of the argument is optional and the function
prototype
always terminated by the semicolon.
Function definition: -
Function definition consists of the whole description and code of the function. It tells about what
function is doing what are its inputs and what are its output. It consists of two parts function
header and function body
Syntax: -
return type function (type 1 arg1, type2 arg2, type3 arg3) /*function header*/
{
Local variable declaration;
Statement 1;
Statement 2;
Return value
}
The arguments of the function definition are known as formal arguments.
Function Call
When the function gets called by the calling function then that is called, function
call. The compiler execute these functions when the semicolon is followed by the
function name.
Example: -
function (arg1, arg2, arg3);
The argument that are used inside the function call are called actual argument
Ex: -
int S=sum (a, b); //actual arguments
Category of User –Defined Functions:
Category 1: Functions with no arguments and no return values
/*Example for Functions with no arguments and no return values
to print addition of sum of two numbers*/
#include<stdio.h>
void sum (); /* function prototype */
void main ()
{
sum (); /* function calling*/
}
void sum () /* Function Definition */
{
int x, y, z;
printf (“\n Enter the values of x and y: “);
scanf (“%d%d”, &x, &y);
z=x+y;
printf (“\n The sum = %d”, z);
}
Category 2: Functions with no arguments and with return values
/*Example for Functions with no arguments and with return values
to print addition of sum of two numbers*/
#include<stdio.h>
int sum (); /* function prototype */
int main ()
{
int c;
c = sum (); /*function calling */
printf (“\n The sum = %d”, c);
}
int sum () /* Function Definition */
{
int x, y;
printf (“\n Enter the values of x and y: “);
scanf (“%d%d”, &x, &y);
/* return value to the calling function */
return x+y;
}
Category 3: Functions with arguments and no return values
/*Example for Functions with arguments and no return values
to print addition of sum of two numbers*/
#include<stdio.h>
void sum (int, int); /* function prototype */
void main ()
{
int a, b;
printf (“\n Enter the values of a and b: “);
scanf (“%d%d”, &a, &b);
sum (a, b); /*calling function */
}
void sum (int x, int y) /* function definition */
{
int z;
z=x+y;
printf (“\n The Sum =%d”, z);
}
Category 4: Functions with arguments and return values
#include<stdio.h>
void sum (int, int); /* function prototype */
void main ()
{
int a, b, c;
printf (“\n Enter the values of a and b: “);
scanf (“%d%d”, &a, &b);
c = sum (a, b); /*calling function */
printf (“\n The Sum =%d”, c);
}
void sum (int x, int y) /* function definition */
{
int z;
z=x+y;
return z;
}
Passing Parameters to Functions
1)call by value:
When a function is called with actual parameters, the values of actual parameters are
copied into the formal parameters.
If the values of the formal parameters changes in the function, the values of the actual
parameters are not changed.
include <stdio.h>
void swap (int, int); //prototype of the function
int main ()
{
int a = 10;
int b = 20;
printf ("Before swapping the values in main a = %d, b = %d\n”, a, b);
swap (a, b);
printf ("After swapping values in main a = %d, b = %d\n”, a, b);
}
void swap (int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
printf ("After swapping values in function a = %d, b = %d\n”, x, y); // Formal parameters
} efore swapping the values in main a = 10, b = 20
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function x = 20, y = 10
After swapping values in main a = 10, b = 20
Call by reference
Instead of passing the value of variable, address or reference is passed and the function
operate on address of the variable rather than value.
Here formal argument is alter to the actual argument, it means formal arguments calls the
actual arguments.
include <stdio.h>
void swap (int *x, int *y); //prototype of the function
int main ()
{
int a = 10;
int b = 20;
printf ("Before swapping the values in main a = %d, b = %d\n”, a, b);
swap (&a, &b);
printf ("After swapping values in main a = %d, b = %d\n”, a, b);
}
void swap (int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
printf("After swapping values in function a = %d, b = %d\n",*x,*y); // Formal parameters
} efore swapping the values in main a = 10, b = 20
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function x = 20, y = 10
After swapping values in main a = 20, b = 10
Recursion
When function calls itself (inside function body) again and again then it is called as recursive
function. In recursion calling function and called function are same. It is powerful technique of
writing complicated algorithm in easiest way.
According to recursion problem is defined in term of itself. Here statement with in
body of the function calls the same function and same times it is called as circular
definition. In other words, recursion is the process of defining something in form of
itself.
Syntax:
Ex: - /*calculate factorial of a no. using recursion*/
int fact(int);
void main ()
{
int num;
printf (“enter a number”);
scanf (“%d”, &num);
f=fact(num);
printf (“factorial is =%d\n”, f);
}
fact (int num)
{
If (num==0||num==1)
return 1;
else
return(num*fact(num-1));
}
Storage Classes
Storage class in c language is a specifier which tells the compiler where and how to store
variables, its initial value and scope of the variables in a program. Or attributes of
variable is known as storage class or in compiler point of view a variable identify some
physical location within a computer where its string of bits value can be stored is known
as storage class.
The kind of location in the computer, where value can be stored is either in the memory
or in the register. There are various storage class which determined, in which of the two-
location value would be stored.
Syntax of declaring storage classes is: - storage class datatype variable name;
There are four types of storage classes and all are keywords: -
1) Automatic (auto)
2) Register (register)
3) Static (static)
4) External (extern)
Examples: -
auto float x; or float x;
extern int x;
register char c;
static int y;
Compiler assume different storage class based on: -
1) Storage class: - tells us about storage place (where variable would be stored).
2) Intial value: -what would be the initial value of the variable. If initial value not assigned, then
what value taken by uninitialized variable.
3) Scope of the variable: -what would be the value of the variable of the program.
4) Life time: - It is the time between the creation and distribution of a variable or how long
would variable exist.
1. Automatic storage class
The keyword used to declare automatic storage class is auto.
Its features: -
Storage-memory location
Default initial value: -unpredictable value or garbage value.
Scope: -local to the block or function in which variable is defined.
Life time: -Till the control remains within function or block in which it is defined.
It terminates when function is released.
The variable without any storage class specifier is called automatic variable.
Example: -
main ()
{
auto int i;
printf (“i= %d”, i);
}
2. Register storage class
The keyword used to declare this storage class is register. The features are: -
Storage: -CPU register.
Default initial value: -garbage value
Scope: -local to the function or block in which it is defined.
Life time: -till controls remains within function or blocks in which it is defined. Register
variable don’t have memory address so we can’t apply address operator on it. CPU register
generally of 16 bits or 2 bytes. So, we can apply storage classesonly for integers, characters,
pointer type.
Variable stored in register storage class always access faster than, which is always stored
in the memory. But to store all variable in the CPU register is not possible because of
limitation of the register pair.
And when variable is used at many places like loop counter, then it is better to declare it
as register class.
Example: -
main ()
{
register int i;
for (i=1; i<=12; i++)
printf (“%d”, i);
}
External storage classes: The keyword used for this class is extern.
Features are: -
Storage: - memory area
Default initial value: -zero
Scope: - global
Life time: -as long as program execution remains it retains. Declaration does not create
variables, only it refers that already been created at somewhere else. So, memory is not allocated
at a time of declaration and the external variables are declared at outside of all the function.
Example: -
int i, j;
void main ()
{
printf (“i=%d”, i);
receive ();
receive ();
reduce ();
reduce ();
}
receive ()
{
i=i+2;
printf (“on increase i=%d”, i);
}
reduce ()
{
i=i-1;
printf (“on reduce i=%d”, i);
}
Output: -i=0,2,4,3,2.
When there is large program i.e., divided into several files, then external variable should be
preferred. External variable extends the scope of variable.
Pointers
Pointer variable is a variable which stores the address of another variable and it points indirectly
to the value of that variable.
Syntax: Data type *pointer name;
Example
Two operators are used in the pointer i.e., address operator (&) and indirection
operator or dereference operator (*).
Indirection operator gives the values stored at a particular address.
Address operator cannot be used in any constant or any expression.
Example:
void main ()
{
int i=105;
int *p; 104 i 2000 *p
p=&i;
t 2000 3000
printf (“value of i=%d”, *p); output i=104
printf (“address of i=%d”, &i); output i= 2000
printf (“address of i=%d”, p); output I = 2000
printf (“address of p=%u”, &p); output p = 3000
}
Pointers to Pointers
Pointer vs array
Example :-
void main ()
{
static char arr [] =” Rama”;
char*p=” Rama”;
printf (“%s%s”, arr, p);
}
In the above example, at the first time printf (), print the same value array and pointer. Here array
arr, as pointer to character and p act as a pointer to array of character. When we are trying to
increase the value of arr it would give the error because it’s known to compiler about an array
and its base address which is always printed to base address is known as constant pointer and the
base address of array
which is not allowed by the compiler.
printf (“size of (p)”, size of (ar));
Unary, relational, arithmetic, bitwise operators are not allowed within structure
variables.
Size of structure-
Size of structure can be found out using sizeof () operator with structure variable
name or tag name with keyword.
sizeof (struct student); or
sizeof(s1);
sizeof(s2);
Size of structure is different in different machines. So, size of whole structure may
not be equal to sum of size of its members.
Array of structures
When database of any element is used in huge amount, we prefer Array of
structures.
Example: suppose we want to maintain data base of 200 students, Array of
structures are used.
#include<stdio.h>
#include<string.h>
struct student
{
char name [30];
char branch [25];
int roll;
};
void main ()
{
struct student s [200];
int i;
s[i]. roll=i+1;
printf ("\nEnter information of students:");
for (i=0; i<200; i++)
{
printf ("\nEnter the roll no: %d\n”, s[i]. roll);
printf ("\nEnter the name:");
scanf ("%s”, s[i].name);
printf ("\nEnter the branch:");
scanf ("%s”, s[i]. branch);
printf("\n");
}
printf ("\nDisplaying information of students:\n\n");
for (i=0; i<200; i++)
{
printf ("\n\information for roll no%d:\n”, i+1);
printf("\nName:");
puts(s[i].name);
printf("\branch:");
puts(s[i]. branch);
}
}
In Array of structures each element of array is of structure type as in above
example.
Array within structures
struct student
{
char name [30];
int roll, age, marks [5];
}; struct student s [200];
We can also initialize using same syntax as in array.
Nested structure
When a structure is within another structure, it is called Nested structure. A
structure variable can be a member of another structure and it is represented as
struct student
{
element 1;
element 2;
………
………
struct student1
{
member 1;
member 2;
} variable 1;
……….
……….
element n;
} variable 2;
It is possible to define structure outside & declare its variable inside other
structure.
struct date
{
int date, month;
};
struct student
{
char nm[20];
int roll;
struct date d;
}; struct student s1;
struct student s2, s3;
Nested structure may also be initialized at the time of declaration like in above
example.
struct student s={“name”,200, {date, month}};
{“ram”,201, {12,11}};
Nesting of structure within itself is not valid. Nesting of structure can be
extended to any level.
struct time
{
int hr, min;
};
struct day
{
int date, month;
struct time t1;
};
struct student
{
char nm [20];
struct day d;
}stud1, stud2, stud3;
Nested of Union
When one union is inside the another union it is called nested of union.
Example:-
union a
{
int i;
int age;
};
union b
{
char name[10];
union a aa;
}; union b bb;
There can also be union inside structure or structure in union.
Example:-
void main ()
{
struct a
{
int i;
char ch [20];
};
struct b
{
int i;
char d [10];
};
union z
{
struct a a1;
struct b b1;
}; union z z1;
z1.b1. j=20;
z1. a1. i=10;
z1.a1.ch [10] = “i “;
z1.b1.d[0] =” j “;
printf (“ “);
Dynamic memory Allocation
The process of allocating memory at the time of execution or at the runtime, is called
dynamic memory location.
Two types of problem may occur in static memory allocation. If number of values to be
stored is less than the size of memory, there would be wastage of memory.
If we would want to store more values by increase in size during the execution on
assigned size then it fails.
Allocation and release of memory space can be done with the help of some library
function called dynamic memory allocation function. These library functions are called as
dynamic memory allocation function. These library function prototypes are found in
the header file, “alloc.h” where it has defined.
Function take memory from memory area is called heap and release when not required.
Pointer has important role in the dynamic memory allocation to allocate memory.
malloc ():
This function use to allocate memory during run time, its declaration is
void*malloc(size);
malloc ()
returns the pointer to the 1st byte and allocate memory, and its return type is void,
which can be type cast such as:
int *p=(datatype*) malloc(size)
If memory location is successful, it returns the address of the memory chunk that was
allocated and it returns null on unsuccessful and from the above declaration a pointer of
type(datatype) and size in byte.
datatype pointer used to typecast the pointer returned by malloc and this typecasting is
necessary since, malloc () by default returns a pointer to void.
Example int*p=(int*) malloc (10);
So, from the above pointer p, allocated IO contigious memory space address of 1st
byte and is stored in the variable. We can also use, the size of operator to specify the size, such
as
*p=(int*) malloc (5*size of int) Here, 5 is the no. of data.
Moreover , it returns null, if no sufficient memory available, we should always
check the malloc return such as, if(p==null)
printf (“not sufficient memory”);
Example:
/*calculate the average of mark*/
void main ()
{
int n, avg, i, *p, sum=0;
printf ("enter the no. of marks”);
scanf (“%d”, &n);
p= (int *) malloc(n*size(int));
if(p==null)
printf (“not sufficient”);
exit ();
}
for (i=0; i<n; i++)
scanf (“%d”, (p+i));
for (i=0; i<n; i++)
printf (“%d”, *(p+i));
sum=sum+*p;
avg=sum/n;
printf (“avg=%d”, avg);
calloc ()
Similar to malloc only difference is that calloc function use to allocate multiple
block of memory.
two arguments are there
1st argument specify number of blocks
2nd argument specify size of each block.
Example: -
int *p= (int*) calloc (5, 2);
int*p= (int *) calloc (5, size of (int));
Another difference between malloc and calloc is by default memory allocated by
malloc contains garbage value, whereas memory allocated by calloc is initialized
by zero (but this initialisation) is not reliable.
realloc ()
The function realloc use to change the size of the memory block and it alter the size of the
memory block without losing the old data, it is called reallocation of memory.
It takes two argument such as;
int *ptr= (int *) malloc(size);
int*p= (int *) realloc (ptr, new size);
The new size allocated may be larger or smaller. If new size is larger than the old size, then old
data is not lost and newly allocated bytes are uninitialized. If old address is not sufficient then
starting address contained in pointer may be changed and this reallocation function moves
content of old block into the new block and data on the old block is not lost.
Example:
#include<stdio.h>
#include<alloc.h>
void main ()
int i, *p;
p=(int*) malloc (5*size of (int));
if(p==null)
{
printf (“space not available”);
exit ();
printf (“enter 5 integers”);
for (i=0; i<5; i++)
{
scanf (“%d”, (p+i));
int*ptr=(int*) realloc (9*size of (int));
if(ptr==null)
{
printf (“not available”);
exit ();
}
printf (“enter 4 more integer”);
for (i=5; i<9; i++)
scanf (“%d”, (p+i));
for (i=0; i<9; i++)
printf (“%d”, *(p+i));
}
free ()
Function free () is used to release space allocated dynamically, the memory released by free () is
made available to heap again. It can be used for further purpose.
Syntax for free declaration.
void(*ptr)
Or
free(p)
When program is terminated, memory released automatically by the operating system. Even we
don’t free the memory, it doesn’t give error, thus lead to memory leak. We can’t free the
memory, those didn’t allocated.
Dynamic array
Array is the example where memory is organized in contiguous way, in the dynamic memory
allocation function used such as malloc (), calloc (), realloc () always made up of contiguous way
and as usual we can access the element in two ways as:
Subscript notation
Pointer notation
Example:
#include<stdio.h>
#include<alloc.h>
void main ()
{
printf (“enter the no. of values”);
scanf (“%d”, &n);
p=(int*) malloc (n*size of int);
If(p==null)
printf (“not available memory”);
exit ();
}
for (i=0; i<n; i++)
{
printf (“enter an integer”);
scanf (“%d”, &p[i]);
for (i=0; i<n; i++)
{
printf (“%d”, p[i]);
}
}
File handling
File: the file is a permanent storage medium in which we can store the data permanently.
Types of files can be handled
we can handle three types of file as
(1) sequential file
(2) random access file
(3) binary file
File Operation
opening a file:
Before performing any type of operation, a file must be opened and for this
fopen () function is used.
syntax:
file-pointer=fopen (“FILE NAME”,” Mode of open”);
example:
FILE *fp=fopen (“ar.c”,” r”);
If fopen () unable to open a file than it will return NULL to the file pointer.
File-pointer: The file pointer is a pointer variable which can be store the address
of a special file that means it is based upon the file pointer a file gets opened.
Declaration of a file pointer: -
FILE* var;
Modes of open
The file can be open in three different ways as
Read mode’ r’/rt
Write mode ’w’/wt
Appened Mode ’a’/at
Reading a character from a file
getc () is used to read a character into a file
Syntax:
character variable=getc(file_ptr);
Writing a character into a file
putc () is used to write a character into a file
puts (character-var, file-ptr);
ClOSING A FILE
fclose () function close a file.
fclose(file-ptr);
fcloseall () is used to close all the opened file at a time
File Operation
The following file operation carried out the file
(1) creation of a new file
(3) writing a file
(4) closing a file
Before performing any type of operation, we must have to open the file.c, language
communicate with file using A new type called file pointer.
Operation with fopen ()
File pointer=fopen (“FILE NAME”,”mode of open”);
If fopen () unable to open a file then it will return NULL to the file-pointer.
Output:
BUBBLE SORT
//C program to sort the numbers using bubble sort
main() {
int arr[50],temp,i,j,n;
printf("\nEnter any Value less Than 50:");
scanf("%d",&n);
printf("\n\tEnter The Values into ARRAY: ");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
for(i=1;i<n;i++) {
for(j=0;j<n-i;j++) {
if(arr[j] >arr[j+1]) {
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
printf(“\nSorted Series:");
for(i=0;i<n;i++) {
printf("\n %d",arr[i]);
}
STRINGS
/*Define functions- length of a string, copy, concatenate, convert into
uppercase letters, compare two strings for alphabetical order- over strings
and implement in a program*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>
main () {
char str1[15], str2[15], str3[10];
int n, c, len, i;
printf ("\n Enter the string1 ");
gets(str1);
puts(str1);
printf ("\n Enter the string2 ");
gets(str2);
puts(str2);
printf ("Enter the string 3 ");
scanf ("%s”, str3);
printf ("%s”, str3);
printf("\n***************************");
printf ("\n 1. String Length ");
printf ("\n 2. String Copy ");
printf ("\n 3. String Comparison ");
printf ("\n 4. String Concat ");
printf ("\n 5. UpperCase ");
printf("\n***************************");
printf ("\n Enter the choice u want to perform");
scanf ("%d”, &n);
switch(n)
{
case 1: len=strlen(str1);
printf ("\n The length of the string entered is %d”, len);
break;
case 2: strcpy (str1, str2);
printf ("\n 1st string =%s,2nd string=%s”, str1, str2);
break;
case 3: c=strcmp (str1, str2);
if(c==0)
printf ("\n Both are equal");
else
printf ("\n Both are different");
break;
case 4: printf ("\n the resultant string is: %s”, strcat (str1, str2));
break;
case 5: for (i=0; i<strlen(str1); i++)
str1[i]=toupper(str1[i]);
printf ("%s”, str1);
break;
default: printf ("\n Enter correct choice");
}
}
Output:
enter the number of row=3
enter the number of column=3
enter the first matrix element=
1 1 1
2 2 2
3 3 3
enter the second matrix element=
1 1 1
2 2 2
3 3 3
multiply of the matrix=
6 6 6
12 12 12
18 18 18
int main ()
{
FILE *fptr1, *fptr2;
char filename [100], c;
fclose(fptr1);
fclose(fptr2);
return 0;
}
Output:
Enter the filename to open for reading
a.txt
Enter the filename to open for writing
b.txt
Contents copied to b.txt
min=max=a[0];
for(i=1; i<n; i++)
{
if(min>a[i])
min=a[i];
if(max<a[i])
max=a[i];
}
printf("minimum of array is : %d",min);
printf("\nmaximum of array is : %d",max);
return 0;
}
Output:
Enter size of the array :5
Enter elements in array : 1
32
43
54
65
Minimum of an array is :1
Maximum of an array is :5
PALINDROME OR NOT\
#include<stdio.h>
int main ()
{
int n, r, sum=0, temp;
printf ("enter the number=");
scanf ("%d”, &n);
temp=n;
while(n>0)
{
r=n%10;
sum=(sum*10) +r;
n=n/10;
}
if(temp==sum)
printf ("palindrome number ");
else
printf ("not palindrome");
return 0;
}
Output :
enter the number=151
palindrome number
MACROS IN C
What is a Macro in C?
You can say that macro is a piece of code that is replaced by the value of the macro
throughout the program. You can define a macro with #define directive. At the end of
defining a macro, you don’t have to put a semicolon(;) to terminate it.
Example:-
#define PI 3.14
Example:- Object-like Macros
#include <stdio.h>
#define PI 3.142
Void main()
{
int area,r;
printf(“Enter the radius”);
scanf(“%d”, &r);
area = PI *r*r;
printf("Area is: %d", area);
}
TRANSPOSE OF A MATRIX
#include <stdio.h>
int main() {
int a[10][10], transpose[10][10], r, c;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);
Output :
Entered matrix:
1 4 0
-5 2 7