0% found this document useful (0 votes)
8 views56 pages

Unt1 An Unit 2

The document provides an introduction to C programming, covering its core features, basic structure, data types, operators, and expressions. It outlines the steps to develop a C program, including writing, compiling, and executing, as well as detailing the compilation process and common errors. Additionally, it explains variable attributes, type conversion, and the use of operators in expressions, alongside examples of simple C programs.

Uploaded by

vip2pcs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views56 pages

Unt1 An Unit 2

The document provides an introduction to C programming, covering its core features, basic structure, data types, operators, and expressions. It outlines the steps to develop a C program, including writing, compiling, and executing, as well as detailing the compilation process and common errors. Additionally, it explains variable attributes, type conversion, and the use of operators in expressions, alongside examples of simple C programs.

Uploaded by

vip2pcs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

Introduction to C Programming – Data types - Operators and Expressions – Data Input and Output –

Decision making and Looping Statements.


INTRODUCTION TO C PROGRAM
C is a high-level language which also provides the capabilities that enable the programmers to ‘get in close’
with the hardware and allows them to interact with the computer on a much lower level.
a) C is a core language : In computing, C is a general purpose, cross-platform, block structured
procedural, imperative computer programming language.
b) C is a small language: C has only thirty-two keywords. This makes it relatively easy to learn
compared to bulkier languages.
c) C is quick: can write codes which run quickly, and the program can be very ‘close to the hardware’.
d) C is portable: C programs written on one system can be run with little or no modification on other
systems. If modifications are necessary, they can often be made by imply changing a few entries in a
header fi le accompanying the main program.
DEVELOPING PROGRAMS IN C
There are mainly three steps:
1. Writing the C program
2. Compiling the program and
3. Executing it.
• For these steps, some software components are required, namely an operating system, a text
editor(integrated development environment), the C compiler, assembler, and linker.
• C uses a semicolon as a statement terminator; the semicolon is required as a signal to the compiler to
indicate that a statement is complete.
• All program instructions, which are also called statements, have to be written in lower case characters.

A brief explanation of each of the processes involved in the compilation model is given as follows:
Writing or Editing the source program using a text editor or an IDE and saving it with .c extension.
Programming Environment Most programming language compilers come with a specifi c editor that can
provide facilities for managing the programs. Such an editor offers a complete environment for writing,
developing, modifying, deploying, testing, and debugging the programs. Such software is referred to as an
integrated development environment or IDE.
Preprocessing is the fi rst phase of the C compilation. It processes include-fi les, conditional compilation
instructions and macros. preprocessor directive is a statement (such as #defi ne) that gives the preprocessor
specifi c instructions on how to modify your source code. The preprocessor
is invoked as the fi rst part of your compiler program’s compilation step. It is usually hidden from the
programmer because it is run automatically by the compiler.
Compilation is the second pass. It takes the output of the preprocessor, and the source code, and generates
assembler source code.
Assembly is the third stage of compilation. It takes the assembly source code and produces an assembly
listing with offsets. The assembler output is stored in an object file.
Linking is the final stage of compilation. After the program has been translated into object code, it is ready
to be linked. The purpose of the linking phase is to get the program into a final form for execution on the

computer. The program may use other source programs that were previously processed by the compiler.
These functions are stored as separate object fi les which must be
linked to our object fi le. There are three types of errors that may occur:
a) Compile errors These are given by the compiler and prevent the program from not running.
b) Linking errors These are given by the linker or at runtime and ends the program. The linker can also
detect and report errors, for example, if part of the program is missing or a non-existent library
component is referenced.
c) Runtime errors These are given by the operating system. Removing errors from a program is called
debugging.
A SIMPLE C PROGRAM
/* A Simple C Program */
#include <stdio.h>
int main(void)
{
printf(“C is Sea\n”);
return 0;
}
A comment line
/* A Simple C Program */
This is a comment line.In C, the comments can be included in the program. The comment lines start with
/* and terminate with */. These statements can be put anywhere in the program. The compiler considers
these as non-executable statements.
Preprocessor
In C, all lines that begin with # are directives for the preprocessor, which means that all these directives
will be processed before the program is actually compiled. The #include directive includes the contents of
a fi le during compilation. In this case, the fi le stdio.h is added in the source program before the actual
compilation begins. stdio.h is a header fi le that comes with the C compiler and contains information about
input and output functions
e.g. printf()
(a) they must begin in the fi rst column and no spaces are allowed between ‘#’ and include and
(b) theyare not terminated by a semicolon.
main()
This is the starting point of the program. A C program may contain one or more functions one of
which must be main(). Functions are the building blocks of a C program. For now the functions may be
recognized by the presence of parentheses after their names.
{}
This is a brace. As the name implies, braces come in packs of two, i.e. for every open brace there
must be a matching close. Braces allow me to lump pieces of program together. Such a lump of program
is often called a block. Such a block of program instructions, within these braces, form the body of
thefunction main().
printf(“C is Sea\n”);
printf() is a ‘library function’ The \n (pronounced backslash n) in the string argument of the
function printf() “C is Sea\n” is an example of an escape sequence. It is used to print the new line
character. If the program is executed, the \n does not appear in the output. Each \n in the string argument
of a printf() causes the cursor to be placed at the beginning of the next line of output. Think of an escape
sequence as a ‘substitute character’ for outputting special characters or some positional action on the
printing point, known as cursor, when the output device is a visual diaplay unit.
return 0;
This statement indicates that the value returned by the function main(), after the program instructions
in its body
void - It indicates no value.
int – indicates integer datatype
ILLUSTRATED VERSION OF A PROGRAM

BACKSLASH CODE

Summary of major points:


• program execution begins at main()
• keywords are written in lower-case
• statements are terminated with a semi-colon
• text strings are enclosed in double quotes
• C is case sensitive, use lower-case and try not to capitalise variable names
• \n means position the cursor on the beginning of the next line
• printf() can be used to display text to the screen
• The curly braces {} define the beginning and end of a program block.
BASIC STRUCTURE OF C PROGRAMS
C programs are essentially constructed in the following manner, as a number of well defined sections.
/* HEADER SECTION */
/* Contains name, author, revision number*/
/* INCLUDE SECTION */
/* contains #include statements */
/* CONSTANTS AND TYPES SECTION */
/* contains types and #defines */
/* GLOBAL VARIABLES SECTION */
/* any global variables declared here */
/* FUNCTIONS SECTION */
/* user defined functions */
/* main() SECTION */
int main()
{
}
Header File
• The header files, usually incorporate data types, function declarations and macros, resolves this
issue. The file with .h extension is called header file, because it’s usually included at the head of a
program.
• Every C compiler that conforms to the international standard (ISO/IEC 9899) for the language will
have a set of standard header files supplied with it.
• The header files primarily contain declarations relating to standard library functions and macros that
are available with C.
STANDARD HEADER FILES
• During compilation, the compilers perform type checking to ensure that the calls to the library and
other user-defined functions are correct. This form of checking helps to ensure the semantic
correctness of the program.
PHILOSOPHY : MAIN
• main() is a user defined function. main() is the first function in the program which gets called when
the program executes. The start up code c calls main() function. We can’t change the name of the
main() function.
• main() is must.
• According to ANSI/ISO/IEC 9899:1990 International Standard for C, the function called at program
start up is named main. The implementation declares no prototype for this function. It can be
defined with no parameters:
int main(void) { /* ... */ }
• or with two parameters (referred to here as argc and argv) :
• int main(int argc, char *argv[ ]) { /* ... */ }
STRUCTURE : C PROGRAM

DECLARATION & DEFINITION


• Declaration means describing the type of a data object to the compiler but not allocating any space
for it.
➢ A declaration announces the properties of a data object or a function. If a variable or
function is declared and then later make reference to it with data objects that do not match
the types in the declaration, the compiler will complain.
➢ data_type variable_name_1,
• Definition means declaration of a data object and also allocating space to hold the data object.
➢ A definition, on the other hand, actually sets aside storage space (in the case of a data
object) or indicates the sequence of statements to be carried out (in the case of a function).
VARIABLES:ATTRIBUTES
• All variables have three important attributes:
➢ A data type that is established when the variable is defined, e.g., integer, real, character.
Once defined , the type of a C variable cannot be changed.
➢ A name of the variable.
➢ 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. For example, an integer variable can only take
integer values, e.g., 2, 100, –12.
DATA TYPES
The four basic data types are
1. INTEGER

These are whole numbers, both positive and negative. Unsigned integers (positive values only)
are supported. In addition, there are short and long integers.
The keyword used to define integers is,
int
An example of an integer value is 32. An example of declaring an integer variable called sum is,
int sum;
sum = 20;
2. FLOATING POINT
These are numbers which contain fractional parts, both positive and negative. The keyword used to
define float variables is,
float
An example of a float value is 34.12. An example of declaring a float variable called money is,
float money;
money =0.12;
3. DOUBLE
These are exponetional numbers, both positive and negative. The keyword used to define double
variables is,
double
An example of a double value is 3.0E2. An example of declaring a double variable called big is,
double big;
big =312E+7;
4. CHARACTER
These are single characters. The keyword used to define character variables is,
char
An example of a character value is the letter A. An example of declaring a character
variable called letter is,
char letter;
letter= 'A';
Note: the assignment of the character A to the variable letter is done by enclosing the
value in single quotes. Remember the golden rule: Single character - Use single quotes.
Sample program illustrating each data type
Example:
#include < stdio.h >
main()
{
int sum;
float money;
char letter;
double pi;
sum = 10; /* assign integer value */
money = 2.21; /* assign float value */
letter = 'A'; /* assign character value */
pi = 2.01E6; /* assign a double value */
printf("value of sum = %d\n", sum );
printf("value of money = %f\n", money);
printf("value of letter = %c\n", letter);
printf("value of pi = %e\n", pi );
}
Sample program output
value of sum = 10
value of money =2.210000
value of letter =A
value of pi = 2.010000e+06
TYPE CONVERSION
Though the C compiler performs automatic type conversions, the programmer should be aware of
what is going on so as to understand how C evaluates expressions.
➢ When a C expression is evaluated, the resulting value has a particular data type. If all the
variables in the expression are of the same type, the resulting type is of the same type as well.
For example, if x and y are both of int type , the expression x +y is of int type as well.
➢ The smallest to the largest data types conversion with respect to size is along the arrow as
shown below:

OPERATORS AND EXPRESSIONS


An ex pression is a sequence of operators and operands that specifies computation of a value, or that
designates an object or a function, or that generates side effects, or that performs a combination thereof.
ARITHMETIC OPERATORS:
The symbols of the arithmetic operators are

Operation Operator Comment Value of Sum before Value of sum after


Multiply * sum = sum * 2; 4 8
Divide / sum = sum / 2; 4 2
Addition + sum = sum + 2; 4 6
Subtraction - sum = sum -2; 4 2
Increment ++ ++sum; 4 5
Decrement -- --sum; 4 3
Modulus % sum = sum % 3; 4 1
OPERATOR PRECEDENCE:
It dictates the order of evaluation of operators in an expression.
ASSOCIATIVITY:
It defines the order in which operators of the same precedence are evaluated in an expression.
Associativity can be either from left to right or right to left.
OPERATOR PRECEDENCE ASSOCIATIVITY
Function call
Array subscripting
Structure and union member access
Structure and union member access through
pointer
Compound literal
() [] -> . ++ - - Suffix/postfix increment and decrement Left to right
+ - ! ~ (type)* & sizeof Unary operator Right to left
* / % Multiplication/division/modulus left-to-right
+ – Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
< <= Relational less than/less than or equal to
> >= Relational greater than/greater than or equal to left-to-right
Example:
#include <stdio.h>
main()
{
int sum = 50;
float modulus;
modulus = sum % 10;
printf("The %% of %d by 10 is %f\n", sum, modulus);
}
PRE/POST INCREMENT/DECREMENT OPERATORS
PRE means do the operation first followed by any assignment operation. POST means do the operation
after any assignment operation. Consider the following statements
++count; /* PRE Increment, means add one to count */
count++; /* POST Increment, means add one to count */
Example:
#include <stdio.h>
main()
{
int count = 0, loop;
loop = ++count; /* same as count = count + 1; loop =
count; */ printf("loop = %d, count = %d\n", loop, count);
loop = count++; /* same as loop = count; count = count
+ 1; */ printf("loop = %d, count = %d\n", loop, count);
}
If the operator precedes (is on the left hand side) of the variable, the operation is performed first, so the
statement
loop = ++count;
really means increment count first, then assign the new value of count to loop.
THE RELATIONAL OPERATORS
These allow the comparison of two or more variables.
==equal to
!=not equal
< less than
<= less than or equal to
>greater than
>= greater than or equal to
Example:
#include <stdio.h>
main() /* Program introduces the for statement, counts to ten */
{
int count;
for( count = 1; count <= 10; count = count + 1 )
printf("%d ", count );
printf("\n");

}
RELATIONALS (AND, NOT, OR, EOR)
Combining more than one condition
These allow the testing of more than one condition as part of selection statements. The symbols
are
LOGICAL AND &&
Logical and requires all conditions to evaluate as TRUE (non-zero).
LOGICAL OR ||
Logical or will be executed if any ONE of the conditions is TRUE (non-zero).
LOGICAL NOT !
logical not negates (changes from TRUE to FALSE, vsvs) a condition.
LOGICAL EOR ^
Logical eor will be excuted if either condition is TRUE, but NOT if they are all true.
Example:
The following program uses an if statement with logical AND to validate the users input to be in
the range 1-10.
#include <stdio.h>
main()
{
int number; int
valid = 0;
while( valid == 0 ) {
printf("Enter a number between 1 and 10 -->");
scanf("%d", &number);
if( (number < 1 ) || (number > 10) ){
printf("Number is outside range 1-10. Please re-enter\n");
valid = 0;
}
else
valid = 1;
}
printf("The number is %d\n", number );
}
Example:
NEGATION
#include <stdio.h>
main()
{
int flag = 0;
if( ! flag ) {
printf("The flag is not set.\n");
flag = ! flag;
}
printf("The value of flag is %d\n", flag);
}
Example:
Consider where a value is to be inputted from the user, and checked for validity to be within a
certain range, lets say between the integer values 1 and 100.
#include <stdio.h>
main()
{
int number;
int valid = 0;
while( valid == 0 ) {
printf("Enter a number between 1 and 100");
scanf("%d", &number );
if( (number < 1) || (number > 100) ) printf("Number
is outside legal range\n");
else
valid = 1;
}
printf("Number is %d\n", number );
}
THE CONDITIONAL EXPRESSION OPERATOR or TERNARY OPERATOR
This conditional expression operator takes THREE operators. The two symbols used to denote
this operator are
the ? and the :. The first operand is placed before the ?, the second operand between the ? and the
:, and the third after the :. The general format is,
condition ? expression1 : expression2
If the result of condition is TRUE ( non-zero ), expression1 is evaluated and the result of the
evaluation becomes the result of the operation. If the condition is FALSE (zero), then expression2
is evaluated and its result becomes the result of the operation. An example will help,
s = ( x < 0 ) ? -1 : x * x;
If x is less than zero then s = -1
If x is greater than zero then s = x * x
Example:
#include <stdio.h>
main()
{
int input;
printf("I will tell you if the number is positive, negative or zero!"\n");
printf("please enter your number now--->");
scanf("%d", &input );
(input < 0) ? printf("negative\n") : ((input > 0) ? printf("positive\n") :printf("zero\n"));
}
BIT OPERATIONS
C has the advantage of direct bit manipulation and the operations available are,

Operato Value of Sum Value of sum


Operation r Comment before after
sum = sum &
AND & 2; 4 0
OR | sum = sum | 2; 4 6
Exclusive OR ^ sum = sum ^ 2; 4 6
1's
Complement ~ sum = ~sum; 4 -5
sum = sum <<
Left Shift << 2; 4 16
sum = sum >>
Right Shift >> 2; 4 0
Example:
/* Example program illustrating << and >> */
#include <stdio.h>
main()

{
int n1 = 10, n2 = 20, i = 0;
i = n2 << 4; /* n2 shifted left four times */
printf("%d\n", i);
i = n1 >> 5; /* n1 shifted right five times */
printf("%d\n", i);
}
Example:
/* Example program using EOR operator */
#include <stdio.h>
main()
{
int value1 = 2, value2 = 4;
value1 ^= value2;
value2 ^= value1;
value1 ^= value2;
printf("Value1 = %d, Value2 = %d\n", value1, value2);
}
Example:
/* Example program using AND operator */
#include <stdio.h>
main()
{
int loop;
for( loop = 'A'; loop <= 'Z'; loop++ )
printf("Loop = %c, AND 0xdf = %c\n", loop, loop & 0xdf);
}
MANAGING INPUT AND OUTPUT OPERATORS
FORMATTED INPUT/OUTPUT
Printf ():
printf() is actually a function (procedure) in C that is used for printing variables and text. Where
text appears in double quotes "", it is printed without modification. There are some exceptions
however. This has to do with the \ and % characters. These characters are modifier's, and for the
present the \ followed by the n character represents a newline character.
#include <stdio.h>
main()
{
printf("Programming in C is easy.\n");
printf("And so is Pascal.\n");
}
OUTPUT:
Programming in C is easy.
And so is Pascal.
FORMATTERS for printf are,
Cursor Control Formatters
\n newline
\t tab
\r carriage return
\f form feed
\v vertical tab
Scanf ():
Scanf () is a function in C which allows the programmer to accept input from a keyboard.
Example:
#include <stdio.h>
main() /* program which introduces keyboard input */
{
int number;
printf("Type in a number \n");
scanf("%d", &number);
printf("The number you typed was %d\n", number);
}
FORMATTERS FOR scanf()
The following characters, after the % character, in a scanf argument, have the following effect.
d read a decimal integer
o read an octal value
x read a hexadecimal value
h read a short integer
l read a long integer
f read a float value
e read a double value
c read a single character
s read a sequence of characters
[...] Read a character string. The characters inside the brackets
UNFORMATTED INPUT/OUTPUT

Functions Description
Reads a single character from the user at the
getch()
console, without echoing it.
Reads a single character from the user at the console, and
getche()
echoing it.
Reads a single character from the user at the console, and
getchar()
echoing it, but needs an Enter key to be pressed at the end.
gets() Reads a single string entered by the user at the console.
puts() Displays a single string's value at the console.
putch() Displays a single character value at the console.
putchar() Displays a single character value at the console.
DECISION MAKING
IF STATEMENTS
The if statements allows branching (decision making) depending upon the value or state of
variables. This allows statements to be executed or skipped, depending upon decisions. The
basic format is,
Syntax
if( expression ) program
statement;
Example
if( students < 65 )
++student_count;
In the above example, the variable student_count is incremented by one only if the value of the
integer variable students is less than 65.
The following program uses an if statement to validate the users input to be in the range 1-10.
Example:
#include <stdio.h>
main()
{
while( valid == 0 ) {
printf("Enter a number between 1 and 10 -->");
scanf("%d", &number);
/* assume number is valid */ valid = 1;
if( number < 1 ) {
printf("Number is below 1. Please re-enter\n"); valid = 0;
}
if( number > 10 ) {
printf("Number is above 10. Please re-enter\n"); valid = 0;
}
}
printf("The number is %d\n", number );
}
IF ELSE
The general format for these are,
Syntax:
if( condition 1 ) statement1;
else if( condition 2 ) statement2;
else if( condition 3 ) statement3;
else statement4;
The else clause allows action to be taken where the condition evaluates as false (zero).
The following program uses an if else statement to validate the users input to be in the range 1-10.
Example:
#include <stdio.h>
main(){
int number; int valid =0;
while( valid == 0 ) {
printf("Enter a number between 1 and 10 -->"); scanf("%d",&number);
if( number < 1 ) {
printf("Number is below 1. Please re-enter\n"); valid = 0;
}
else if( number > 10 ) {
printf("Number is above 10. Please re-enter\n");
valid = 0;
}
else
valid = 1;
}
printf("The number is %d\n", number );
}
This program is slightly different from the previous example in that an else clause is used to set
the variable valid to 1. In this program, the logic should be easier to follow.
NESTED IF ELSE
/* Illustates nested if else and multiple arguments to the scanf function. */
Example:
#include <stdio.h>
main(){
int invalid_operator = 0;
char operator;
float number1, number2, result;
printf("Enter two numbers and an operator in the format\n");
printf(" number1 operator number2\n");
scanf("%f %c %f", &number1, &operator, &number2);
if(operator == '*')
result = number1 * number2;
else if(operator == '/')
result = number1 / number2;
else if(operator == '+')
result = number1 + number2;
else if ( operator == ' -' )
result = number1 - number2 ;
else
invalid_operator = 1;
if( invalid_operator != 1 )
printf("%f %c %f is %f\n", number1, operator, number2, result );
else
printf("Invalid operator.\n");
}
SWITCH CASE:
The switch case statement is a better way of writing a program when a series of if elses occurs.
The general format for this is,
Syntax
switch ( expression ) {
case value1:
program statement;
program statement;
......
break;
case valuen:
program statement;
.......
break;
default:
.......
.......
}

The keyword break must be included at the end of each case statement. The default clause
is optional, and is executed if the cases are not met. The right brace at the end signifies the
end of the case selections.
Example:
main()
{
int menu, numb1, numb2, total;
printf("enter in two numbers -->");
scanf("%d %d", &numb1, &numb2 );
printf("enter in choice\n");
printf("1=addition\n");
printf("2=subtraction\n"); scanf("%d",&menu );
switch( menu ) {
case 1: total = numb1 + numb2; break;
case 2: total = numb1 - numb2; break;
default: printf("Invalid option selected\n");
}
if( menu == 1 )
printf("%d plus %d is %d\n", numb1,numb2,total );
else if( menu == 2 )
printf("%d minus %d is %d\n", numb1, numb2, total );
}
The above program uses a switch statement to validate and select upon the users input choice,
simulating a simple menu of choices.
BRANCHING AND LOOPING
ITERATION, FOR LOOPS
The basic format of the for statement is,
Syntax
for( start condition; continue condition; re-evaulation)
program statement;
Example:
/* sample program using a for statement
*/ #include <stdio.h>
main() /* Program introduces the for statement, counts to ten */
{
int count;
for( count = 1; count <= 10; count = count + 1)
printf("%d ", count );
printf("\n");
}
The program declares an integer variable count. The first part of the for statement
for( count = 1;
initialises the value of count to 1. The for loop continues whilst the condition
count <= 10;
evaluates as TRUE. As the variable count has just been initialised to 1, this
condition is TRUE and so the program statement
printf("%d ", count );
is executed, which prints the value of count to the screen, followed by a space character.
Next, the remaining statement of the for is executed
count = count + 1 );
which adds one to the current value of count. Control now passes back to the conditional
test,
count <= 10;
which evaluates as true, so the program statement
printf("%d ", count );
is executed. Count is incremented again, the condition re-evaluated etc, until count
reaches a value of 11.
When this occurs, the conditional test
count <= 10
evaluates as FALSE, and the for loop terminates, and program control passes to the statement
printf("\n");
which prints a newline, and then the program terminates, as there are no more statements left to
execute.
THE WHILE STATEMENT
The while provides a mechanism for repeating C statements whilst a condition is true. Its format
is,
Syntax:

while( condition )
program statement;

Somewhere within the body of the while loop a statement must alter the value of the condition
to allow the loop to finish.
Example:
/* Sample program including while */
#include <stdio.h>
main()
{
int loop = 0;
while( loop <= 10 ) {
printf("%d\n", loop);
++loop;
}
}
The above program uses a while loop to repeat the statements
printf("%d\n", loop);
++loop;
whilst the value of the variable loop is less than or equal to 10.
Note how the variable upon which the while is dependant is initialised prior to the while statement (in
this case the previous line), and also that the value of the variable is altered within the loop, so that
eventually the conditional test will succeed and the while loop will terminate.
This program is functionally equivalent to the earlier for program which counted to ten
THE DO WHILE STATEMENT
The do { } while statement allows a loop to continue whilst a condition evaluates as TRUE (non-
zero). The loop is executed as least once.
Syntax:
while( condition )
program statement;
Example:
/* Demonstration of DO...WHILE */
#include <stdio.h>
main(){
int value, r_digit;
printf("Enter the number to be reversed.\n");
scanf("%d", &value);
do {
r_digit = value % 10;
printf("%d", r_digit);
value = value / 10;
} while( value != 0 );
printf("\n");
}
The above program reverses a number that is entered by the user. It does this by using the modulus
% operator to extract the right most digit into the variable r_digit. The original number is then
divided by 10, and the operation repeated whilst the number is not equal to 0.
VELAMMAL ENGINEERING COLLEGE

DEPARTMENT OF CSE & IT

19CS101T / PROGRAMMING FOR PROBLEM SOLVING IN C

UNIT II

ARRAYS AND STRINGS

Defining an array – Processing an Single and Two Dimensional array


– Multidimensional Arrays, Character Arithmetic – Defining a string –
NULL character – Initialization of Strings – Reading and Writing
Strings – Processing Strings –Searching and Sorting of Strings.

ARRAYS

Definition:
An array is a derived data type. It is a collection of data elements of similar
data types. The data elements are stored in contiguous memory location.

Syntax :
datatype arrayname[size]
int a[10];
where
int is the data type of the elements.
a is the array name.
[10] is the index which denotes the array contains 10 data elements.

ARRAY INITIALIZATION:
The array can be initialized with elements while declaring the array.
Example:
int a[5]={1,2,3,4,5}
Here, 5 data elements are stored in the array called “a”. The array elements
are stored sequentially in separate locations.
The array elements are called as below:
A[0] refers to 1st element 1
A[1] refers to 1st element 2
A[2] refers to 1st element 3
A[3] refers to 1st element 4
1
A[4] refers to 1st element 5
CHARACTERISTICS OF AN ARRAY:

1. All the data elements share the same name, and they are distinguished
from one another with the help of an element number.
2. Any particular element of an array can be modified separately without
disturbing other elements.
3. The element number in an array plays major role for calling each
element.

CLASSIFICATION OF ARRAY:

Arrays can be classified into major types.

1. One-dimensional Array.
2. Two dimensional Array.

3. Multi dimensional Array.

1. One-Dimensional Array:

The array elements are arranged in rows or columns. The data are stored
in continuous memory location.

Example:

int a[5]={1,2,3,4,5}

Address 2000 2004 2008 2012 2016


Element a[0] a[1] a[2] a[3] a[4]
Values 1 2 3 4 5

Example Program:

#include<stdio.h>
void main()
{
int a[10],n,i;
clrscr();
2
printf("\nEnter the size of the array");
scanf("%d",&n);
printf("\nEnter the elements into the array one by one");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nThe array elements are\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
getch();
}

OUTPUT:

Enter the size of the array5

Enter the elements into the array one by one


1
2
3
4
5

The array elements are


1 2 3 4 5

SUM OF THE ELEMENTS IN AN ARRAY


#include <stdio.h>
#include <conio.h>
void main()
{
int a[25],i,j,n,sum=0;
clrscr();
printf("\nEnter the no. of elements in the array");
scanf("%d",&n);
printf("\nEnter the elements in the array\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
sum=sum+a[i];
}
printf("\nThe sum of the elements in the array is %d",sum);
getch();}
3
OUTPUT:

Enter the no. of elements in the array4


Enter the elements in the array
4
3
2
1

The sum of the elements in the array is 10

LARGEST ELEMENT IN AN ARRAY

#include <stdio.h>
#include <conio.h>
void main()
{
int a[25],i,n,max;
clrscr();
printf("\nEnter the no. of elements in the array");
scanf("%d",&n);
printf("\nEnter the elements in the array\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
max=a[0];
for(i=1;i<n;i++)
{
if(a[i]>max)
max=a[i];
}
printf("\nThe largest element is %d",max);
getch();
}

output:
Enter the no. of elements in the array4
Enter the elements in the array
6
7
5
45
The largest element is 45

4
SEARCHING AN ELEMENT IN AN ARRAY

Linear search

#include <stdio.h>
#include <conio.h>
void main()
{
int a[25],i,j,n,x;
clrscr();
printf("\nEnter the no. of elements in the array");
scanf("%d",&n);
printf("\nEnter the elements in the array\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\nEnter the element to be searched in the array");
scanf("%d",&x);
for(i=0;i<n;i++)
{
if(a[i]==x)
{
printf("\nThe element is found");
break;
}
}
if(i==n)
{
printf("\nThe element is not found");
}
getch();
}
OUTPUT:
Enter the no. of elements in the array 4
Enter the elements in the array
2
1
4
5
Enter the element to be searched in the array 2
The element is found

5
Binary Search:

#include<stdio.h>
void main()
{
int arr[50],i,n,x,flag=0,first,last,mid;

printf("Enter size of array:");


scanf("%d",&n);
printf("\nEnter array element(ascending order)\n");

for(i=0;i<n;++i)
scanf("%d",&arr[i]);

printf("\nEnter the element to search:");


scanf("%d",&x);

first=0;
last=n-1;
while(first<=last)
{
mid=(first+last)/2;
if(x==arr[mid])
{
flag=1;
break;
}
else if(x>arr[mid])
first=mid+1;
else
last=mid-1;
}
if(flag==1)
printf("\nElement found at position %d",mid+1);
else
printf("\nElement not found");

Output:

Enter size of array:6


Enter array element(ascending order)
20 27 40 50 58 99
Enter the element to search:27
Element found at position 2

6
INSERTING AN ELEMENT INTO AN ARRAY

#include <stdio.h>
void main()
{
int a[30],i,n,x,p;
clrscr();
printf("\nEnter the size of the array");
scanf("%d",&n);
printf("\nenter the elements into the array");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nEnter the element to be inserted");
scanf("%d",&x);
printf("\nEnter the position in which the element to be inserted");
scanf("%d",&p);
for(i=n-1;i>=p;i--)
a[i+1]=a[i];
a[p]=x;
printf("\nThe elements are \n");
for(i=0;i<=n;i++)
printf("%d\t",a[i]);
getch();
}
OUTPUT:
Enter the size of the array 5

enter the elements into the array


3 4 5 2 1

Enter the element to be inserted 5

Enter the position in which the element to be inserted 3

The elements are

3 4 5 5 2 1

SORTING OF AN ARRAY

#include <stdio.h>
#include <conio.h>
void main()
{
int a[25],i,j,n,temp;
clrscr();
printf("\nEnter the no. of elements in the array");
7
scanf("%d",&n);
printf("\nEnter the elements in the array\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("\nThe sorted array is \n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
getch();
}

OUTPUT:

Enter the no. of elements in the array6

Enter the elements in the array


4
1
7
4
7
2

The sorted array is


1 2 4 4 7 7

8
Bubble Sort:

#include <stdio.h>
int main()
{
int array[100], n, i, j, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (i = 0; i< n; i++)
scanf("%d", &array[i]);
for (i = 0 ; i < n - 1; i++)
{
for (j= 0 ; j < n - i - 1; j++)
{
if (array[j] > array[j+1])
{
swap = array[j];
array[j] = array[j+1];
array[ j+1] = swap;
}
}
}
printf("Sorted list in ascending order:\n");
for (i = 0; i < n; i++)
printf("%d\n", array[i]);
}

Output:

9
2.Two-Dimensional Array:

The array elements are thought to be stored in the form of rows and columns.

Syntax :
datatype arrayname[row size][column size];
int a[3][3];

Diagrammatic representation:

Column 1 Column 2 Column 3


Row 1 a[0][0] a[0][1] a[0][2]
Row 2 a[1][0] a[1][1] a[1][2]
Row 3 a[2][0] a[2][1] a[2][2]

The above arrangement of array elements is only for understanding.


Physically array elements are stored in continuous memory locations. The
two dimensional array is a collection of one-dimensional array, which are
placed one after another.

Example Program:

#include<stdio.h>
void main()
{
int a[10][10],n,i,j;
clrscr();
printf("\nEnter the size of the array");
scanf("%d",&n);
printf("\nEnter the elements into the array one by one");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\nThe array elements are\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
10
getch();
}

OUTPUT:

Enter the size of the array2

Enter the elements into the array one by one


1
2
3
4

The array elements are


1 2
3 4

PROGRAMS IN TWO DIMENSIONAL ARRAY

MATRIX ADDITION

#include <stdio.h>
#include <conio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,k,m,n;
clrscr();
printf("\nEnter the no. of rows in the matrix A");
scanf("%d",&m);
printf("\nEnter the no. of columns in the matrix A");
scanf("%d",&n);
printf("\nEnter the elements in the matrix A");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nEnter the elements in the matrix B");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&b[i][j]);
11
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf("\nThe Resultant matrix is\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
getch();
}

OUTPUT:

Enter the no. of rows in the matrix2

Enter the no. of columns in the matrix2

Enter the elements in the matrix A


1
1
1
1

Enter the elements in the matrix B


1
1
1
1

The Resultant matrix is


2 2
2 2

12
MATRIX MULTIPLICATION

#include <stdio.h>
#include <conio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,k,m,n,p;
clrscr();
printf("\nEnter the no. of rows in the matrix A");
scanf("%d",&m);
printf("\nEnter the no. of columns in the matrix A");
scanf("%d",&n);
printf("\nEnter the no. of columns in the matrix B");
scanf("%d",&p);
printf("\nEnter the elements in the matrix A");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nEnter the elements in the matrix B");
for(i=0;i<n;i++)
{
for(j=0;j<p;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("\nThe Resultant matrix is\n");
for(i=0;i<m;i++)
{
for(j=0;j<p;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
printf("%d\t",c[i][j]);
}
printf("\n");
}
getch();
}
13
OUTPUT:
Enter the no. of rows in the matrix A2

Enter the no. of columns in the matrix A2

Enter the no. of columns in the matrix B2

Enter the elements in the matrix A


1
1
1
1

Enter the elements in the matrix B


1
1
1
1

The Resultant matrix is


2 2
2 2

TRANSPOSE OF A MATRIX:
#include <stdio.h>

void main()
{
static int array[10][10];
int i, j, m, n;

printf("Enter the order of the matrix \n");


scanf("%d %d", &m, &n);
printf("Enter the coefiicients of the matrix\n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
scanf("%d", &array[i][j]);
}
}
printf("The given matrix is \n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
14
{
printf(" %d", array[i][j]);
}
printf("\n");
}
printf("Transpose of matrix is \n");
for (j = 0; j < n; ++j)
{
for (i = 0; i < m; ++i)
{
printf(" %d", array[i][j]);
}
printf("\n");
}
}

Output:
Enter the order of the matrix
33
Enter the coefiicients of the matrix
379
275
634
The given matrix is
379
275
634
Transpose of matrix is
326
773
954

SUM OF DIAGONAL ELEMENTS IN A MATRIX

#include <stdio.h>
#include <conio.h>
void main()
{
int a[10][10],i,j,m,n,sum=0;
clrscr();
printf("\nEnter the no. of rows in the matrix A");
scanf("%d",&m);
printf("\nEnter the no. of columns in the matrix A");
scanf("%d",&n);
printf("\nEnter the elements in the matrix A");
15
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nThe Addition of diagonal elements in the matrix is\n");
for(i=0;i<m;i++)
{
sum=sum+a[i][i];
}
printf("%d",sum);
getch();
}

OUTPUT:

Enter the no. of rows in the matrix A 2

Enter the no. of columns in the matrix A 2

Enter the elements in the matrix A


1
1
1
1

The Addition of diagonal elements in the matrix is


2

3.Multi Dimensional Array:


In C programming, you can create an array of arrays. These arrays are
known as multidimensional arrays.

int test[2][3][4] = {
{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
{{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}} };

Three-dimensional:

#include <stdio.h>
void main()
{
int test[2][3][2];
16
printf("Enter 12 values: \n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
scanf("%d", &test[i][j][k]);
}
}
}
printf("\nDisplaying values:\n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);
}
}
}

17
CHARACTER ARRAY:

The data elements stored in the array belong to character data type.
Hence the name, character array.

The character array can be used to stored individual characters or a


collection of characters called strings. If a string is stored in the character
array, a null character (‘\0’) is automatically added to the array at the end,
which denotes the end of the string.
Example program:

Program to display character array & their addresses:


#include <stdio.h>
void main()
{
char a[]={'A','B','C','D'};
int i;
clrscr();
for(i=0;a[i]!='\0';i++)
{
printf("\nThe array elements are : %c",a[i]);
printf("\nThe memory location is %u",&a[i]);
}
getch();
}
OUTPUT:

The array elements are : A


The memory location is 65522
The array elements are : B
The memory location is 65523
The array elements are : C
The memory location is 65524
The array elements are : D
The memory location is 65525

18
STRING HANDLING:

In C language, the group of characters, digits and symbols


enclosed within quotation marks are called strings. The string is always
declared as character arrays. Every string is terminated with ‘\0’ (NULL)
character. The NULL character is a byte with all bits at logic zero.

DECLARATION & INITIALIZATION OF STRING

The string can be initialized as follows:

char name[]=”India”;

The C compiler inserts the NULL character automatically at the end of the
string. So, initialization of NULL character is not essential.
Display of strings with different formats:

Let the character array be

Char name[]=”computer”;

S.No Statement Output Meaning


1. printf(“%s”,name); Computer The whole string is
displayed
2. printf(“%.5s”,name); Compu Only 5 characters are
displayed
3. printf(“%-10.4s”,name); Comp 4 characters from the
left are displayed

Read & write Strings in C using Printf() and Scanf() functions


#include <stdio.h>
#include <string.h>
int main()
{
/* String Declaration*/
char nickname[20];

printf("Enter your Nick name:");


scanf("%s", nickname);

/*Displaying String*/
printf("%s",nickname);

return 0;
}
19
Read & Write Strings in C using gets() and puts() functions
#include <stdio.h>
#include <string.h>
int main()
{
/* String Declaration*/
char nickname[20];

/* Console display using puts */


puts("Enter your Nick name:");

/*Input using gets*/


gets(nickname);

puts(nickname);

return 0;
}

STRING STANDARD FUNCTIONS

Every C compiler supports a large number of string handling library


functions. Some of the standard string functions are given below:

S.No Function Description


1. strlen( ) Determines the length of the string

2. strcpy( ) Copies a string from source to destination

3. strcmp( ) Compares the characters of two strings.

4. strcat( ) Appends source string to destination string

5. strrev( ) Reverses the string

6. strupr( ) Converts s to all uppercase

7. strlwr( ) Converts string to all lowercase

6. strncpy( ) Copy the specified number of characters

7. strncmp( ) Compare two string upto given n character

8. stricmp( ) Compare two strings alphabetically


without case sensitivity

20
9. strncat( ) Appends a string to the end of another
string up to n

10. strtok( ) Breaks a string into tokens by delimiters

C String function – strlen


It returns the length of the string without including end character (terminating
char ‘\0’).

Syntax:
strlen(string)

Example of strlen:
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "Welcome";
printf("Length of string str1: %d", strlen(str1));
return 0;
}

Output:
Length of string str1: 7

C String function – strcpy


The strcpy() function copies the string pointed by
source (including the null character) to the destination.

Syntax:
strcpy(destination, source);

Example of strcpy:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[30];
char s2[30] = "Good Day!";
/* this function has copied s2 into s1*/
strcpy(s1,s2);
printf("%s", s1);
return 0;
}

Output:
Good Day!

C String function – strcmp


It compares the two strings and returns an integer value. If both the strings are
same (equal) then this function would return 0 otherwise it may return a negative or
positive value based on the comparison.
21
Syntax:
strcmp(str1, str2)

Example of strcmp:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "Goodday";
char s2[20] = "Welcome";
if (strcmp(s1, s2) ==0)
{
printf("string 1 and string 2 are equal");
}
else
{
printf("string 1 and 2 are different");
}
return 0;
}

Output:
string 1 and 2 are different

C String function – strcat

It concatenates two strings and returns the concatenated string.

Syntax:
strcat(str1,str2)

Example of strcat:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
return 0;
}

Output:
Output string after concatenation: HelloWorld

C String function – strrev


strrev( ) function reverses a given string in C language.
Syntax : strrev(string)
strrev(string)

Example of strrev:

22
#include<stdio.h>
#include<string.h>

int main()
{
char name[30] = "Hello";

printf("String before strrev( ) : %s\n",name);


printf("String after strrev( ) : %s",strrev(name));

return 0;
}
Output:
String before strrev( ) : Hello
String after strrev( ) : olleH

C String function – strlwr


strlwr( ) function converts a given string into lowercase.

Syntax
strlwr(string)

Example of strlwr:

#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = "MODIFY This String To LOwer";
printf("%s\n",strlwr (str));
return 0;
}
Output:
modify this string to lower

C String function – strupr


strupr( ) function converts a given string into uppercase.

Syntax
strupr(string)

Example of stuprr:

#include<stdio.h>
#include<string.h>

int main()
{
char str[ ] = "Modify This String To Upper";
23
printf("%s\n",strupr(str));
return 0;
}
Output:
MODIFY THIS STRING TO UPPER

STRING OPERATIONS USING PREDEFINED FUNCTIONS


#include <stdio.h>
#include <conio.h>
#include <string.h>
void str_len();
void str_comp();
void str_con();
void str_cpy();
char a[25],b[25],c[50];
void main()
{
int choice;
clrscr();
printf("1. finding the length of the string");
printf("\n2. string comparison");
printf("\n3. string copy");
printf("\n4. String concatenate");
printf("\nEnter ur choice");
scanf("%d",&choice);
switch(choice)
{
case 1:
str_len();
break;
case 2:
str_comp();
break;
case 3:
str_cpy();
break;
case 4:
str_con();
break;
default:
exit(1);
}
getch();
}

void str_len()
24
{
int n;
fflush(stdin);
printf("\n Enter the string");
gets(a);
n=strlen(a);
printf("\nThe length of the string is %d",n);
}

void str_comp()
{
fflush(stdin);
printf("\n Enter the I string");
gets(a);
printf("\nEnter the II String");
gets(b);
if(strcmp(a,b)==0)
printf("\n The two strings are identical");
else
printf("\nThe strings are different");
}

void str_cpy()
{
fflush(stdin);
printf("\n Enter the string");
gets(a);
strcpy(b,a);
printf("\nThe copied string :");
puts(b);
}

void str_con()
{
fflush(stdin);
printf("\n Enter the I string");
gets(a);
printf("\nEnter the II String");
gets(b);
strcat(a,b);
printf("\nThe concatenated string is : ");
puts(a);
}

OUTPUT:

25
1. finding the length of the string
2. string comparison
3. string copy
4. String concatenate

Enter ur choice 1

Enter the string computer

The length of the string is 9

STRING OPERATIONS WITHOUT USING PRE-DEFINED


FUNCTIONS

#include <stdio.h>
#include <conio.h>
#include <string.h>
void str_len();
void str_con();
void str_cpy();
char a[25],b[25],c[50];
void main()
{
int choice;
clrscr();
printf("1. finding the length of the string");
printf("\n2. string copy");
printf("\n3. String concatenate");
printf("\nEnter ur choice");
scanf("%d",&choice);
switch(choice)
{
case 1:
str_len();
break;
case 2:
str_cpy();
break;
case 3:
str_con();
break;
default:
exit(1);
}
getch();
}
26
void str_len()
{
int n=0,i;
fflush(stdin);
printf("\n Enter the string");
gets(a);
for(i=0;a[i]!='\0';i++)
n++;
printf("\nThe length of the string is %d",n);
}

void str_cpy()
{
int i;
fflush(stdin);
printf("\n Enter the string");
gets(a);
for(i=0;a[i]!='\0';i++)
b[i]=a[i];
printf("\nThe copied string :");
puts(b);
}

void str_con()
{
int n=0,i;
fflush(stdin);
printf("\n Enter the I string");
gets(a);
printf("\nEnter the II String");
gets(b);
for(i=0;a[i]!='\0';i++)
{
n++;
}
for(i=0;b[i]!='\0';i++)
{
a[n++]=b[i];
}
printf("\nThe concatenated string is : ");
puts(a);
}

27
OUTPUT:

1. finding the length of the string


2. string copy
3. String concatenate
Enter ur choice 2

Enter the string computer

The copied string : computer

TWO DIMENSIONAL CHARACTER ARRAY

Like a two-dimensional integer array, a character array can be a two


dimensional array. A collection of strings can be stored in a two dimensional
array.

The syntax is:

Char a[2][10];

Here, The array accommodates 2 strings with 9 characters long. The last
location is allotted for storing the NULL character.

Example Program;

#include<stdio.h>
void main()
{
char a[4][10],i,j,n;
clrscr();
printf("\nEnter the number of names to be stored in the array");
scanf("%d",&n);
printf("\nEnter the names one by one\n");
for(i=0;i<n;i++)
{
fflush(stdin);
gets(a[i]);
}
printf("\nThe names are\n");
for(i=0;i<n;i++)
{
puts(a[i]);
printf("\n");
28
}
getch();
}

OUTPUT:

Enter the number of names to be stored in the array3

Enter the names one by one


arthi
archana
kanimozhi

The names are


arthi
archana
kanimozhi

SORTING OF NAMES IN A TWO DIMENSIONAL CHARACTER


ARRAY

#include <stdio.h>
#include <conio.h>
void main()
{
char a[25][25],i,j,n,temp[20];
clrscr();
printf("\nEnter the no. of strings in the array");
scanf("%d",&n);
printf("\nEnter the strings in the array\n");
for(i=0;i<n;i++)
{
scanf("%s",a[i]);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(a[i],a[j])>0)
{
strcpy(temp,a[i]);
strcpy(a[i],a[j]);
strcpy(a[j],temp);
}
}
29
}
printf("\nThe sorted strings in the array is \n");
for(i=0;i<n;i++)
{
printf("%s\n",a[i]);
}
getch();
}

OUTPUT:

Enter the no. of strings in the array3


Enter the strings in the array
cse
ece
it

The sorted strings in the array is


cse
ece
it

Search a String in the List of Strings


#include<stdio.h>
#include<string.h>
int main()
{
char str[20][50], s1[50];
int n, i, found=0;

printf("Enter how many string (names): ");


scanf("%d", &n);

printf("Enter %d strings:\n", n);


for(i=0; i<n; i++)
{
scanf("%s", str[i]);
}

printf("Enter a string to search: ");


scanf("%s", s1);

for(i=0; i<n; i++)


{
if(strcmp(s1, str[i]) == 0)
{
found=1;
printf("Found in row-%d\n", i+1);

30
}
}

if(found==0) printf("Not found");


return 0;
}

Output for the different test-cases:-

Enter how many string (names): 5


Enter 5 strings:
Java
HTML
Python
C++
Programming
Enter a string to search: Python
Found in row-3

Enter how many string (names): 3


Enter 3 strings:
C
C++
.NET
Enter string to search: Java
Not found

************

31

You might also like