Vel Tech Multi Tech
Vel Tech Multi Tech
An Autonomous Institution
Approved by AICTE, Affiliated to Anna University, Chennai.
ISO 9001:2015 Certified Institution, Accredited by NBA (BME, CSE, ECE, EEE, IT & MECH),
Accredited by NAAC with 'A' Grade with CGPA of 3.49.
#42, Avadi-Vel Tech Road, Avadi, Chennai- 600062, Tamil Nadu, India.
S.no Topic
1 Structure of a C program
2 compilation and linking processes
3 Constants
4 Variables
5 Data Types
6 Expressions using operators in C
7 Managing Input and Output operations in C
8 Decision Making and Branching in C
9 Looping statements in C
10 Arrays
Initialization
Declaration
One dimensional array
Two-dimensional arrays
11 Strings
String operations
String Arrays
STRUCTURE OF C PROGRAM
VEL TECH MULTI
Link section:
The link section provides instruction to the compiler to link or include the
required in-built functions from the system library such as using the #include
directive.Eg #include<stdio.h>, #include<string.h>,#include<math.h>.
Definition section:
The definition section defines all symbolic constants using the #define
directive(optional). Having the constants being defined here, we can use them
elsewhere in code.
Figure 1.2
main() A C program contains one or more
{ functions, where a function is defined
Statement 1; as a group of statements that perform a
Statement 2; well- defined task.
............
Statement N; Figure 1.2 shows the structure of a
} C program.
Function1()
{ The statements in a function are written
Statement 1; to perform a specific task.
Statement 2;
Statement N;
} The main() function is the most
Function2() important function and is a part of every
{ C program and is mandatory
Statement 1;
Statement 2; The execution of a C program begins
Statement N; with main( )function.
}
FunctionN() A C program can have any number of
{ functions depending on the number of
Statement 1; independent tasks that have to be
Statement 2;
performed, and each function can have
Statement N;
} any number statements.
PROGRAM STATEMENT
Declaration statement: the name and type of the data objects needed during
program execution.
Example :-int a
Expression statement: is the simplest kind of statement
Labeled statements: can be used to mark any statement so that control may be
transferred to the statement by switch statement
Case 1:
labelABC:
EXAMPLE C PROGRAM
//sample.c//
#include<stdio.h>
main()
{
printf(“welcome to
C”); return 0;
}
VEL TECH MULTI
Compile and Link C Program
There are three basic phases occurred when we execute any C program.
Preprocessing
Compiling
(assembler)
Linking
Linking Phase:The link phase is implemented by the linker. The linker is a process that
accepts as input object files and libraries to produce the final executable program.
The process can be split into four separate stages: Preprocessing, compilation, assembly, and
linking.
/*
* "Hello, World!": A classic.
*/
#include
<stdio.h> int
main(void)
{
puts("Hello,
World!"); return 0;
Preprocessing
The first stage of compilation is called preprocessing. In this stage, lines starting with a #
character are interpreted by the preprocessor as preprocessor commands. These commands
form a simple macro language with its own syntax and semantics.
gcc -E hello_world.c
[lines omitted for brevity]
int main(void) {
puts("Hello, World!");
return 0;
}
Compilation
In this stage, the preprocessed code is translated to assembly instructions These form an
intermediate readable language.
Some compilers also supports the use of an integrated assembler, in which the
compilation stage generates machine code directly, avoiding the overhead of generating
the intermediate assembly instructions and invoking the assembler. object code is
directly produced by compiler.
to view the result of the compilation stage, pass the -S option to cc:
gcchello_world.s
This will create a file named -S hello_world.c
Assembly
During the assembly stage, an assembler is used to translate the assembly instructions to
machine code, or object code.
--The output consists of actual instructions to be run by the target processor.
Linking
The object code generated in the assembly stage is composed of machine instructions that the
processor understands but some pieces of the program are out of order or missing. To
produce an executable program, the existing pieces have to be rearranged and the missing
ones filled in. This process is called linking.
Finally to run
a.out hello_world.c
extention To compile:
gcc filename.c
./a.out
VEL TECH MULTI
Constants/Literals
A constant is a value or an identifier whose value cannot be altered in a program.
1. By “const” keyword
2. By “#define” preprocessor directive
Eg-1
#include<stdio.h>
main()
{
const int SIDE = 10;
int area;
area = SIDE*SIDE;
printf("The area of the square %d is: %d sq. units" , SIDE, area);
}
Output
The area of the square 10 is: 100 sq. Units
C constant
Primary Constants
-integer constant
-floating point constant
-character Constant
-String Constant
-Backslash Constant
1. Integer constants
An integer constant is a numeric constant (associated with number) without any fractional or
exponential part. There are three types of integer constants in C programming:
decimal constant(base 10)
octal constant(base 8)
hexadecimal constant(base 16)
VEL TECH MULTI
For example:
Decimal constants: 1,0, -9, 22 etc
Octal constants: 021, 077, 033 etc
Hexadecimal constants: 0x7f, 0x2a, 0x521
etc
In C programming, octal constant starts with a 0 and hexadecimal constant starts with a 0x.
55 /*int constant */
55l /*unsigned int constant*/
55 ul /*unsigned long constant*/
2. Floating-point constants
A floating point constant is a numeric constant that has either a fractional form or an
exponent form(decimal point). For example:
633E---illegal..incomplete exponent
-2.0 6.333 – 633f—illegal..no decimal or
0.0000234 exponent
-0.22E-5 correct 633E- .e633—illegal..missing integer
4L-correct
Rules for defining floating point(real) constants:
3. Character constants
A character constant is a constant which uses single quotation around characters.
For example:
'a'
'6',
'=',
'F'
Rules for defining character constants
OUTP OUTP
UT 10 UT 10
20 20
The Area of Triangle is: The Area of Triangle is:
100
VEL TECH MULTI
Example program using const keyword in C:
#include <stdio.h>
void main()
{
const int height = 100; /*int constant*/
const float number = 3.14; /*Real
constant*/ const char letter = 'A'; /*char
constant*/
const char letter_sequence[10] = "ABC"; /*string
constant*/ const char backslash_char = '\?'; /*special char
cnst*/ printf("value of height :%d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
printf("value of backslash_char : %c \n", backslash_char);
}
Output:
2.value of height
Example : 100using #define preprocessor directive in C:
program
value of number :
3.140000<stdio.h>
#include value of letter :
A
#define height 100
value ofnumber
#define letter_sequence
3.14 : Output:
#define letter 'A' value of height : 100
#define letter_sequence "ABC" value of number :
#define backslash_char '\?' 3.140000 value of letter :
void main() A
{ value of letter_sequence :
printf("value of height : %d \n", height );
ABC value of backslash_char
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n",letter_sequence);
printf("value of backslash_char : %c \n",backslash_char);
}
Variabl Constant
e int a variable const
=10; a+ int a =10; a++;
+; printf(“%d”,a);
printf(“%d”,a); ---------------------
----------------------- o/p:= 10
VEL TECH MULTI
DATA TYPES IN C
The data type, of a variable determines a set of values that a variable might take and a set
of operations that can be applied to those values.
Data type refer to the type and size of data associated with the variable and functions.
Allows 15 digits
after decimal point.
long double 10 -1.7e-4932 to 1.7e4932 %LF
Allows 15 digits
after decimal point.
VEL TECH MULTI
/*Program*/
#include<stdio.h>
int main()
{
char a;
unsigned char
b; int i;
unsigned int
j; long int k;
unsigned long int
m; float x;
double y
long double z;
return 0;
}
VEL TECH MULTI
The specifiers and qualifiers for the data types can be broadly classified into
three types
Size qualifiers alter the size of the basic data types. There are two such qualifiers that can
be used with the data type int; these are short and long.
short, when placed in front of the data type int declaration, tells the C compiler that the
particular variable being declared is used to store fairly small integer values. Long specifies it
is a very big integer value.Long integers require twice the memory of than small ints.
Sign specifiers: for example fot int data type out of 2bytes(2*8=16bits) of its size the
highest bit(the sixtheenth bit) is used to store the sign of the integer value. The bit is 1 if
number is negative and 0 if the number is positive.
Bit Bit Bit Bit Bit Bit Bit Bit Bit Bit Bit Bit Bit Bit Bit Bit
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Sign of number
(1 for –ve and 0
for +ve0
Type qualifiers : There are two type qualifiers, const and volatile;
Eg: const float pi = 3.14156; // specifies that the variable pi can never be changed by the
Program.
VEL TECH MULTI
Allowed combinations of basic data types and modifi ers in C for a 16-bit
computer
VEL TECH MULTI
VARIABLES
Variable is the name of memory location which holds the data. Unlike constant, variables
are changeable, value of a variable can be changed during execution of a program. A
programmer must chose a meaningful variable name.
Variables are used for holding data values so that they can be utilized for various
computations in a program.A variable must be declaed and then used for coputation work in
program./A variable is an identifier used for storing and holding some data(value).
1.A data type: Like int, double, float. Once defined,the type of a C variable
cannot be changed.
2.A name of the variable.
3.A value that can be changed by assigning a new value to the variable.
The kind of values a variable can assume depends on its type.
Eg : for variable int salary,it can only take integer values can only take integer
values like 65000 and not 6500.0
Declaration of a variable must be done before it is used for any computation in the
program.
Declaration tells the compiler what the variable name is.
Declaration tells what type of data the variable will hold.
Until the variable is not defined/or/declared compiler will not allocate memory space to the
variables.
A variable can also be declared outside main() function.
A variable can also be declared in other program and declared using extern keyword.
Initializing a variable:=
int yearly_salary;
Initializing a variable
floatmeans to provide a value to variable
monthly_salary; int
int a;
yearly salary=5,00,000
double x;
float monthly_salary= 41666.66
VEL TECH MULTI
Variables are a way of reserving memory to hold some data and assign names to them so that
we don’t have to remember the numbers like REG46735 or memory address like FFFFoxFF
and instead we can use the memory location by simply referring to the variable.
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language.
Assume variable A holds 10 and variable B holds 20
Relational Operators
Following table shows all the logical operators supported by C language. Assume variable A
holds 1 and variable B holds 0, then −
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is as follows −
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume A = 60 and B = 13 in binary format, they will be as follows −
A = 0011 1100
B = 0000 1101
The following table lists the assignment operators supported by the C language
Misc Operators
Operators Precedence in C
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence
than +, so it first gets multiplied with 3*2 and then adds into 7.
Expression
Eg : c+d
x/y+b+a*a*a
3.14 *r *r
#include<stdio.h>
int main()
{
int num1,num2,num3;
scanf("%d %d %d",&a,&b,&c);
if((a>b)&&(a>c))
printf("\n %d is
greatest",a); else if(b>c)
printf("\n %d is greatest",b
"); else
printf("\n %d is greatest",c);
return 0;
}
Example program –find odd or even number
Example of Arithmetic(% mod) and relational operators(==)
#include<stdio.h>
int main()
{ int
num,result;
if(num%2==0)
printf(“even number \n”);
else
printf(“odd number \n”);
return 0;
}
VEL TECH MULTI
Bitwise XOR
Explanation
Output = 21
complement = 220
OutputAND = 8
OutputOR = 29
VEL TECH MULTI
getche( )
4)fputs( ) 5)fprint( )
fgets( ) 6)fscanf( )
Input means to provide the program with some data to be used in the program
Output means to display data on screen or write the data to a printer or a file.
1. Singlecharacterinputandoutput[getchar() andputchar()]
input- getchar()
output- putchar()
The int getchar(void) function reads the next available character from the screen and
returns it as an integer. This function reads only single character at a time.
The int putchar(int c) function puts the passed character on the screen and returns the same
character. This function puts only single character at a time.
program
#include <stdio.h>
int main( ) {
int c; output
$./a.out
Enter a value : this is DS class
printf( "Enter a value :"); You entered: t
c = getchar( );
return 0;
}
VEL TECH MULTI
2. Stringinputandoutput[gets()andputs()
The gets( ) function reads a line from stdin into the buffer pointed to by s until either a
terminating newline or EOF (End of File).
The puts( ) function writes the string 's' and 'a' trailing newline to stdout.
Program
return 0;
}
scanf()
scanf() is a predefined function in "stdio.h" header file. It can be used to read the input value
from the keyword.
VEL TECH MULTI
Syntax of scanf() function
1. & ampersand symbol is the address operator specifying the address of the variable
2. control string holds the format of the data
3. variable1, variable2, ... are the names of the variables that will hold the input value.
intscanf("control
a; string", &variable1, &variable2, ...);
Examp
float b;
scanf("%d%f",&a,&b);
Example
double d;
char c;
long int l;
scanf("%c%lf%ld",&c&d&l);
Printf
Printf is a predefined function in "stdio.h" header file, by using this function, we can print the
data or user defined message on console or monitor. While working with printf(), it can take
any number of arguments but first argument must be within the double cotes (" ") and every
argument should separated with comma ( , ) Within the double cotes, whatever we pass, it
prints same, if any format specifies are there, then value is copied in that place.
Program
#include <stdio.h> //This is needed to run printf() function.
int main()
{
printf("C Programming"); //displays the content inside quotation
return 0;
}
Program(integer and float)
Output <stdio.h>
#include
C Programming
#include <conio.h>
void main();
{
int a;
float b;
clrscr();
printf("Enter any two numbers: ");
scanf("%d %f",&a,&b);
printf("%d %f \n",a,b);
getch();
}
Program
#include <stdio.h>
int main()
{
return 0; Output
}
4 digit integer right justified to 6 column: 9876
4 digit integer right justified to 3 column:
9876 Floating point number rounded to 2 digits:
987.65 Floating point number rounded to 0
digits: 988
Floating point number in exponential form: 9.876543e+02
FILE INPUT and OUTPUT
4. File string input and output using fgets( )and fputs( )
The fgets() function
The fgets() function is used to read string(array of characters) from the file.
Syntax fgets(char str[],int n,FILE *fp);
The fgets() function takes three arguments, first is the string read from the file, second is size
of string(character array) and third is the file pointer from where the string will be read.
Example File*f
p;
Str[80
Example program
#include<stdio.h>
void main()
{
FILE *fp;
char str[80];
fp = fopen("file.txt","r"); // opens file in read mode (“r”)
while((fgets(str,80,fp))!=NULL)
printf("%s",str); //reads content from
file
fclose(fp);
}
Data in file...
C is a general-purpose programming
language. It is developed by Dennis Ritchie.
C is a general-purpose programming
language. It is developed by Dennis
Ritchie.
VEL TECH MULTI
Output :
The fputs() function takes two arguments, first is the string to be written to the file and
second is the file pointer where the string will be written.
Syntax:
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
int roll;
char name[25];
fp = fopen("file.txt","r");
printf("\n Reading from file...\n");
while((fscanf(fp,"%d%s",&rollno,&name))!=NULL)
printf("\n %d\t%s",rollno,name);//reading data
fclose(fp);
}
Output
:
Reading from file...
6666 keith
7777 rose
VEL TECH MULTI
Example program
#include<stdio.h>
void main()
{ Output
FILE *fp;
int roll; 6666
char name[25]; john
fp = fopen("file.txt","w");
scanf("%d",&roll);
scanf("%s",name);
fprintf(fp,"%d%s%",roll,name);
close(fp);
}
VEL TECH MULTI TECH
if(test-expression)
It allows the computer to evaluate the expression first and them depending on whether
the value of the expression is "true" or "false", it transfer the control to a particular
statements. This point of program has two paths to flow, one for the true and the other
for the false condition.
if(test-expression)
{
statement-block
}
statement-x;
44
Nested if
Syntax-1 Syntax-2
if(test-condition-1) If(test-condition-1)
{ {
(stmt if(test-condition-2)
s) else {
{ statement-1;
if(condition 2) }
{ else
Statement-1; {
} statement-2;
els }
e }
{ else
statement-2; {
} statement-3;
} }
} statement-x
statement-
If the test-condition-1 is false, the statement-3 will be executed; other wise it continues
the second test. If the condition-2 is true, the statement-2 will be evaluated and then the
control is transferred to the statement-x.
Example:Program to relate two integers using =, > or <
#include <stdio.h>
int main()
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1,
&number2);
}
VEL TECH MULTI
The switch statement:
When many conditions are to be checked then using nested if...else is very difficult, confusing and
cumbersome.So C has another useful built in decision making statement known as switch.
This statement can be used as multiway decision statement.The switch statement tests the
value of a given variable or expression against a list of case values and when a match is
found, a block of statements associated with that case is executed.
Eg-1
int i = 1; switch( code)
switch(i) {
{ case 1:
case 1: stmts1;
printf("A"); break;
break; case 2:
case 2:
stmts2;
printf("B"); break;
break;
case 3:
case 3: stmts3
printf("C"); break;
break;
default:
default:
}
stmtsx
Example2: C program to find largest of two umb }
n
#include<stdio.h>
void main () For case 1,da=10% of basic salary.
{
For case 2, da=15% of basic salary.
float basic , da , salary
For case 3, da=20% of basic salary.
; int code ;
char name[25]; For default case >3 da is not given.(da=0)
da=0.0;
printf("Enter employee name\n");
scanf("%[^\n]",name); o/p
printf("Enter basic salary\n");
scanf("%f",&basic); Enter name of
printf("Enter code of the Employee\n"); employee: Kartiyani
scanf("%d",&code); Enter Basic
salary 5000
switch (code)
{ Enter code of
case 1: employee 1
da = basic * 0.10;
break; Employee name
case 2: is Kartiyani
da = basic * 0.15; DA is 500 and total salary is 5500
break;
case 3:
da = basic * 0.20; break;
default :
da = 0;
}
salary = basic + da;
printf("Employee name is\n");
printf("%s\n",name);
printf ("DA is %f and Total salary is =%f\n",da, salary);
getch();
}
VEL TECH MULTI
BREAK is a keyword that allows us to jump out of a loop instantly, without waiting to
get back to the conditional test.
break;
Output
Example program value of a: 10
#include <stdio.h> value of a: 11
int main () value of a: 12
{ value of a: 13
int a = 10; value of a: 14
while( a < 20 value of a: 15
)
{
printf("value of a: %d\n", a);
a++;
if( a > 15)
{
break;
}
}
return 0;
}
VEL TECH MULTI
Continue
The continue statement in C programming works somewhat like the break statement.
Instead of forcing termination, it forces the next iteration of the loop to take place,
skipping any code in between.
For the for loop, continue statement causes the conditional test and increment portions
of the loop to execute. For the while and do...while loops, continue statement causes the
program control to pass to the conditional tests.
Syntax: continue;
Break Continue
The break statement can be used in The continue statement can appear only in
both switch and loop (for, while, do loops. You will get an error if this appears
while) statements. in switch statement.
A continue doesn't terminate the loop, it
A break causes the switch or loop
causes the loop to go to the next iteration.
statements to terminate the moment it is
The continue statement is used to skip
executed. Loop or switch ends abruptly
statements in the loop that appear after
when break is encountered.
the continue.
The continue statement can appear only
The break statement can be used in both
in loops. You will get an error if this
switch and loop statements.
appears in switch statement.
When a break statement is encountered, When a continue statement is
it terminates the block and gets the encountered, it gets the control to the
control out of the switch or loop. next iteration of the loop.
GOTO
GOTO STATEMENT
‘C’ supports goto statement to branch unconditionally from one point to another in the program.
A goto statement in C programming provides an unconditional jump from the 'goto' to a labeled
statement.
NOTE − Use of goto statement is highly discouraged in any programming language because it makes
difficult to trace the control flow of a program, making the program hard to understand and hard to
modify. Any program that uses a goto can be rewritten to avoid them.
Syntax
goto label;
Or ..
.
label: statement;
label: statement;
...
...
goto label;
VEL TECH MULTI
Output
value of a:
10 value of
a: 11 value
Example program of a: 12
#include value of a:
<stdio.h> 13 value of
int main () a: 14 value
{ of a: 16
int a = 10; value of a:
ABCL:do 17 value of
{ a: 18 value
if( a == 15) of a: 19
{
a = a + 1;
goto ABCL;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
return 0;
}
program to print ‘n’ natural number
#include<stdio.h>
void main( )
{
int n,i=1;
clrscr();
printf("enter number");
scanf("%d\t",n);
printf("natural numbers from 1 to %d", n);
lb: printf("%d\t",i);
i++;
if(i<=n)
goto lb;
getch();
}
VEL TECH MULTI
LOOPING STATEMENTS
If the loop Test Condition is true, then the loop is executed, the
sequence of statements to be executed is kept inside the curly braces { } is
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.
Types of Loop
1. while loop
2. for loop
3. do while loop
while loop
5 10 15 20 25 30 35 40 45 50 55 60
VEL TECH MULTI
1) break 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.
For Loop
In forfor(initialization;
loop we have exactly two semicolons, one after initialization and second
condition; increment/decrement)
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
statement-block;
one condition.
}
4. MULTIDIMENTIONAL ARRAYS
An array is a collection of similar data items, accessed using a common name. The collection of
element can all be integers or be all decimal value or be all characters or be all strings.
Array Declaration:
To declare an array in C, a programmer specifies the type of the elements and the number of
elements required. The arraySize must be an integer constant greater than zero and datatype can
be any valid C data type.
Syntax1:
datatype arrayName[ arraySize ];
Example-1
int n=25; int n;
int number[20]; double x[n], y[n]; //array Scanf(“%d”,&n);//get
int marks[44]; size int x[n]; //array
declaration
float salary[10]; declaration
double value[25];
#include<stdio. #include<stdio.
h> #define N h> int main( )
100 {
int main( ) int N=10,M=20;
{ int marks[N*M];//array dec
int marks[N];//array dec ....
.... return 0;
return 0; }
Syntax-2
Example: static int marks[20];
<storage class> datatype arrayName[ arraySize ];
VEL TECH MULTI
Array intitialization:
Example-1 int mark[5] = {55, 66, 77, 88, 99};
mark[0] = 55
mark[1] = 66
mark[2] = 77
mark[3] = 88
mark[4] = 99
it means....
balance[0] = 1000.0;
balance[1] = 2.0;
balance[2] = 3.4;
balance[3] = 7.0;
balance[4] = 50.0;
Automatic sizing
int arr[] = {3,1,5,7,9};
Here, the C compiler will deduce the size of the array automatically based on the number of
elements. Array size is deduced to be 5
VEL TECH MULTI
OPERATIONS ON ARRAYS
o Traversing an array
o Inserting an element in an array
o Searching an element in an array
o Deleting an element from an array
o Merging two arrays
o Sorting an array in ascending or descending order
Working with one dimensional array
STORE and DISPLAY VALUES IN AN ARRAY (traversing an
array) #include<stdio.h>
int main( )
Output:
{
Enter the array
int k,array[10];//array declaration elements 2
printf(“Enter the array elements:”); 4
for(k=0;k<5;k++) 3
{ 1
scanf(“%d ”,&array[i]); // storing values in array 8
} Display the array
printf(“\n Display the array elements:”); elements 2
for(k=0;k<5;k++) 4
{ 3
printf(“%d \n”,array[i]);//displaying values of array 1
} 8
return 0;
}
FIND SUM AND AVERAGE OF N NUMBERS
#include<stdio.h>
int main( ) Output:
{ Enter the array size: 6
int k,n,sum=0;array[10];//array Enter the array
declaration float avg; elements 9
printf(“\n Enter the array 2
size:”); scanf(“%d”,&n); 4
3
printf(“\n Enter the array
1
elements:”); for(k=0;k<n;k++)
8
{
scanf(“%d ”,&array[i]); // storing values in array
sum=27 and avg=4.50000
}
for(k=0;k<n;k++)
{
sum=sum+array[i]; //sum of array elements
}
avg=sum/n;
printf(“\n sum=%d and avg=%f ”,sum,avg);
}
return 0; Output:
} Enter the array
REVERSE OF ARRAY ELEMENTS elements 2
#include<stdio.h> 4
int main( ) 3
{ 1
int k,n,array[10];//array 8
declaration printf(“\n Enter the Display the array
array size:”); scanf(“%d”,&n); elements 8
printf(“\n Enter the array 1
elements:”); for(k=0;k<n;k++) 3
4
2
VEL TECH MULTI
{
scanf(“%d ”,&array[i]); // storing values in array
}
printf(“\n array elements in reverse
order:”); for(k=n-1;k>=0;k--)
{
printf(“%d \n”,array[i]);//displaying values of array
}
return 0;
}
Write a program to print the position of the smallest number of n numbers using
arrays.
#include <stdio.h>
int main()
{
int i, n, arr[20], small, pos;
printf("\n Enter the number of elements in the array : ");
scanf("%d", &n);
printf("\n Enter the elements :
"); for(i=0;i<n;i++)
scanf("%d",&arr[i]);
small = arr[0] Output
for(i=1;i<n;i++) Enter the number of elements in the array :
{ 5 Enter the elements : 7 6 5 14 3
if(arr[i]<small) The smallest element is : 3
{ The position of the smallest element in
small = the array is : 4
arr[i]; pos =
i;
}
}
printf("\n The smallest element is : %d", small);
printf("\n The position of the smallest element in the array is:
%d",
pos);
return 0;
}
Logic Here the remainders of the integer division of a decimal number by 2 are stored as
consecutive array elements.The division procedure is repeated until the number becomes
0.
Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i,key, FOUND=0, a[30]; // array declaration
printf(“\n How many numbers:”);
scanf(“%d”,&n); // array size Output
printf(“\n Enter the array elements: \n”);
How many numbers: 6
for(i=0 ; i<n; i++) Enter the array
{ elements: 21
scanf(“%d”, &a[i]); 33
} 46
printf(“\n Enter the key to be searched: 52
”); scanf(“%d”,&key); 27
Enter the key to be searched:
for(i=0 ; i<n; i++) // searching an element in an array 73 NOT FOUND
if(a[i] == key)
{
printf(“\n Found at %d”,i);
FOUND=1;
}
if(FOUND = = 0) Output
printf(“\n NOT FOUND...”);
How many numbers: 6
return 0; Enter the array
} elements: 21
33
46
52
27
Enter the key to be searched:
52 Found at 3
EC83 PREPARED BY R.M.D ENGG
BINARY SEARCHING
eliminated The binary search halves the size of the list to search in each
Iteration
Logic : Binary search can be explained simply by the analogy of searching for a page in a
book. Suppose a reader is searching for page 90 in a book of 150 pages. The reader would
first open the book at random towards the latter half of the book. If the page number is less
than 90, the reader would open at a page to the right; if it is greater than 90, the reader would
open at a page to the left, repeating the process till page 90 was found.
INSERTION SORT
The array is searched sequentially and unsorted items are moved and inserted into the sorted
sub-list (in the same array). This algorithm is not suitable for large data sets as its average
and worst case complexity are of Ο(n2), where n is the number of items.
It finds that both 14 and 33 are already in ascending order. For now, 14 is in sorted sub-list.
It swaps 33 with 27. It also checks with all the elements of sorted sub-list. Here we see that
the sorted sub-list has only one element 14, and 27 is greater than 14. Hence, the sorted sub-
list remains sorted after swapping.
EC83 PREPARED BY R.M.D ENGG
By now we have 14 and 27 in the sorted sub-list. Next, it compares 33 with 10....and so on.
Algorithm
Now we have a bigger picture of how this sorting technique works, so we can derive simple
steps by which we can achieve insertion sort.
Program
#include<stdio.h>
int main()
{
int data[100],n,temp,i,j;
printf("Enter number of terms(should be less than 100): ");
scanf("%d",&n);
printf("Enter elements: ");
for(i=0;i<n;i++) Enter number of terms(should be less than 100):5
{
scanf("%d",&data[i]); Enter elements: 33 12 4 26 77
}
for(i=1;i<n;i++) In ascending order: 4 12 26 33 77
{
temp = data[i];
j=i-1;
while(temp<data[j] && j>=0)
/*To sort elements in descending order, change temp<data[j] to temp>data[j]
in above line.*/
{
data[j+1] = data[j];
--j;
}
data[j+1]=temp;
}
printf("In ascending order: ");
for(i=0; i<n; i++)
printf("%d\t",data[i]);
return 0;
}
EC83 PREPARED BY R.M.D ENGG
Ascending order
Step by step descriptive logic to sort array in ascending order.
1. Input size of array and elements in array. Store it in some variable say size and arr.
2. To select each element from array, run an outer loop from 0 to size - 1. The loop
structure must look like for(i=0; i<size; i++).
3. Run another inner loop from i + 1 to size - 1 to place currently selected element at its
correct position. The loop structure should look like for(j = i + 1; j<size; j++).
4. Inside inner loop to compare currently selected element with subsequent element and
swap two array elements if not placed at its correct position.
Which is if(arr[i] > arr[j]) then swap arr[i] with arr[j].
Program
#include <stdio.h>
#define MAX_SIZE 100 // Maximum array size
int main()
{
int arr[MAX_SIZE];
int size;
int i, j, temp;
return 0;
}
OUTPUT
Enter size of array: 10
Enter elements in array: 20 2 10 6 52 31 0 45 79 40
Elements of array in ascending order:
0 2 6 10 20 31 40 45 52 79
EC83 PREPARED BY R.M.D ENGG
/*C program to sort an one dimensional array in descending order.*/
#include <stdio.h>
#define MAX 100
int main()
{
int
arr[MAX],n,i,j;
int temp;
//sort array
for(i=0;i< n;i+
+)
{
for(j=i+1;j< n;j++)
{
if(arr[i]< arr[j])
{
temp =arr[i];
arr[i] =arr[j];
arr[j] =temp;
}
}
}
Two dimentional arrays stores data in tabular column format represented as rows and columns
Array Declaration:
datatype arrayname[size][size];
Array Initialization:
int a[2][2]={ {1,4 },{2,3}}
int b[2][2]={1,4,2,3}
1 4
2 3
12.3 45.2
19.3 23.4
#include <stdio.h>
int main()
{
int i,j;
int a[3][2] = {{4,7},{1,0},{6,2}};
for(i = 0; i < 3; i++)
{
for(j = 0; j < 2; j++)
{
printf(“%d”, a[i][j]);
}
printf(“\n”);
}
return 0;
}
Row-1 4 7
Row -2 1 0
Row-3 6 2
1 2 3 4 5 6 7 8 9
Row 0 Row 1 Row 2
EC83 PREPARED BY R.M.D ENGG
WORKING WITH TWO-DIMENSIONAL ARRAYS
Transpose of a matrix
Transpose of A is AT=(aji), where i is the row number and j is the column number.
Program
#include <stdio.h>
int main()
{
int a[10][10], transpose[10][10], r, c, i, j;
printf("Enter rows and columns of matrix:
"); scanf("%d %d", &r, &c);
Sample output
// getting elements of the matrix Enter rows and columns
printf("\nEnter elements of matrix:\ of matrix: 2
n"); for(i=0; i<r; ++i) 3
for(j=0; j<c; ++j)
{ Enter element of
printf("Enter element a%d%d: ",i+1, j+1); matrix: Enter element
scanf("%d", &a[i][j]); a11: 2 Enter element
} a12: 3 Enter element
a13: 4 Enter element
// Displaying the matrix a[][] */ a21: 5 Enter element
printf("\n Entered Matrix: \ a22: 6 Enter element
n"); for(i=0; i<r; ++i) a23: 4
for(j=0; j<c; ++j)
{ Entered
printf("%d ", a[i][j]); Matrix: 2 3 4
if (j == c-1)
printf("\n\n"); 56 4
}
return 0;
}
EC83 PREPARED BY R.M.D ENGG
Program -2(Transpose)
#include <stdio.h>
void main()
{
int array[10][10];
int i, j, m, n;
$ cc pgm85.c
$ a.out
Enter the order of the matrix
3 3
Enter the coefiicients of the matrix
3 7 9
2 7 5
6 3 4
The given matrix is
3 7 9
2 7 5
6 3 4
Transpose of matrix is
3 2 6
7 7 3
9 5 4
EC83 PREPARED BY R.M.D ENGG
Matrix addition and subtraction
#include <stdio.h>
int main(){
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
#include
<stdio.h>
#include <math.h>
#defi ne row 10
#defi ne col 10
int main()
{
fl oat mat[row][col], s;
int i,j,r,c;
printf(“\n Input number of
rows:”); scanf(“%d”, &r);
printf(“\n Input number of
cols:”); scanf(“%d”, &c);
for(i = 0 ; i< r; i++)
{
for(j = 0 ;j<c; j++)
{
scanf(“%f”, &mat[i][j]);
}
}
printf(“\n Entered 2D array is as follows:\n”);
for(i = 0; i < r; i++)
{
for(j = 0; j < c; j++)
{
printf(“%f”, mat[i][j]);
}
printf(“\n”);
}
s = 0.0;
for(i = 0; i < r; i++)
{
for(j = 0; j < c; j++)
{
s += mat[i][j] * mat[i][j];
}
}
printf(“\n Norm of above matrix is: %f”, sqrt(s));
return 0;
}
CEC83
Program to read a matrix andPREPARED
find sum,BY R.M.D ENGG
product of all elements of two dimensional (matrix)
array
include <stdio.h>
#define MAXROW 10 Enter number of
#define MAXCOL 10
Rows :3 Enter number
int main()
of Cols :3
{
int matrix[MAXROW][MAXCOL];
int i,j,r,c;
Enter matrix
int sum,product; elements : Enter
element [1,1] : 1
printf("Enter number of Rows :"); Enter element [1,2] : 1
scanf("%d",&r); Enter element [1,3] : 1
printf("Enter number of Cols :"); Enter element [2,1] : 2
scanf("%d",&c); Enter element [2,2] : 2
Enter element [2,3] : 2
printf("\nEnter matrix elements :\n"); Enter element [3,1] : 3
for(i=0;i< r;i++) Enter element [3,2] : 3
{ Enter element [3,3] : 3
for(j=0;j< c;j++)
{ SUM of all elements : 18
printf("Enter element [%d,%d] : ",i+1 ,j+Product of all elements
scanf("%d",&matrix[i][j]); :216
}
}
sum=0;
product=1;
for(i=0;i< r;i++)
{
for(j=0;j< c;j++)
{
sum+=matrix[i][j];
product*= matrix[i][j];
} }
printf("\nSUM of all elements : %d \nProduct of all elements :%d",sum,product);
return 0;
}
Find the sum of diagonal elements of a matrix
#include < stdio.h > 1 2 3
int main() 2 4 6
{ 3 5 8
int a[10][10],i,j,sum=0,r,c;
clrscr(); Sum of diagonal=13
printf("\n Enter the number of rows and column ");
scanf("%d%d",&r,&c);
printf("\nEnter the %dX%d matrix",r,c);
for(i=0;i < r;i++)
{
for(j=0;j < c;j++)
{
scanf("%d",&a[i][j]);
}//for
}//for
for(i=0;i < r;i++)
{ for(j=0;j < c;j++)
{ if(i==j)
{
sum+=a[i][j];
}
}//for
EC83 PREPARED BY R.M.D ENGG
}//for
printf("\nThe sum of diagonal elements is %d",sum); return 0;
}//main
#include <stdio.h>
void main ()
{ static int array[10] Enter the order of the
[10]; int i, j, m, n, a = 0, sum matix 2 2
= 0; Enter the co-efficients of the
printf("Enetr the order of the matix \ matrix 40 30
n"); scanf("%d %d", &m, &n); 38 90
if (m == n ) The given matrix
{ is 40 30
printf("Enter the co-efficients of the matrix\n"); 38 90
for (i = 0; i < m; ++i)
{ The sum of the main diagonal elements is
for (j = 0; j < n; ++j) = 130
{ The sum of the off diagonal elements is
scanf("%d", &array[i][j]); = 68
}
}
printf("The given matrix is \n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
printf(" %d", array[i][j]);
}
printf("\n");
}
C Program to Find the Frequency of Odd & Even Numbers in the given Matrix
#include <stdio.h>
void main()
{
Strings in C are represented by arrays of characters. The end of the string is marked with a
special character, the null character
DECLARATION OF STRINGS
char str[30];
char text[80];
STRING INITIALIZATION
char arr[4]={‘s’,'h’,'b',’r‘,’\0’}
char *c = "abcd";
char str=“100”
char str=“3.4”
Char str=“111000”
EC83 PREPARED BY R.M.D ENGG
STRING INPUT /OUTPUT
#include
<stdio.h>
– printf("%s",str), scanf("%s",str) #include
<string.h> int
– gets(str),puts(str) main()
{
– fgets with stdin and fputs with stdout char nickname[20];
scanf("%s",
– fgets( ) and fputs( )…for files nickname);
Eg char s[1000] ;
fgets(s,1000,stdin); #include #include
<stdio.h> <stdio.h>
#include #include
Example program <string.h> int <string.h> int
#include <stdio.h> main() main()
int main() { {
{ char char nickname[20];
char name[10]; nickname[20]; fgets(nickname,20,stdin);
printf("Who are you? "); gets(nickname); fputs(nickname,stdout);
puts(nickname); return 0;
fgets(name,10,stdin); return 0; }
printf("Glad to meet you, %s \n",name);
return(0);
}
String input and output using fscanf() and fprintf()
C program has three I/O streams.
stdin,
stdout, and
stderr
--The input stream is called standard-input (stdin); the usual output stream is called standard-
output (stdout); and the side stream of output characters for errors is called standard error
(stderr).
Example program
#include <stdio.h>
int main()
{
int fi rst, second;
fprintf(stdout,“Enter two ints in this line: ”);
fscanf(stdin,“%d %d”, &fi rst, &second);
fprintf(stdout,“Their sum is: %d.\n”, fi rst + second);
return 0;
}
EC83 PREPARED BY R.M.D ENGG
Character Manipulation
A set of standard C library functions that are contained in <string.h> provides the following.
Function Description
strcpy(s1,s2) Copies s2 into s1
strncpy(s1,s2,n) It copies first n characters of str2 into str1.
strcat(s1,s2) Concatenates s2 to s1. That is, it appends the string contained by s2 to
the end of the string pointed to by s1. The terminating null character
strncat(s1,s2,n) First n characters of str2 is concatenated at the end of str1
strlen(s1) Returns the length of s1. That is, it returns the number of characters in
the string without the terminating null character.
strcmp(s1,s2) Returns 0 if s1 and s2 are the same
Returns less than 0 if s1<s2
Returns greater than 0 if
s1>s2
strncmp(s1,s2,n) Returns 0 if s1 and s2 are the same for first n characters
strcmpi( ) Same as strcmp() function. But, this function negotiates case.
“A” and “a” are treated as same.
strchr(s1,ch) Returns pointer to first occurrence ch in s1
strrchr(s1,ch ) Returns pointer tolast occurrence ch in s1
strstr(s1,s2) Returns pointer to first occurrence s2 in s1
strlen( ) function in C gives the length of the given string
strdup( ) function in C duplicates the given string
strlwr( ) function converts a given string into lowercase
strupr( ) function converts a given string into uppercase
strrev( ) function reverses a given string in C language
strupr( )
strlwr( ) Output:
Output:
modify this MODIFY THIS STRING TO UPPER
#include<stdio.h> #include<string.h> int main()
#include<stdio.h> string to lower
#include<string.h> {
int main() char str[ ] = "Modify This String To Upper";
{ printf("%s\n",strupr(str));
char str[ ] = "MODIFY This String return 0;
To LOwer"; }
printf("%s\n",strlwr (str));
return 0;
}
String Array
String Array = {“abc”, ”def”, “ghi”}
char
char s[5][30];
s[5][10] ={“Cow”,”Goat”,”Ram”,”Dog”,”Cat”};
which is equivalent to
EC83 PREPARED BY R.M.D ENGG
Example program : Search a character in a string
#include<stdio.h>
int main() { Enter a string: apple lime juice
char str[20], ch;
int count = 0, i; Enter the character to be searched
printf("\nEnter a string : ");
scanf("%s", &str); : i Character i is present
#include
<stdio.h> int
main()
{
char s[1000], i;
printf("Enter a string:
"); scanf("%s", s);
Enter a string:
apple Length of
string: 5
copy Two Strings Without Using strcpy( )
#include
<stdio.h> int
main()
{
char s1[100], s2[100], i;
printf("Enter string s1:
"); scanf("%s",s1);
for(i = 0; s1[i] != '\0'; ++i)
{
s2[i] = s1[i];
}
s2[i] = '\0';
printf("String s2: %s",
s2); return 0;
Output
program to convert the lower case characters of a string into upper case without using string
functions
EC83 PREPARED BY R.M.D ENGG
#include <stdio.h>
int main()
{ Output
char str[100], upper_str[100]; Enter the string : Hello
int i=0; The string converted into upper case is : HELLO
clrscr();
printf("\n Enter the string :");
gets(str);
while(str[i] != '\0')
{
if(str[i]>='a' && str[i]<='z')
upper_str[i] = str[i] – 32;
else
upper_str[i] = str[i];
i++;
}
upper_str[i] = '\0';
printf("\n The string converted into upper case is : ");
puts(upper_str);
return 0;
}
program to compare two strings without using string function
#include <stdio.h>
#include <string.h>
int main()
{
char str1[50], str2[50];
int i=0, len1=0, len2=0, same=0;
clrscr();
printf("\n Enter the first string : ");
gets(str1);
printf("\n Enter the second string : ");
gets(str2);
len1 = strlen(str1);
len2 = strlen(str2);
if(len1 == len2)
{
while(i<len1)
{
if(str1[i] == str2[i])
i++;
else break;
}
if(i==len1)
{
same=1;
printf("\n The two strings are equal");
}
}
if(len1!=len2)
printf("\n The two strings are not equal");
if(same == 0)
{
if(str1[i]>str2[i])
printf("\n String 1 is greater than string 2");
else if(str1[i]<str2[i])
printf("\n String 2 is greater than string 1");
}
return 0;
}
Write a program to reverse a given string without using string function
#include <stdio.h>
EC83 PREPARED BY R.M.D ENGG
#include <conio.h>
#include <string.h>
int main() Output
{ Enter the string: Hi there
char str[100], reverse_str[100], temp; The reversed string is: ereht iH
int i=0, j=0;
clrscr();
printf("\n Enter the string : ");
gets(str);
j = strlen(str)–1;
while(i < j)
{
temp = str[j];
str[j] = str[i];
str[i] = temp;
i++;
j––;
}
printf("\n The reversed string is : ");
puts(str);
getch();
return 0;
}
C program to change case from upper to lower and lower to upper without using string function
#include <stdio.h>
int main ()
{ o/p
int i = 0; Input a
char ch, s[1000]; string file
ABC
printf("Input a string\n"); the string
gets(s); is FILEabc
while (s[i] != '\0') {
ch = s[i];
if (ch >= 'A' && ch <= 'Z') // convrt to lower case
s[i] = s[i] + 32;
else if (ch >= 'a' && ch <= 'z') //convert to upper case
s[i] = s[i] - 32;
i++;
}
Printf(“\n the string is:”)
printf("%s\n", s);
return 0;
}
C Program to Count Number of Words in a given Text or Sentence
#include <stdio.h>
#include <string.h>
void main() o/p
{ enter the string
char s[200]; hello how are you friends
printf("enter
int count = the string\n"); number of words in given string are: 5
scanf("%[^\n]s", s);
for (i = 0;s[i] != '\0';i++)
{ if (s[i] == ' ')
count++; }
printf("number of words in given string are: %d\n", count + 1);
return 0;
}
Palindrome program in C language using built in functions
EC83 PREPARED BY R.M.D ENGG
#include <stdio.h>
#include <string.h>
int main() o/p
{ Enter a string to check if it is a
char a[100], b[100]; palindrome wow
printf("Enter a string to check if it is a palindrome\n"); Entered string is a palindrome
gets(a);
strcpy(b,a);
strrev(b);
if (strcmp(a,b) == 0)
printf("Entered string is a palindrome.\n");
else
printf("Entered string isn't a palindrome.\n");
return 0;
}
Palindrome program in C language without using built in functions
#include <stdio.h>
#include <string.h>
int main(){
char string1[20]; o/p
int i, length; Enter a string:wow
int flag = 0; wow is not a palindrome
printf("Enter a string:");
scanf("%s", string1);
length = strlen(string1);
for(i=0;i < length ;i++)
{
if(string1[i] != string1[length-i-1]){
flag = 1;
break;
}}
if (flag) {
printf("%s is not a palindrome", string1);
}
else {
printf("%s is a palindrome", string1);
}
return 0;
}
C program to find the frequency of characters in a string
#include <stdio.h>
#include <string.h> Enter a
int main() string
{ maple tree
char string[100]; a occurs 1 times in the
int c = 0, count[26] = {0}, x; string e occurs 3 times in
printf("Enter a string\n"); the string l occurs 1 times
gets(string); in the string m occurs 1
while (string[c] != '\0') { times in the string p occurs
/** Considering characters from 'a' to 'z' 1 times in the string r
only and ignoring others. */
if (string[c] >= 'a' && string[c] <= 'z') {
x = string[c] - 'a';
count[x]++;
}
c++;
}
for (c = 0; c < 26; c++)
printf("%c occurs %d times in the string.\n", c + 'a', count[c]);
return 0; }
EC83
C program to swap two strings
PREPARED BY R.M.D ENGG
#include <stdio.h>
#include <string.h>
int main()
{
char first[100], second[100], temp[100];
printf("\nBefore Swapping\n");
printf("First string: %s\n", first);
printf("Second string: %s\n\n",
second);
strcpy(temp, first);
strcpy(first, second);
strcpy(second, temp);
printf("After Swapping\n");
printf("First string: %s\n", first);
printf("Second string: %s\n",
second);
return 0;
}
Write a program to extract a substring from the middle of a given string.
#include <stdio.h>
#include <conio.h>
int main()
{
char str[100], substr[100];
int i=0, j=0, n, m;
clrscr();
printf("\n Enter the main string : ");
gets(str);
printf("\n Enter the position from which to start the substring: ");
scanf("%d", &m);
printf("\n Enter the length of the substring: ");
scanf("%d", &n);
i=m;
while(str[i] != '\0' && n>0)
substr[j] = str[i];
i++;
j++;
n––;
}
substr[j] = '\0';
printf("\n The substring is : ");
puts(substr);
getch();
return 0;
}
Output
Enter the main string : Hi there
Enter the position from which to start the substring: 1
Enter the length of the substring: 4
The substring is : i th
EC83 PREPARED BY R.M.D ENGG
Write a program to insert a string in the main text.
#include <stdio.h>
int main()
{
char text[100], str[20], ins_text[100];
int i=0, j=0, k=0,pos;
clrscr();
printf("\n Enter the main text : ");
gets(text);
printf("\n Enter the string to be inserted : ");
gets(str);
printf("\n Enter the position at which the string has to be inserted: ");
scanf("%d", &pos);
while(text[i]! = '\0')
{
if(i==pos) Output
{ Enter the main text : newsman
while(str[k] != '\0') Enter the string to be inserted : paper
{ Enter the position at which the string has to be
ins_text[j] = str[k]; inserted: 4
j++; The new string is: newspaperman
k++;
}
}
else
{
ins_text[j] = text[i];
j++;
} i+
+;
}
ins_text[j] = '\0';
printf("\n The new string is : ");
puts(ins_text);
getch();
return0;
}
Write a program to delete a substring from a text.
#include
<stdio.h> int
main()
{
char text[200], str[20], new_text[200]; Output
int i=0, j=0, found=0, k, n=0,
Enter the main text : Hello, how are
copy_loop=0; clrscr();
you? Enter the string to be deleted : ,
printf("\n Enter the main text : ");
how are you?
gets(text); The new string is : Hello
printf("\n Enter the string to be deleted :
"); gets(str);
while(text[i]!='\0')
{
j=0, found=0, k=i;
while(text[k]==str[j] && str[j]!='\
0')
{ k+
+;
j++;
}
if(str[j]=='\0')
copy_loop=k;
new_text[n] =
text[copy_loop]; i++;
copy_loop++;
n++;
}
new_str[n]='\0';
printf("\n The new string is : ");
puts(new_str);
return 0;
EC83
}
PREPARED BY R.M.D ENGG
Write a program to replace a pattern with another pattern in the text.
#include
<stdio.h>
#include
<conio.h> main()
{
char str[200], pat[20], new_str[200],
rep_pat[100]; int i=0, j=0, k, n=0, copy_loop=0,
rep_index=0; clrscr();
printf("\n Enter the string : ");
gets(str);
printf("\n Enter the pattern to be replaced: ");
gets(pat);
printf("\n Enter the replacing pattern: ");
gets(rep_pat);
while(str[i]!='\0')
{
j=0,k=i;
while(str[k]==pat[j] && pat[j]!='\0')
{ k+
+;
j++;
}
if(pat[j]=='\0')
{
copy_loop=k;
while(rep_pat[rep_index] !='\0')
{
new_str[n] =
rep_pat[rep_index]; rep_index+
+;
n++;
}
}
new_str[n] =
str[copy_loop]; i++;
copy_loop++;
n++;
}
new_str[n]='\0';
printf("\n The new string is : ");
puts(new_str);
getch();
return 0;
}
Output
Enter the string : How ARE you?
Enter the pattern to be replaced :
ARE Enter the replacing pattern : are
The new string is : How are you?