Sie sind auf Seite 1von 46

About C

What is C

C is a general purpose, structured language. Its instruction consist of terms that resemble
algebric expression. C has certain special features that allow it to be used at a lower level
i.e. closer to hardware, thus bridging the gap between machine language and more
conventional higher programming language. This flexibility allows C to be used for
system programming (for writing operating system) as well as application programming
(e.g. for writing program to solve a complicated system of mathematical equation, or for
writing a program to bill customer) and hence C is known as middle level language.

As a programming language, C is rather like Pascal or Fortran. Values are stored in


variables. Programs are structured by defining and calling functions. Program flow is
controlled using loops, if statements and function calls. Input and output can be directed
to the terminal or to files. Related data can be stored together in arrays or structures.

Of the three language, C allows the most precise control of input and output. C is also
rather terser than Fortran or Pascal. This can result in short efficient program, where the
programmer has made wise use of C’s range of powerful operators. It also allows the
programmer to produce programs, which are impossible to understand.

Programmers who are familiar with the use of pointers (or indirect addressing, to use the
correct term) will welcome the ease of use compared with some other languages.
Undisciplined use of pointers can lead to errors, which are very hard to trace.

It is hoped that newcomers will find C a useful and friendly language. Care must be taken
in using C. Many of the extra facilities which it offers can leas to extra types of
programming error. You will have to learn to deal with these to successfully make the
transition to being a C programmer.

The UNIX system is itself written in C. In fact C was invented specifically to implement
UNIX. All of the UNIX commands which you type, plus the other system facilities such
as password checking, line printer queues or magnetic tape controllers are written in C.

In the course of the development of UNIX, hundreds of functions were written to give
access to various facets of the system. These functions are available to the programmer in
libraries. By writing in C can using the UNIX system libraries, very powerful system
program can be created. These libraries are less easy to access using other programming
languages. C is therefore the natural language for writing UINX system programs.

History of C
C was originally developed in the 1970 by Dennis Ritchie and Keringhan at Bell
laboratories (now a part of AT & T). It is an outgrowth of two earlier language, called
BCPL AND B which were also developed at Bell laboratories.
In 1978 when C get immense popularity the American National standards Institute
defined a standard for C, eliminating much uncertainty about the exact syntax of the
language. This newcomer, called ANSI C, proclaims itself the standard version of the
language. As such it will inevitably overtake, and eventually replace common C.

ANSI C does incorporate a few improvements over the old common C. The main
differently within the computer memory. A variable is a named location in memory that
is used to hold A value that may be modified by program. All variable have to declare
before they can be used.
There are 3 atomic type of data types in C:

1. Integer
2. Float
3. character

Integer:
Integer are used to represent non decimal numbers in memory location. They are declared
by keyword int. Integer are further classified as:
Name of data type Access specifier Size in bytes Range of numbers
Short int %d 2bytes -32768to32767
Long %ld 4bytes -2.14,483,648to2,147,483,648
Signed int %d 4bytes -32768 to 32767
Unsigned int %u 4bytes 0 to 65535

FLOAT:
Float are used to represent decimal numbers in memory location. They are declared by
keyword
Float. Float are further classified as:
Name Access Apecifiers Size (Bytes) Range
Float %f 4 3.4*(10**-38)to3.4*(10**+38)
Double %lf 8 1.7*(10**-380to3.4*(10**+38)
Long double %lF 10 3.4*(10**-4932)to1.1*(10**+4932)

CHAR:
Char are used to reperesent one character in memory location. They can be uppercase
letter from A TO Z, the lowercase latter a to z, the digit from 0 to 9, and certain special
character.
Name Acess Specifiers Size(Bytes) Range
Singed char %c 1 -128to127
Unsigned char %c 1 0 to 255

Identifiers
Identifiers are names that are given to various program elements such as variables,
function and arrays. Identifiers consist of letters and digit, in any order, except one thing
that, the first character must be letter.
2. Both upper case and lower case letter are permitted.
3. All character are allowed

C Language Keywords
The following names are reserved by the C language. Their meaning is already defined,
and they cannot be re-defined to mean anything else.
Auto Extern Size of
Break Float Static
Case For Struct
Char Goto Switch
Const If Type def
Continue Int Union
Default Long Unsigned
Do Register Void
Double Return Volatile
Else Short while

Other than these names, you choose any names of reasonable length for variables,
functions etc. The names must begin with a letter or underscore (letter are better), and
then can contain letters, numbers and underscores.

Library function

The C language is accompanied by a number of library functions that carry out various
commonly used operations or calculations. These library functions are not a part of the
language per se, through all implementations of the language include them. These are
library functions that carry out standard input/output operations (e.g., read and write
characters, read and write numbers, open and close files, test for end of file, etc.),
functions that perform operation on characters functions that perform operations on string
(e.g., copy a string, compare string, concatenate strings, etc.) and functions that carry out
various mathematical calculations (e.g, evaluate trigonometric, logarithmic and
exponential functions, compute absolute values, square roots, etc.). Other kinds of library
functions are also available.

Library functions that are functionally similar are usually grouped together as (compiled)
object programs in separate library files. These library files are supplied as a part of each
C compiler.

In order to use a library function it may be necessary to include certain specific


information within the main portion of the program. This is accomplished with the
preprocessor statement # include; i.e.,
e.g. #include<stdio.h>
The names of these special files are specified by each individual implementation of C,
through there are certain commonly used file names such as stdlib.h and math.h. The
suffix “h” generally designates a “header” file, which indicated that it is to be included at
the beginning of the program. Some more inclusion.

#include<conio.h>

Input and output

Input and output are covered in some detail. C allows quite precise control of these. This
section discusses input and output from keyboard and screen.

The same mechanisms can be used to read or write data from and to files. It is also
possible to treat character strings in a similar way, constructing or analysing them and
storing results in variables. These variables. These variants of the basic input and output
commands are discussed in the next section

The Standard Input Output File


Character Input / Output
Getchar
Putchar
Formatted Input / output
Printf
Scanf
Whole Lines of Input and Output
Gets
Puts

The Standard input Output File

The standard input output file contains most of the functions along with
definitions of the data types required to use these facilities, your program must include
these definitions by adding the line This is done by adding the line

#include <stdio.h>
Near the start of the program file.
If you do not do this, the compiler may complain about undefined or data types.

Character Input / Output

This is the lowest level of input and output. It provides very precise control, but is
usually too fiddly to be usefully. Most computers perform buffering of input and output.
This means that they’ll not start reading any input until the return key is pressed, and
they’ll not print characters on the terminal until there is a whole line to be printed.

Getchar
Putchar

Getchar

Getchar returns the next character of keyword input as an int. if there is an error
then EOF (end of file) is returned instead. It is therefore usual to compare this value
against EOF before using it. If the return value is stored in a char, it will never be equal to
EOF, so error conditions will not be handled correctly.

As an example, here is a program to count the number of characters read until an


‘*’ is encountered.

#include <stdio.h.
Main( )
{ int ch, I = 0;
While ((ch = getchar( ) ) ! = ‘*’)
I ++;
Printf (“%d \n”, i);
}

Putchar

Putchar puts its character argument on the standard output (usually the screen).

The following example program converts any typed input into capitals. To do this it
applies the function toupper from the character conversion library ctype.h to each
character in turn.

#include <ctype.h> /* For definition of toupper * /


#include <stdio.h> /* For definition of getchar, putchar, EOF * /
Main ( )
{ int ch;
While (( ch = getchar( ) ) ! = EOF)
Putchar (toupper ( ch) );
}

Formatted Input / Output

We have met these function earlier in the course. They are closest to the facilities
offered by Pascal or Fortran, and usually the easiest to use for input and output. The
versions offered under C are a little more detailed, offering precise control of layout.
printf
scanf

printf
This offers more structures output than putchar. Its arguments are, in order; a
control string, which controls what gets printed, followed by a list of values to be
substituted for entries in the control string. Output data can be written from the computer
to the standard output device using the library function printf( ). This function can be
used to output any combination of numerical values, single character and strings.

In general terms, the printf function is written as:

Printf(control string,arg2,………argn)

Where control string refers to a string that contain formatting information and
arg1, arg2…argn are argument that represents the individual output data items. The
control string consists of individual groups of character, either one – character group for
each output data item. Each character group will consist of percent sign (%) followed by
a conversion character indicating the type of the corresponding data item.

Where control string refers to a string that contain formatting information and
arg1, arg2…argn are argument that represents the individual output data items. The
control string consists of individual groups of character, either one-character group for
each output data item. Each character group must begin with a percent sign (%). In its
simplest from, an individual character group will consist of percent sign (%) followed by
a conversion character indicating the type of the corresponding data item.

Conversion character MEANING


c Single character
d Decimal integer, signed, short integer
e Floating point with exponent
f Floating point without exponent
g Floating float is displayed with e-type or f-type
i Single decimal integer
o Octal integer without a leading zero
s String
u Unsigned decimal integer
x Hexadecimal integer

It is also possible to insert number into the control string to control field widths for values
to be displayed. For example %6d would print a decimal value in a field 6 spaces wide,
%8.2f would print a real value in a field 8 spaces wide with room to dhow 2 decimal
places. Display is left justified by default, but can be right justified by putting a – before
the format information, for example %6d, a decimal integer right justified in a 6 space
field.
scanf
scanf allows formatted reading of data from the keyword. Like printf it has a
control string followed by the list of items to be read. However scanf wants to know the
address of the items to be read, since it is a function which will change that value. There
fore the names of variables are preceded by the & sign. Character strings are an exception
to this. Since a string is already a character pointer, we give the names of string variables
unmodified by a leading &.

In general terms, the scanf function is written as


scanf (control string, & arg1, &arg2, &arg3……….&argn)

Control string entries which match values to be read are preceded by the
percentage sign in a similar way to their printf equivalents.

A simple program fro inputting a integer, a float and a character value and to print
them on screen

#include<stdio.h>
Void main( )
{
Int a;
float b;
char c;
printf (“please enter the number”);
scanf(“d”,&a); /* Memory location for variable a*/
scanf(“%f’,&b); /* Memory location for variable b*/
scanf (“%c”,&c); /* Memory location for variable C*/
printf (“the number are “);
printf (“%d %f %c”, a,b,c); */ print the value of a b c respectively
}

Whole Lines of Input and Output

Where we are not too interested in the format of our data, or perhaps we cannot
predict its format in advance, we can read and write whole lines as character strings. This
approach allows us to read in a line of input, and then use various string handling
functions to analyse it at our leisure.

gets
puts
gets
gets reads a whole line of input into a string until a newline or EOF is
encountered. It is critical to ensure that the string is large enough to hold any expected
input lines.

When all input is finished, NULL as defined in stdio.h is returned.


puts

puts writes a string to the output, and follows it with a new line character.

Example: Program which uses gets and pust to double space typed input.

#include <stdio.h>
Main ( )
{ char line [256]; /*Define string sufficiently large to
store a line of input */

While (gets (line) ! = NULL /* Read line */


{ puts (line); /*Print line */
Printf (“\n”); /*print blank line */
}
}

Note that putchar, printf and puts can be freely used together. So can getchar, scanf and
gets.

Special Characters

C makes use of some ‘invisible’ characters which have already been mentioned.
However a fuller description seem appropriate here.

NULL, The Null Pointer or Character


EOF, The End of File Marker

NULL, The Null Pointer or Character

NULL is a character or pointer value. If a pointer, then the pointer variable does
not reference any object (i.e. a pointer to nothing). It is usual for functions which return
pointers to return NULL if they failed in some way. The return value can be tested. See
the section on open for an example of this.

NULL it is used as a character, NULL is commonly written as “\0’. It is the string


termination character which is automatically appended to any string in your C program.
You usually need not bother about this final \0’, since it is handled automatically.
However it sometimes makes a useful target to terminate a string search. There is an
example of this in the string_length function example in the section on Function in C.

EOF, The End Of File Marker


EOF is a Character which indicates the end of a file. It is returned by read commands of
the gets and scanf families when they try to read beyond the end of a file.

A Very Simple Program

This program which will print out the message This is a C program
#include <stdio.h>
Main( )
{
Printf (“This is a C program \ n”);
}
Through the program is very simple, a few pointer are worthy of note.

Every C program contains a function called main. This the screen, keyword and file
system of your computer. You will find it at the beginning of almost every C program.

#include<stdio.h> allows the start function, while the two curly brackets show the
start and finish of the function. Curly brackets in C are used to group statements together
as in a function, or in the body of a loop. Such a grouping is known as a compound
statement or a block.

Printf(“This is a C program\n”); prints the words on the screen. The text to be


printed is enclosed in double quotes. The \n at the end of the text tells the program to
print a new line as part of the output.

Most C program are in lower case letters. You will usually find upper case letters
used in preprocessor definitions (which will be discussed later) or inside quotes as parts
of character strings. C is case sensitive, that is, it recognises a lower case letter and it’s
upper case equivalent as being different.

Constant and variable Types

Variables
Variable Names
Global Variables
External Variables
Static Variables
Constants
Arrays

Variables

In C, a variable must be declared before it can be used. Variables can be declared


at the start of any block of code, but most are found at the start of each function. Most
local variables are created when the function is called, and are destroyed on return from
that function.

A declaration begins with the type, followed by the name of name of one or more
variables. For example,

int high, low, results [20];

Declarations can be spread out, allowing space for an explanatory comment.


Variables can also be initialized when they are declared, this is done by adding an equals
sign and the required value after the declaration.
int high = 250 ; /* Maximum Temperature */
int low = 40; /* Minimum Temperature */
int results [20]; /* Series of temperature readings */
C provides a wide range of types. The most common are

There are also several variants on these types.

All of the integer types plus the char are called the types. Float and double are
called the real types.

Global Variables

Local variable are declared within the body of a function, and can only be used
within that function. This is usually no problem, since when another function is called, all
required data is passed to it as arguments. Alternatively, a variable can be decaled
globally so it is available to all functions. Modern programming practice recommends
against the excessive use of global variables. They can lead to poor program structure,
and tend to clog up the available name space.

A global variable declaration looks normal, but is located outside any of the
program’s functions. This is usually done at the beginning of the program file, but after
preprocessor directives. The variable is not declared again in the body of the functions
which access it.

External Variable

External Variable

Where a global variable is declared in one file, but used by functions from another, then
the variable is called an external variable in these functions, and must be declared as
such. The declaration must be preceded by the word extern. The declaration is required so
the compiler can find the type of the variable without having to search through several
source for the declaration.
Global and external variables can be of any legal type. They can be initialized, but the
initialization takes place when the program starts up, before entry tom the main function.

Static variables

Another class of local variable is the static type. A static can only be accessed
from the function in which it was declared, like a local variable. The static variable is not
destroyed on exit from the function, instead its value is preserved, and become available
again when the function is next called. Static variables are declared as local variable, but
the declaration is preceeded by the word static.

static int counter;

static variable can be initialized as normal, the initialization is performed once


only, when the program starts up.

Constants

A C constant is usually just the written version of a number. For example


1,0,5.73,12.5e9. We can specify our constants in octal or hexadecimal, or force them to
be treated as long integers.

Octal constants are written with a leading zero – 015.


Hexadecimal constants are written with a leading 0x – 0x1ae.
Long constants are written with a trailing L -890L.

Character constants are usually just the character enclosed in single quotes; ‘a’, ‘b’, ‘c’,
Some character can’t be represented in this way, so we use a 2 character sequence.

In addition, a required bit pattern can be specified using its octal equivalent.
‘\044’ produces bit pattern 00100100.

Character constants are rarely used, since string constants are more convenient. A string
constant is surrounded by double quotes eg “Brian and Dennis”. The string is actually
stored as an array of character. The null character “\0’ is automatically placed at the end
of such a string to act as a string terminator.

A character is a different type to a single character string. This is important.

We will meet strings and character again when we deal with the input / output
functions in more detail.

Expressions and Operators


One reason for the power of C is its wide range of useful operators is a function
which is applied to values to give a result. You should be familiar with operators such as
+, -, /,

Arithmetic operators are the most common. Other operators are used for
comparison of values, combination of logical states, and manipulation of individual
binary digits.

Operators and values are combined to from expressions. The values produced by these
expressions can be stored in variables, or used as a part of even larger expressions.

Assignment Statement
Arithmetic operator
Type conversion
Comparison
Logical Connectors
Summary

Arithmetic operators
Here are the most common arithmetic operators:

Operator Purpose
+ addition
- subtraction
* multiplication
/ division
% remainder after integer division

Suppose that A and B are integer variable whose values are 10 and 3
respectively. Several arithmetic expression involving these variable are shown
Expression Values
A+B 13
A-B 7
A*B 30
A/B 3
A%B 1

*, / and % will be performed before + or – in any expression. Brackets can be


used to force a different order of evaluation to this. Where division is performed between
two integers, the result will be an integer, with remainder discarded. Modulo reduction is
only meaningful between integers. If a program is ever required to divide a number by
zero, this will cause an error, usually causing the program to crash.

Relational Operator

There are relational operators in C. They are


Operator meaning
< lass than
<= less than or equal to
> greater than
>= greater than or equal to

Closely associated with relational operator are the following two equality operators

Operator meaning
= equal to
!= not equal to

Suppose that i,j and k are integer variable whose values are 1 2 and 3
respectively, several logical expression involving these variable are shown below
Expression Interpretation Value
I<J TRUE 1
(I+J)>=K TRUE 1
(J+K)>(I+5) FALSE 0
K!=3 FALSE 0
J = =2 TRUE 1

Unary operators

C includes a class of operators that act upon a single operand to produce a new
value. Such operations are known as unary operators. Unary operators usually followed
or proceed their single operands

Name of operator Symbol Use


Unary - Use to negate the number
Increment operator ++ Use to increase the value by 1
Decrement operator -- Use to decrease the value by 1

Increment or decrement operator is further classified as

1. post increment / post decrement : the operator is written after the operator
2. pre increment / pre decrement : the operator is written before the operand In post
increment or decrement the action takes place first and then increment or
decrement take place while in pre increment or decrement first the value get
increase or decrease then action takes place.
For example:
Void main ()
{
Int Y,a=2; //2 will get stored in y then value of A get increase to become 3 printf
(“%d %d”, Y,A); // it will print 2 and 3
Y = ++A; // first A increase to become 4 then 4 will store in Y
printf (“%d %d”, Y, A); // it will print 4 and 4
}

Assignment Statement

The easiest example of an expression is in the assignment statement. An


expression is evaluated, and the result is saved in a variable. A simple example might
look like

Y= (m * x) + c
This assignment will save the value of the expression in variable y.
Here are some arithmetic expression used within assignment statements.
Velocity = distance / time;
Force = mass * acceleration;
Count = count + 1;
C has some operators which allows abbreviation of certain types of arithmetic assignment
statements.

Comparison operator

C has no special type to represent logical or Boolean values. It improvises by


using any of the integral types char, int, short, long, unsigned, with a value of 0
representing false and any other value representing true. It is rare for logical values to be
stored in variables. They are usually generated as required by comparing two numeric
values. This is where the comparison operators are used, they compare two numeric
values and produce a logical result.

Note that = is used in comparisons and = is used in assignments. Comparison


operators are used in expressions like the ones below.

x == y
i > 10
a+b!=c

In the last example, all arithmetic is done before any comparison is made.
These comparison are most frequently used to control an if statement or a for or a
while loop. These will be introduced in a later chapter.

Logical Connectors
These are the usual and, Or and Not operators. (&&,||,!) respectively
They are frequently used to combine relational operators, for example

x < 20 && x >=10


In C these logical connectives employ known as lazy evaluation. They evaluate their left
hand operand, and then only evaluate the right hand one if this is required.
They evaluate their left hand operand, and also evaluate the right hand one compulsory. If
any one of them is true the result it true.

Clearly if false && anything is always false, true || anything is always true. In such cases
the second test is not evaluated.

Not operates on a single logical value, its effect is to reverse its state. Here is an example
of its use.
if ( ! acceptable)
printf (“Not Acceptable ! ! \n”);

IIIustrate Examples:
1, Give the no of 25p, 50p, 1Rs, 2Rs, and 3Rs, and 5Rs, coins in a purse. Calculate the
total no of coins and the total amount of money=.

Solu
#include <stdio.h>
#include <conio.h>
Void main( )
{
int no_25, no_50, no_1, no_2, no_5, tot;
float tot_amt;
cluscr ( );
printf (“Enter no of 25p, 50p, 1Rs, 2Rs, & 5Rs, coins”);
scanf (“%d%d%d%d%d”, &no_25, &n_50, &no_1, &no_2, &no_5);
tot = no+25+no+50+no_1+no_2+no_5;
tot_amt=no_25*0.25+no_50+0.5++00_1*+no_2*2+no_5*5;
printf (“The total no of coins is %d;, tot);
printf (“\n The total amount is %f”, tot_amt);
getch ( );
}

2. enter to three sides of a triangle. Calculate the area using formula.

Area= s (s-a) (s-b) (s-c) where s =a + b + c/2

#include <stdion.h>
#include <conio.h>
Void main ( )
{
int a, b, c;
float area, s;
clrsecr ( );
printf (“Enter three sides of triangle”);
scanf (“%d %d %d”, &a, &b, &c);
S = (a + b+ c) / 2;
area = sqpt (s * (s – a) * (s – b) * ( s- c) );
printf (“The area of triangle is %f;, area);
getch( );
}

3. Enter two numbers and enter change them without using any other variable.

#include <stdio.h>
#include <conio.h>
Void main( )
{
int a, b;
clrscr( );
printf (“Enter two nos”);
scanf (“%d %d”, &a, &b);
printf (“The original nos are %d & %d”, a,b);
a = a+b;
b- =a; a- = b;
printf (“The interchanged values are a = %d, = %b = %d”, a, b);
getch ( );
}

4. Enter the dimensions of a room and the dimensions and cost of a tile. Calculate the
numbers of tiles required to cover the floor and the cost for doing so.
#include <stdio.h>
#include <conio.h>
void main ( )
{
int lr. Br, lt, bt, ar, at;
flaot no_tiles, cost, tot_cost;
clrscr( );
printf (“Enter dimension of the room”);
scanf (“%d %d”, &lt, &bt);
ar = tr * br;
at = lt * bt;
no_tiles = ar / at;
printf (“Enter cost of 1 tile”);
scanf (“%f’, & cost);
tot_ cost = no_tiles * cost;
printf (“The total cost of using %d tiles is %f’, no_tiles, tot_cost);
getch( );
}

5. write a program to enter a two digit integer number. Reverse and display the reversed
no.
#include <stdio.h>
#include <conio.h>
void main( )
{
int number, reverse = 10;
clrscr( );
printf (“Enter a number”);
snacf (“%d”, & number);
reverse = reverse * number %10 + number %10;
printf (“The reversed number is %d”, reverse);;
getch ( );
}

Type conversion

You can mix the types of values in your arithmetic expressions. Char types will
be treated as int. Otherwise where types of different size are involved, the result will
usually be of the larger size, so a float and a double would produce a double result.
Where integer and real types meet, the result will be a double.

There is usually no trouble in assigning a value to a variable of different type. The


value will be preserved as expected except where;

The variable is too small to hold the value. In this case it will be corrupted (this is
bad).
The variable is an integer type and is begin assigned a real value. The value is
rounded down. This is often done deliberately by the programmer.

Values passed as function argument must be of the correct type. The function has
no way of determining the type passed to it, so automatic conversion cannot take place.
This can lead to corrupt results. The solution is to use a method called casting which
temporarily disguises a value as a different type.

eg. The function sqrt finds the square root of a double.


int i = 156;
int root
root = sqrt ( double) )i);

The cast is made by putting the bracketed name of the required type just before
the value. (double) in this example. The result of sqrt (double) i); is also a double, but
this is automatically converted to an int on assignment to root.

Summary

Three types of expression have been introduced here;


Arithmetic expression are simple, but watch out for subtle type conversions. The
shorthand may save you a lot of typing.

Comparison takes two numbers and produces a logical result. Comparisons are
usually found controlling if statements or loops.

Logical connectors allows several comparisons to be combined into a single test.


Lazy evaluation can improve the efficiency of the program by reducing the amount of
calculation required.
Precedence C operators

The following table shows the precedence of operators in C. Where a statement


involves the use of several operators, those operator according to table which encounters
first will be applied first, Parentheses ( 0 always enjoy the highest precedence.
Operator category Operators Associatvity
Unary operators - ++ --! Size of typedef R->L
Arithmetic multiply,divide and remainder */% L-.>R
Arithmetic add and subtract +- L->R
Relational operator <<= >>= L->R
Equality = = != L-> R
Logical and && L->R
Logical or || L->R

Control Statements

A program consist of a statements which are usually executed in sequence.


Programs can be more powerful we can control the order in which statements are run.

Statements fall into three general types.

Assignment, where values, usually the results of calculations, are stored in


variables.
Input / Output, data is read in or printed out.
Control, the program makes a decisions about what to do next.

This section will discuss the use of control statements in C. We will show how they can
be used to write powerful programs by;

Repeating important section of the program.


Selection between optional sections of a program.
The if else Statement
The switch Statement
Loops
The while Loop
The do while Loop
The for Loop
The break Statement
The continue Statement
The goto Statement

The if else Statement

The is used to decide whether to do something at a special point, or to decide


between two course of action.

The following test decides whether a student has passed an exam with a pass mark of 45
if (result >= 45)
printf (“pass \n”);
else
printf (“Fail \n”);

It is possible to use the if part without the else.


Each versions consists of a test, (this is the bracketed statement following the if). If the
test is true then the next statement is obeyed. If is is false then the statement following the
else is obeyed if present. After this, the rest of the program continues as normal.

If we wish to have more than one statement following the if or the else, they
should be grouped together between curly brackets. Such a grouping is called a
compound statement or a block.

if (result >= 45)


{
printf (“ passed \n”);
printf (“Congratulations \n”)
}
else
{
printf (“Failed \n”);
printf (“Good luck in the resits \ n”);
}

Sometimes we wish to make a multi-way decision based on several conditions. The most
general way of doing this is by using the else if variant on the if statement. This works by
cascading several comparisons. As soon as one of these given a true result, the following
statement or block is executed and no further comparisons are performed. In the
following example we are awarding grades depending on the exam result.

if (result >= 75)


printf (“Passed: Grade A \n”);
else if (result >= 60)
printf (“passed” grade B \n”);
else (result >= 45)
printf (“Passed: Grade C\n”);
else
printf (“Failed \n”);

In this example, all comparisons test a single variable called result. In other cases,
each test may involve a different variable or some combination of tests. The same pattern
can be used with more or fewer else ifs, and the final lone else may be left out. It is up to
the programmer to devise the correct structure for each programming problem .

The switch Statement


The is another form of the multi way decision. It is well structured, but only can
only be used in certain cases where;

Only one variable is tested, all branches must depend on the value of that variable.
The variable must be an integral type. (int, long, short or char).

Each possible value of the variable can control a single branch. A final, catch all,
default branch may optionally be used to trap all unspecified cases.

Hopefully an example will clarify things. This is a function which converts an


integer into a vague description. It is useful where we are only concerned in measuring a
quantity when it is quite small.

estimate (number)
int number;
/* Estimate a number as none, one, two, several, many */
{
switch (number) {
case 0 :
printf (“None \n”);
break;
case 1:
printf (“One \n”);
break ;
case2:
printf (“Two \ n”);
break ;
case3:
case4:
case5:
printf (“Several \n”);
break;
default :
printf (“Many \n”);
break ;
}
}

Each interesting case is listed with a corresponding action. The break statement
prevents any further statement from being executed by leaving the switch. Since case 3
and case 4 have no following break, they continue on allowing the same action for
several value of number.

Both if and switch constructs allows the programmer to make a selection from a
number of possible actions.

The other main type of control statement is the loop. Loops allow a statement, or
block of statements, to be repeated. Computers are very good at repeating simple tasks
many times, the loop is C’s way of achieving this.

Loops

C given you a choice of three types of loop, while do while and for.

The while loop keeps repeating an action until an associated test returns false.
This is useful where the programmer does not known in advance how many times the
loop will be traversed.

The do while loops is similar, but the test occurs after the loop. Loops allows a
statement, or block of statements, to be repeated. Computers are very good at repeating
simple tasks many times, the loops is C’s way of achieving this.

Loops

C given you a choice of three types of loop, while, do while and for.

The while loop keeps repeating an action until an associated test returns false.
This is useful where the programmer does not know in advance how many times the loop
will be traversed.

The do while loops is similar, but the test occurs after the loop body is executed.
This ensures that the loop body is run at least once.

The for loop is frequently used, usually where the loop will be traversed a fixed
number of times. It is very flexible, and novice programmers should take case not to
abuse the power it offers.

The while Loop

The while loop repeats a statement until the test at the top proves false.
A simple program to print 10 numbers

void main ()
{
int i=1;
while(i<=10)
{
Printf(“d”,i);
I++;
}
getch( );
}
The while loop is used to look at the value of i one at a time until the value of i is found.
To be 10. Then the loop is exited. While the value of i is less than 10 the i is incremented
and the test is repeated.

As an example, here is a function to return the length of a string. Remember that the
string is represented as an array of character terminated by a null character ‘\0’.

int string_length (char string[])


{
int i = 0;
while (string [i] ! = ‘\0’)
i++;
return(i);
}

The string is passed to the function as an argument. The size of the array is not
specified, the function will work for a string of any size.

The while loop is used to look at the character in the string one at a time until the
null character is found. Then the loop is exited and the index of the null is returned.
While the character isn’t null, the index is incremented and the test is repeated.

The while loop is known as entry control loop, because entry in loop will possible
only if condition is true.

The do while Loop

This is very similar to the while loop except that the test occurs at the end of the
loop body. This guarantees that the loop is executed at least once before continuing. Such
a setup is frequently used where data is to be read. The test then verifies the data, and
loops back to read again if it was unacceptable. It is known as exit control loop
do
{
printf (“Enter 1 for yes, 0 for no:”);
scanf (“%d”, &input_value);
}
while (input_value ! && input_ value ! = 0);
void main()
{
int i=1;
do{
printf(“%d”, i);
i++;
}
while (i<=10);
getch( );
}

The do while loop used is used to look at the value of i one at a until the value of i
is found to be 10. Then the loop is exited. While the the value of I is less than 10 the i is
incremented and the test is repeated. In do while first the loop get executed then the
condition is checked, therefore the loop get executed at least once.

The for Loop

The for loop works well where the number of iterations of the loop is known
before the loop is entered. The head of the loop consists of three parts separated by
semicolons.

The first is run before the loop is entered. This is usually the initialization of the
loop variable.

The second is a test, the loop is exited when this returns false.
The thirds is a statements to be run every time the loop body is completed. This is
usually an increment of the loop counter.

To print the number from 1 to 10 as already discussed in while and do while loop
Lest see that program through for loop

void main ()
{
int i;
for (i<1;i<10;i++)
printf(“%d”,i);
}
getch( 0;
}

In above program the initialization, testing and increment operation has written
simultaneously and therefore for loop is known as compact loop.
The example is a function which calculated the average of the numbers stored in
an array.
The function takes the array and the number of elements as arguments.

float average (float array[], int count)


{
float total = 0. 0;
int I;
for (I = 0; i< count; i++)
total += array [i];
return (total / count);
}

The for loop ensures that the head correct number of array elements are added up
before calculating the average.

The three statements at the head of a for loop usually do just one thing each,
however any of them can be left blank. A blank first or last statement will mean no
initialization or running increment. A blank comparison statement will always be treated
as true. This will cause the loop to run indefinitely unless interrupted by some other
means. This might be a return or a break statement.

In for loop, all the three parameter are optional, we can also left all the parameter
of for loop
for (; ;)
It will acts as infinite loop, since no condition is specified.
In for loop, the initialization takes place only once

It is also possible to squeeze several statements into the first of third position,
separating them with commas. This allows a loop with more than one controlling
variable. The example below illustrates the definition of such a loop, with variables hi
and lo starting at 100 and 0 respectively and converging.

for (hi = 100, 10 = 0; hi >= 10 - -, 10++)

The for loop extremely flexible and allows many types of program behaviour to
be specified simply and quickly.

The break Statement

We have already met break in the discussion of the switch statement. It is used to
exit from a loop or a switch, control passing to the first statement beyond the loop or a
switch.
With loops, break can be used to force an early exit from the loop, or to
implement a loop with a test to exit in the middle of the loop body. A break within a loop
should always be protected within an if statement which provides the test to control the
exit condition.

void main( )
{
int I, num;
while (i<5)
{
scanf (“%”, & num);
i++;
if(i>3)
break;
}
}

In above program as soon as value of I become greater than 3, control read break
statement and throw itself out of while loop.

IIIustrate example

1. Write a program to enter the values of a, b, c in the equation.


ax

#include <stdio.h>
#include <conio.h>
void main ( )
{
int a, b, c, d;
float x1, x2;
clrscr( );
printf (“Enter values of a, b, c”);
scanf(“%d %d %d”, &a, &b &c);
d = b * b – 4 * a * c;
if (d > = 0)
{
x1 = (-b + sqrt (d) ) / (2 * a);
x2 = (-b – sqrt (d) 0 / (2 * a);
printf (“x11 = %f \n x2 = %f’, x1, x2);
}
else
printf (“No solution possible”);
getch( );
}

2. Enter the three sides of a triangle. If the sum of any two sides is greater than the third
side then calculate the area of the triangle else display “such a triangle cannot exist’.

#include <stdio.h>
#include <conio.h>
void main ( )
{
int a, b, c;
float s, area = 0;
clrscr( );
printf (“Enter the three sides”);
scanf (%d %d %d”, &a, &b, &c);
if (a+b >e | | a + c > b | | b + c > a)
{
s = (a + b + c) / 2;
area = sqrt ( s * ( s – a) * (s – b) * (s – c) );
printf (“Area is %f’, area);
}
Else
printf (“such a triangle cannot exist”);
getch ( );
}
3. Write a program to enter no of students in class and no of subs studied by each student
enter marks in subjects studied by the student. Calculate and display list percentage.

#include <stdio.h>
#include <conio.h>
void main( )
{
int no_stu, m no_sub, m1, max_ marks, tot = 0;
flaot perc;
clrscr( );
printf (“Enter no of students”);
scanf (“%d”, & no_ stu);
for (I = 1; i<= no_stu; i++)
{
printf (“%d”, & no_sub);
scanf (%d”, & max_markc);
tot =0;
for (j = 1; j <= no_sub; j++)
{
printf (“Enter marks”);
scanf (%d”, & m1);
tot + = m1;
}
Perc = (float) tot / (max * no_sub) * 100;
Printf (“Percentage of student %d is %f %1”, perc);
}
Getch( );
}

4. Write a program to calculate the expression.

#include <stdio.h>
#include <conio.h>
Void main ( )
{
float x = 0;
Int fact = 1, power = 1, I, j, k;
Clrscr( );
For (I = 1; j=5; i<5 & &j >=1; i++, j- -)
{
Fact = 1; k =1
While (k < = i)
Fact * = k++;
Power = 1; k =1;
While ( k < =i)
{
Power * = j;
k++;
}
X+ = (float) fact / power;
}

5. write a program to calculate the value of expression.

x = n! / r! * (n – r)! where n>r.

#include <stdio.h>
#incldue <conio.h>
Void main ( )
{
int n, r, fact_n = 1, fact_nr = 1, fact_r = 1;
int 1;
clrscr ( );
printf(“Enter value of n, r”);
scanf (“%d %d”, &n, &r”);
i = 1;
while (i <=r)
fact_r * = i++;
i = 1;
do
{
fact_n * = i++;;
}
While (I < = n);
i = 1;
for (i = 1; i < = (n – r) ; i++)
fact_nr * = i;
x = (float) fact_n / ( fact_ r * fact_nr);
printf (“value is 57.1f”, x);
getch( );
}

6. Write a program to display


a
a c
a……d……g
a……e……i…….m

#include <stdio.h>
#include <conio.h>
Void main( )
{
int I, j;
clrscr( );
for (i = 1; i<=4; i++)
{
for (j =97; j < 97 + i * I; j + = i)
printf (“%c”, j);
printf (“\n);
}
Getch( 0;
}

The continue Statement

This is similar to break but is encountered less frequently. It only works within
loops where its effect is to force an immediate jump to loop control statements.

In a while loop, jump to the test statement.

In a while loop, jump to the test statement.

In a for loop, jump to the test, and perform the iteration.


A simple program to accept 5 positive number.
void main( )
{
int num, i=0;
while (i<5)
{
scanf (“%d”, &num);
if (num<0)
continue;
i++;
}
getch();
}

In above program as soon as compiler detect that value of variable num is less
than 0 means num is negative, it jumps to start of loop.

ARRAYS

Defination

An array is a location of variables of the same type. These similar elements could
be all ints, or folat, ar all chars. It is very important that all elements of any given array
must be of same data type.

Array Declaration

Like other variable, needs to be declared so that the compiler will know what kind
of an array and how many large an array we want. An integer type of array will be
declared as int marks [30];

Here int specifies the type of variables and word marks specifies the name of
variable. The [30] tells that how many elements of the type int will be in out array. This
number is often called the dimension of the array. The bracket ([]) tells the compiler that
we are dealing with array.

A char type of array will be declared as


Char name [15];
A float type of array will be declared as
float deci[10];

Accessing Elements of an array


The number in the bracket following array name is known as subscript or index.
Individual array elements are identified by an integer index. In C the index begins at zero
and is always written inside square brackets (known as subscript). Each index has its own
set of square brackets. The first elements of array has index 0, second elements has index
1 and so on. If we have to access third element of array we have to write index as 2 after
array name e.g. marks [2]

Array initialization

Array can be initialized as normal variable in C


Int even [6] = {2,3,6,8,10};
In above statements values are stored as
Even[0]=2
Even[1]=4
Even[2]=6
Even[3]=8
Even[4]=10

Also
int even[]={2,4,6,8,10};
if we are initialization array during declaration then size declaration is optional.

char name []={a,e,i,o,u};


Also
char name [] =” Bhopal”;
group of character in this way is known as string

if we provide the number more than the size of array then program will give error

Storage of array element in memory


int num[5] ={12,24,36,48,60};

We know that each variable consume some space in memory and hence array
num too. Num represent the array and num [0] is the first elements of array, but the
address of num and num [0] is same because from num our array is string and first
elements is num [0]. The representation of array is shown as follows:
If we consider that base address of num is 5000, then
5000 5002 5004 5006 5008
12 24 36 48 60
Num[0] num[1]num[2] num[3]num[4]

Since we specified it as array, but compiler takes


num[0] =(num+0)=(5000+0)
Num[1]=(num+2)=(5000+2) because compiler know that integer occupies 2 bytes
Num[2]=(num+4)= (5000+4)
There fore it is said that an array represent its address own.
Reading and writing data in array

Reading and writing in array is same as normal variable except that we have to
use subscript
e.g.
scanf (“%d”, & marks[1]);
It will read a number from user store in marks array at second position printf (“%d”,
marks[1]);

It will print the value of integer stored in array marks at position 1


Here is a very simple program that read 5 integer numbers from users and print those
numbers
void main ( )
{
int a [6]; //Array declaration
int i;
for (i=0;i<5;i++)
scanf(“%d”, &a[i]);
for (i=0;i<5;i++)
printf(“%d”, a[i]);
getch( );
}
Simple array is known as one dimensional array or single dimensional array

Multidimensional array

Multidimensional arrays are defined in much the same manner as one dimensional arrays,
except that a separate pair of square bracket is required for each subscript. Thus a two
dimensional array will require two pairs of square backets, at three Dimensional array
definition can be written as:
Data type arr[size1] [size]…..[size]
Where size is any integer.

We have already seen that an n elements, one dimensions array can be through of
as a list of values. Similarly a, two dimensional array having size m and n respectively
can be through of As a matrix having m rows and n columns. Extending this idea, a three
dimensional array can be visualized as asset of matrix (in which one matrix is placed over
other)

Two dimensional array

Initializing A 2 Dimensional array


int values[3][4]={
{1,2,3},
{4,5,6},
{7,8,9}
};
values are stored as
values[0][0]=1values[0][1]=2values[0][2]=3
values[1][0]=4values[1][1]=5values[1][2]=6
values[2][0]=7values[2][1]=8values[2][2]=9

Reading and writing data in two dimensional array: Reading and writing int two
D array is same as normal array except that we have to use subscript e.g.
Scanf(“%d”, & values[1][2]);

It will read a number from user and store in values array at second row and third column
printf (“%d”, values[1][1]);

It will print the value of integer stored in array values at second row second
column
Here is a vary simple program that read 25 integer numbers from users and print
those numbers

void main( )
{
int a[6][6]; // 2D Array declaration
int I,j;
forii=0;i<5;i++)
{
for(j=0;j<5;j++)
scanf (“%d”, &a[i][j]);
}
for(i=0;i<5;i++)
{
for ( j=0;j<5;j++)
printf(“%d”,a[i][j]);
}
getch( );
}

We can any that a 2 D array is an array of array


The declaration

int nav[2] [3]={12,24,36,40};


int nav[][3]={12,24,36,40};
is also valid but
int nav[2][]={12,24,36,40};
int nav[][]={12,24,36,40}; are totally wrong

Three Dimensional array


A three dimensional (3 D) array is same as 2 D array except that three bracket is
used instead of two bracket.

int t[2][3][4]={
{
{1,2,3,4},
{5,6,7,8},
{9,10,11,12}
}
{
{21,22,23,24},
{25,26,27,28},
{29,30,31,32}
}
};

t[0][0][0]=1 t[0][0][1]=2 t[0][0][2]=3 t[0][0][3]=4


t[0][1][0]=5 t[0][1][1]=6 t[0][1][2]=7 t[0][1][3]=8
t[0][2][0]=9 t[0][2][1]=10 t[0][2][2]=11 t[0][2][3]=12

t[1][0][0]=12 t[1][0][1]=22 t[1][0][2]=23 t[1][0][3]=24


t[1][1][0]=25 t[1][1][1]=26 t[1][1][2]=27 t[1][0][3]=28
t[1][2][0]=29 t[1][2][1]=30 t[1][2][2]=31 t[1][2][3]=32

IIIustrate example:

1. Write a program to enter 15 elements into an integer array. Find the sum of all the even
and old elements in the array.

#include<stdio.h>
#include<conio.h>
void main( )
{
int a [15], sum_even=0, sum_odd=0,I;
clrscr( );
for (i=0; I < 15; i++)
{
printf (“Enter element”);
scanf(%d”, &a [i]);
}
for(i=; i < 15; i++)
{
if(a[i] %2= =0)
sum_odd f=a[i];
else
sum_odd f =a[i];
}
printf(“\n The sum of even nos is %d”, sum_even);
printf(“\n The sum of odd nos is %d”, sum_odd);
getch ( 0;
}

2. Enter nos into a 15 element integer array. Identify the max and min no in the array and
identify the position as well.

#include <stdio.h>
#include <conio.h>
void main( )
{
int a[15];
clrscr( );
int max, min, i, index_max=0, index_min=0;
clrscr( );
for (i=d; i<15; i++)
{
printf(“Enter element”);
scanf(“%d”, & a[i]);
}
max = a [0]; min=a[0]; index_max=0; index+min=0;
for (i=1; i<15; i++)
{
if 9a [a] >max)
{
Index+max=i;
}
else
if (s[i] <min)
{
index_min=i;
index =a [i];
}
}
printf (max element %d at pos %d”, max, index_max);
printf (“min element %d at pos %d”, min, index_min);
getch( );
}

3. Write a program to display the column wise sum of a 2D array of size5*4

#include <stdio.h>
#include <conio.h>
void main( )
{
int a [5] [4], I, j;
int sum = 0;
for (i=0; I <5; i++)
{
for(j = 0; j <4; j++)
{
printf (“Enter element”);
scanf (“%d”, &a [i] [j]);
}
}
for (i=0; i<4; i++) //for each column
{
sum=0;
for(j=0; j<5;j++)
sum + = a [j][i];
printf (“The sum of column %d is %d”, I, sum);
}
getch( );
}

4. Write a program to execute bubble sorting on an integer array of `5 elements.

#include <stdio.h>
#include <conio.h>
void main( )
{
int a[5];
int i, j, temp;
clrscr( );
printf(“Enter elements in an array”);
for (i=0; i<15; i++)
{
printf (“Enter element”);
scanf (“%d”, &a [i]);
}
for (i=0;i<14;i++)
{
for(j=0;j<14=I;j++)
{
if(a[j]<a[j+1]
{
temp = a [j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf (“\n The sorted list is:”);
for (i=0; i<15; i++)
printf(“%d \n”, a[i]);
getch( );
}

5. Write a program to enter 10 elements into an integer array. Search and find whether an
element exists in the array or not.

#include <stdio.h>
#include <conio.h>
void main( )
{
int a[10], no, I;
char flag = ‘f’;
for (i=0; i,10;i++)
{
printf (“Enter element”);
scanf(“%d”, &a [i]);
}
printf (“Enter element to be searched”);
scanf (“%d”, & no);
for (i=0; i<10; i++)
{
if(a[i] = = ‘f’);
printf (“Element not in list”);
getch( );
}

6. Write a program to reverse a list of 15 element.

#include <stdio.h>
#include <conio.h>
void main( )
{
int a [15], temp, i, 1;
clrscr( );
printf(“Enter elements into array \n”);
for (i=0; i<15;i+++
{
printf (“Enter element”);
scanf (“%d”, & a [i]);
}
1 =15 / 2;
for (i=0;<=1;i++)
{
temp =a [i];
a[i] =a[14 – i];
a[14 – i] = temp;
}
printf(“\n The reversed llist in \n”);
for(i=0;i<15.i++)
printf(“%d \n”, a[i]);
getch( );
}

String handling in C

What are string

A group of character can be stored in a character array. Character arrays are many
a times also called strings. Character arrays or string are used by programmer language to
manipulate text such as words and sentences.

A string constant is a one dimensional array of characters terminated by a null


(“\0’). For example

char name [] = {‘H’, ‘A’, ‘E’, ‘S’, ‘L’, ‘E’, ‘R’, ‘\0’);

Each character in the array occupies one byte of memory and the last character is
always ‘\0’. What character is this? It looks like two characters, but it is actually only one
character, with the \ indicating that what follows it is something special. ‘\0’ is called null
character. Note that ‘\0’ and ‘0’ are not same. Ascii value of ‘0\’ is 0, whereas ascii value
of ‘0’ is 48. Figure show the way a character array is stored in memory. Note that the
elements of the character array are stored in contiguous memory locations.

The terminating null (\0’) is important, because it is the only way the functions
that work with a string can know where the string ends. In fact, a string not terminated
by a ‘\0’ is not really a string, but merely a collection of characters.

H A E S L E R \0

4001 4002 4003 4004 4005 4006 4007 4008

For example. The string used above can also be initialised as,
Char name[ ] = “HAESLER”;

C inserts the null character automatically.

More about string

Following program illustrates this.

Main( )
{
Char name [ ] = “Klinsman”;
Int i=0;
While (name[i]! = ‘\0’
{
Printf(“%C”, name [i]);
}
}

And here is the output..


Klisman
This program doesn’t rely on the length of the string (number of characters in it)
to print out its contents and hence is definitely more general.
Main
{
Char name[ ] =Klisman”;
Printf(“%s”, name);
}

The % used in printf( ) is a format specification for printing out a string. The same
specification can be used to receive a string from the keyboard, as shown below.

Main ( )
{
Char name[25];
Printf(“Enter your name”);
Scanf(“%s”, name);
Printf (“Hello %s!”, name);
}
And here is a sample run of the program

Enter your name Debashis


Hello Debashis!

Note that the declaration char name [25] sets aside 25 bytes under the array name[
], whereas the scanf ( ) function fills in the characters types at Keyboard into this array
until the enter key is hit. Once enter is hit, scanf ( ) places a ‘\0’ in the array. Naturally,
we should pass the base address of the array to the scanf( ) function.

While entering the string using scanf ( ) we must be cautious about two things:

(a) The length of the string should not exceed the dimension of the character array.
This is because the C compiler doesn’t perform bounds checking on character
arrays. Hence, if you carelessly exceed the bound there is always a danger of
overwriting something important, and in that event you would have nobody to
blame but yourselves.
(b) Scanf ( ) is not capable of receiving multi-word string. Therefore names such as
‘Debashish Roy’ would be unacceptable. The way to get around this limitation is
by using the function gets( ). The usage of function gets ( ) and its counterpart
puts( ) is shown below.

main( )
{
Char name [25];
Printf (“Enter your full name”);
Gets (name);
Puts(“Hello!”);
Puts (name);
}

And here is the output …


Enter your Debashish Roy
Hello!
Debashish Roy

The program and the output are self – explanatory except for the fact that, puts( )
can display only one string at a time (hence the use of two puts () in the program above).
Also, on displaying a string, unlike printf( ), puts( 0 paces the cursor on the next line.
Through gets( ) is capable of receiving only one string at a time, the plus point with
gets( ) is it can receive a multiword string.

Standard Library string Functions

With every C compiler a large set of useful string handling library functions are
provided.
The following figure lists the more commonly used functions along with their purpose.

Function Use
Function Use
strlen Finds length of a string
strlwr Converts a string to lowercase
strupr Converts a string to uppercase
strcat Appends one string at the end of another
strncat Appends first n characters of a string at the end of another
strcpy Copies first n character of one string into another
strcmp Compares two strings
strncmp Compares first n characters of two strings
strcmpi Compares two strings without regard to case (“i”) denotes that this
function ignores case)
stricmp Compares two strings without regard to case(identical to strcmpi)
strnicmp Compares first n characters of two strings without regard to case.
strdup Duplicates a string
strchr Finds first occurrence of a given character in a string
strrchr Finds last occurrence of a given character in a string
strstr Finds first occurrence of a given string in another string
strnset Sets all character of string to a given character
strnset Sets first n characters of a string to a given character
strrev Reverses string

strlen ( )
This function counts the number of characters present in a string. Its usage is
illustrated in the flowing program.
main ( 0
{
char arr[ ] = “Bamboozled”;
int len1, len2;
len1 = ltrlen (arr);
len2 = strlen (“Hu,pty dumpty”);
printf (“\nstring = %s length = %d”, arr, len1);
printf (“\nstring = %s length \ %d”, Humpy Dumpy”, len2);
}

The output would be…

String = Bamboozled length = 10


String = Humpty Dumpty length = 13

Note that in the call to the function strlen( ), we are passing the base address of the
function in turn returns the length of the string. While calculating the
length it doesn’t count ‘\0’. Even in the second call,

Len2 = strlen (“Humpty Dumpty”);

What gets passed to strlen( ) is the address of the string and not be string it self.
strcpy ( )

This function copies the contents of one string into another. The base
addresses of the source and target strings should be supplied to this function. Here is an
example of strcpy ( ) in action..

Main ( )
{
Char source [ ] = “Sayonara”;
Char taget[20];
Strcpy (target, source);
Printf(“\nsource string = %s”, source);
Printf (“\ntarget string = %s”, target);
}
And here is the output…
Source string = Sayonara
Target string = Sayonara

On supplying the base addresses, strcpy( ) goes on copying the characters in


source string into the target string till it doesn’t encounter the end of source string (‘\0’).
It is our responsibility to see to it that the target string’s dimension is big enough to hold
the string being copied into it. Thus, a string hets copied into another, piecemeal,
character by character.

strcat( )

This function concatenates the source string at the end of the tiger string. For
example, “Bombay” and “Nagpur” on concatenation would result into a string “Bombat
Nagpur”. Here is an example of strcat( ) at work.

main( )
{
char source [ ] = “Folks!”;
char target[30] = “Hello”;
strcat (target, source);
printf (“\nsource string = %s, source);
printf(\%nsource string = %s”, target);
}

And here is the output..

source string = Falks!


target string = Hello Folks!

Note that the target string has been made big ebough to hold the final string.
strcmp( )

This is a function which compares two strings to find out whether they are same
or different. The two strings are compared character by character until there is a
mismatch or end of one of the strings is reached, whichever occurs first. If the two strings
are identical, strcmp( ) returns a value zero. If they’re not, it returns the numeric
difference between the ascii values of the non-matching characters. Here is a program
which puts strcmp( ) in action.

main( )
{
char string1[] = “Jerry”;
char string2[] = “Ferry”;
int I, j, k;
i = strcmp (string1, “Jerry”);
j = strcmp (string1, string2);
k = strcmp (string1, “Jerry boy”);
printf (“\n%d%d%d”, i,j,k);
}

And here is the output..

04 – 32
In the first call to strcmp( ),the two strings are identical – “Jerry” and “Jerry” –
and the value returned by strcmp( ) is zero. In the second call, the first character of
“Jerry” doesn’t match with the first character of “Ferry” and the result is 4, which is the
numeric difference between ascii value of “J” and ascci value of “F”. In the third call to
strcmp( ) “Jerry” doesn’t match with “Jerry boy”, because the null character at the end of
“Jerry” doesn’t match the blank in “Jerry boy” the value returned is – 32, which is the
value of null character minus the ascii value of space i. e. ‘\0’ minus ‘ ‘, which is equal to
= 32.

The exact value of mismatch will rarely concern us. All we usually want to know
is whether or not the first string is alphabetically above the second string. If it is, a
positive value is returned; if it isn’t, negative is returned. Any non-zero value means there
is a mismatch.

IIIustrative Examples:

1. Write a program to enter a string Reverse the name and check whether ti palindrome.

#include <stdio.h>
#include <conio.h>
void main( )
{
char name[100], name [100];
int i = 0, 1;
clrscr ( );
printf (Enter the string”);
gets(name);
1 = strlen(name) ;
while (i<1)
{
name 1 [i] = name [1=i];
i++;
}
if (strcmp (name1, name) = =0)
printf (“name is a palindrome”);
else
printf(“Not a palindrome”);
getch( );
}

2. Input you and surname into a single char array. Display the interals.

#include <stdio.h>
#include <conio.h>
void main( 0
{
char name [100];
int i = 0;
clrscr( );
printf(“Enter the name”);
gets(name):
printf(%c”, name[0]);
while (name[i++]! = ‘’);
printf(%c”, name[i]);
getch( );
}

3. Write a program to enter name of students in a class of 60. Arrange the names in
alphabetically descending order.

#include <stdio.h>
#include <conio.h>
#include <string.h>
void main( )
{
char names [60] [20];
char temp[20];
clrscr( );
printf(“Enter names \n);
for (i=0; i < 60; i++)
gets (names [i]);
for (i = 0; i <59; i++)
{
for (j=0; j <59 – i; j++ )
{
if (strcmp (name[j], names[j+1]) ,0)
{
strcmp(name[j], names[j+1]) <0)
strcmp(names[j], names[j+1]);
strcpy (names[j+1}, temp);
}
}
}
printf(“sorted list is \n”);
for (i=0; i<60; i++)
printf(“%s \n”, names [i]);
getch( );
}

4. write a program to concatenate two strings into a third string without usingstrcat
function.

#incldue <stdio.h>
#include <conio.h>
void main( )
{
char a [10], b[10], c[20];
clrscr( );
printf(“Enter the two strings”);
gets (a);
gets (b);
i = 0; j = 0;
while (a [j] ! = ‘\0’)
c[i++] = a [j++];
j = 0;
while (b[j]! = ‘\0’)
printf(“The concatenate string %s”, i);
getch( );
}

4. Write a program to compare two char array without regard to case.

#include <stdio.h>
#include <conio.h>
void mian( )
{
char a [10], b[10], c[20];
clsrscr( );
printf(“Enter the two strings”);
gets(a);
gets(b);
i=0; j=0;
while (a[j]! = ‘\0’)
c[i++] =a[j++];
j = 0;
while (b[j]! = ‘\0’)
printf(“The concatenate string $s”, i);
getch( 0;
}

5. Write a program to compare two char array without regard to case.

#include <stdio.h>
#include <conio.h>
void main( 0
{
char name [10], name1[10];
int i = 0;
char flag = ‘f’;
clrscr( );
printf(“Enter the two strings”);
gets (name);
gets (name);
i = 0; j = 0;
while (name[i]! =’\0’ & & name1[i]! = ‘\0’
{
if (tolower (name[i]= =tolower(name1[i]) )
{
i++;
flag = ‘t’;
}
else
if (tolower(name[i]) <tolower(name1[i]) )
{
printf (“First string is smaller”);
break;
}
else
{
printf (“First string is larger”);
flag =’f’;
break;
}
}
if (flag = = ‘t’ & & name [i] = = ‘\0’ & & name1 [i] = ‘\0’)
printf (“First string is smaller”);
else if(“flag = = ‘t’ & 7 name [i] ! \ ‘\0’ & & name1 [i] == ‘\0’)
printf (“first string is bigger”);
else if(“flag= = ‘t’ & & name[i] = =’\0’ & & name1 [i] = = ‘\0’)
printf (“both are equal”);
getch( );
}

Two Dimensional Array of Characters

In the last chapter we saw several examples of 2-dimensional integer arrays. Let’s
now look at a similar entity, but one dealing with characters.

This can be done as.

char masterlist [6][10] = {


“akshay”,
“parag’,
“ranam”,
“srinivas”.
“gopal”,
“rajesh”
};

Notice how the two dimensional; character array has been initialised. The order of
the subscripts in the array declaration is important. The first subscript gives the number
of names in the array, while the second subscript gives the length of each item in the
array.

Instead of initialising names, had these names been supplied from the keyboard,
the program segment would have looked like this…
for (i=0;i<=5;i++)

scanf(“%s”, & masterlist[i][0];

Das könnte Ihnen auch gefallen