Loops
The versatility of the computer lies in its ability to perform a set of
instructions repeatedly. This involves repeating some portion of
the program either a specified number of times or until a particular
condition is being satisfied. This repetitive operation is done
through a loop control instruction.
There are three methods by way of which we can repeat a part of a
program. They are:
(a) Using a for statement
(b) Using a while statement
(c) Using a do-while statement
The while Loop
It is often the case in programming that you want to do something
a fixed number of times.The while loop is ideally suited for such cases.
The general form of while is as shown below:
initialise loop counter ;
while ( test loop counter using a condition )
{
do this ;
and this ;
increment loop counter ;
}
here is example:-
int i = 1 ;
while ( i <= 10 )
{
printf ("%d\n", i ) ;
i = i + 1 ;
}
The for Loop
The for allows us to specify three things about a loop in a single line:
(a) Setting a loop counter to an initial value.
(b) Testing the loop counter to determine whether its value has
reached the number of repetitions desired.
(c)Increasing the value of loop counter each time the program
segment within the loop has been executed.
The general form of for statement is as under:
for ( initialise counter ; test counter ; increment counter )
{
do this ;
and this ;
and this ;
}
The do-while Loop
The do-while loop looks like this:
do
{
this ;
and this ;
and this ;
and this ;
} while ( this condition is true ) ;
This means that do-while would execute its statements at least
once, even if the condition fails for the first time. The while, on
the other hand will not execute its statements if the condition fails
for the first time. do while test condition at the end whereas
while test condition at the start.
Multiple Initialisations in the for Loop
The initialisation expression of the for loop can contain more than
one statement separated by a comma.
For example,
for ( i = 1, j = 2 ; j <= 10 ; j++ )
Multiple statements can also be used in the incrementation
expression of for loop.However, only one expression is allowed
in the test expression.
Nesting of Loops
The way if statements can be nested, similarly whiles and fors can
also be nested.
The Odd Loop
/* Execution of a loop an unknown number of times */
main( )
{
char another ;
int num ;
do
{
printf ( "Enter a number " ) ;
scanf ( "%d", &num ) ;
printf ( "square of %d is %d", num, num * num ) ;
printf ( "\nWant to enter another number y/n " ) ;
scanf ( " %c", &another ) ;
} while ( another == 'y' ) ;
}
/* odd loop using a for loop */
main( )
{
char another = 'y' ;
int num ;
for ( ; another == 'y' ; )
{
printf ( "Enter a number " ) ;
scanf ( "%d", &num ) ;
printf ( "square of %d is %d", num, num * num ) ;
printf ( "\nWant to enter another number y/n " ) ;
scanf ( " %c", &another ) ;
}
}
/* odd loop using a while loop */
main( )
{
char another = 'y' ;
int num ;
while ( another == 'y' )
{
printf ( "Enter a number " ) ;
scanf ( "%d", &num ) ;
printf ( "square of %d is %d", num, num * num ) ;
printf ( "\nWant to enter another number y/n " ) ;
scanf ( " %c", &another ) ;
}
}
The break Statement
When break is encountered inside any loop, control automatically passes to the
first statement after the loop. A break is usually associated with an
if.
The keyword break, breaks the control only from the while in
which it is placed.
The continue Statement
When continue is encountered inside any loop,
control automatically passes to the beginning of the loop.
A continue is usually associated with an if.
Decisions Using switch
The control statement that allows us to make a decision from the
number of choices is called a switch, or more correctly a switch-
case-default, since these three keywords go together to make up
the control statement. They most often appear as follows:
switch ( integer expression )
{
case constant 1 :
do this ;
case constant 2 :
do this ;
case constant 3 :
do this ;
default :
do this ;
}
The integer expression following the keyword switch is any C
expression that will yield an integer value. It could be an integer
constant like 1, 2 or 3, or an expression that evaluates to an
integer. The keyword case is followed by an integer or a character
constant. Each constant in each case must be different from all the
others. The “do this” lines in the above form of switch represent
any valid C statement.
What happens when we run a program containing a switch? First,
the integer expression following the keyword switch is evaluated.
The value it gives is then matched, one by one, against the
constant values that follow the case statements. When a match is
found, the program executes the statements following that case,
and all subsequent case and default statements as well. If no
match is found with any of the case statements, only the
statements following the default are executed.
The goto Keyword
the general form of goto is:
goto label;
label:
Avoid goto keyword! They make a C programmer’s life miserable.
There is seldom a legitimate reason for using goto, and its use is
one of the reasons that programs become unreliable, unreadable,
and hard to debug. And yet many programmers find goto
seductive.
In a difficult programming situation it seems so easy to use a goto
to take the control where you want. However, almost always, there
is a more elegant way of writing the same program using if, for,
while and switch. These constructs are far more logical and easy
to understand.
Function
A function is a self-contained block of statements that perform a
coherent task of some kind. Every C program can be thought of as
a collection of these functions.
the general form of the function is
return-type function_name(type varname1,type varname2,..............,type varnameN)
{
body of the function
}
return type specifies the type of data that the function returns.
example of return type are int,float,double,void,char
Note on return type:-
if you specified void
then function return nothing.
if you specified int
then function return integer value
if you specified float
then function return float value
if you specified char
then function return char value
and so on like this.
that which specified it return that value.
Passing Values between Functions
/* Sending and receiving values between functions */
main( )
{
int a, b, c, sum ;
printf ( "\nEnter any three numbers " ) ;
scanf ( "%d %d %d", &a, &b, &c ) ;
sum = calsum ( a, b, c ) ;
printf ( "\nSum = %d", sum ) ;
}
calsum ( x, y, z )
int x, y, z ;
{
int d ;
d = x + y + z ;
return ( d ) ;
}
And here is the output...
Enter any three numbers 1 2 3
Sum = 6
the values of a, b and c are passed on to the function calsum( ),
by making a call to the function calsum( ) and mentioning a, b and c
in the parentheses:
sum = calsum ( a, b, c ) ;
In the calsum( ) function these values get collected in three
variables x, y and z:
calsum ( x, y, z )
int x, y, z ;
The variables a, b and c are called ‘actual arguments’,
whereas the variables x, y and z are called ‘formal
arguments’. Any number of arguments can be passed to a
function being called. However, the type, order and number of
the actual and formal arguments must always be same.
There are two methods of declaring the formal arguments.
The one that we have used in our program is known as
Kernighan and Ritchie (or just K & R) method.
calsum ( x, y, z )
int x, y, z ;
Another method is,
calsum ( int x, int y, int z )
This method is called ANSI method and is more commonly
used these days.
Return statement
The return statement serves two purposes:
(1) On executing the return statement it immediately
transfers the control back to the calling program.
(2) It returns the value present in the parentheses after
return, to th3e calling program. In the above program
the value of sum of three numbers is being returned.
There is no restriction on the number of return statements
that may be present in a function. Also, the return statement
need not always be present at the end of the called function.
The following program illustrates these facts.
fun( )
{
char ch ;
printf ( "\nEnter any alphabet " ) ;
scanf ( "%c", &ch ) ;
if ( ch >= 65 && ch <= 90 )
return ( ch ) ;
else
return ( ch + 32 ) ;
}
In this function different return statements will be executed
depending on whether ch is capital or not.
Whenever the control returns from a function some value is
definitely returned. If a meaningful value is returned then it
should be accepted in the calling program by equating the
called function to some variable. For example,
sum = calsum ( a, b, c ) ;
All the following are valid return statements.
return ( a ) ;
return ( 23 ) ;
return ( 12.34 ) ;
return ;
Scope Rule of Functions
by default the scope of a variable is local to the
function in which it is defined.
Arrays
Array is a collection of same type elements under the same variable identifier referenced by index number. Arrays are widely used within programming for different purposes such as sorting, searching and etc. Arrays allow you to store a group of data of a single type. Arrays are efficient and useful for performing operations . You can use them to store a set of high scores in a video game, a 2 dimensional map layout, or store the coordinates of a multi-dimensional matrix for linear algebra calculations.
Arrays are of two types single dimension array and multi-dimension array. Each of these array type can be of either static array or dynamic array. Static arrays have their sizes declared from the start and the size cannot be changed after declaration. Dynamic arrays that allow you to dynamically change their size at runtime, but they require more advanced techniques such as pointers and memory allocation.
It helps to visualize an array as a spreadsheet. A single dimension array is represented be a single column, whereas a multiple dimensional array would span out n columns by n rows.
single dimensional array
Arrays can be declared using any of the data types available in C. Array size must be declared using constant value before initialization. A single dimensional array will be useful for simple grouping of data that is relatively small in size
datatype array_name
[size_of_array
]; .
example are
int x[4];
float z[5];
char c[6];
Note: In C language the end of string is marked by the null character '\0'. Hence to store a group of 3 possible string data. the array as char ch[4]; This applies for char type array.
ch[0]=s;
ch[1]=t;
ch[2]=d;
ch[3]='\0';
Array can be initialized in two ways, initializing on declaration or initialized by assignment.
initializing on declaration
If you know the values you want in the array at declaration time, you can initialize an array as follows:
datatype array_name[size]={element1,element2,....,elementN};
initialized by assignment
ch[0]=s;
ch[1]=t;
ch[2]=d;
ch[3]='\0';
Multidimensional arrays
Arrays can have more than one dimension. Two dimensional arrays are widely used for tables, neural networks and etc. You can have as many dimensions as you would like but you have to consider the complexity of the code as you add new dimension. Multidimensional arrays allow you to store data in a spreadsheet or matrix like format.
To declare a multidimensional array:
datatype array_name
[size_of_first_dimension
][size_of_second_dimension
] ...
example
int i[3][3];
To access elements in a multidimensional array, all you have to do is provide a combination of index values for each dimension to reach the desired element, just like a bunch of cells in a spreadsheet or coordinates in a n dimensional matrix or graph.
array_name
[index1]
[index2]
...
[
indexM]
;
Setting values in a multidimensional array is just as simple as in a basic array, you need to add another index per dimension.
array_name
[index1]
[index2]
...
[
indexM]
= value;
example
i[0][1]=43;
An Introduction to Pointers
A Pointer is a variable that holds memory address
.this address is the location of another object.
Pointer Operators:-
there are two special operator * and &.
The
unary or
monadic operator
& gives the ``address of a variable''.
The
indirection or dereference operator
* gives the ``contents of an
object
pointed to by a pointer''.
Declaration
Datatype *variable_name;
example
int *i,**j
here i is pointer to integer.j is pointer to pointer to integer.j is double pointer.
float *i;
here i is pointer to float;
consider statement
int *ptr,*p,a=56;
as you see in figure the value of a is stored at memory address 5000.
to access its address value.
ptr=&a;
ptr hold the memory address of a.
printf("%d",ptr);
it will print 5000
printf("%d",*ptr);
it will print 56
pointer can be assign to another pointer
p=ptr;
pointer arithmetic
We can basically add and subtract pointer variables.
If p1 and p2 are pointers to same data type then
p1- p2, p1+p2 , p1++ , p2-- , --p1 , p1+3 (multiplication, division not allowed)
p1<=p2, p1==p2 etc (and other relational operations)
assume integer are two bytes long.
ptr++;
it wll point to next integer.
similarly
ptr--;
it wll point to previos integer.
ptr=ptr+5;
it will point to 5th element of ptr.
to assign annother value to a structure through ptr
we use arrow operator.(<-)
ptr->a=57;
printf("%d",*ptr);
it will print 57
Structure
This program demonstrates two fundamental aspects of structures:
(a) declaration of a structure
(b) accessing of structure elements
The general form of a structure declaration statement is
given below:
struct <structure name>
{
structure element 1 ;
structure element 2 ;
structure element 3 ;
......
......
} ;
Once the new structure data type has been defined one or more
variables can be declared to be of that type. For example the
struct book
{
char name ;
float price ;
int pages ;
} ;
struct book b1, b2, *b3 ;
struct book
{
char name ;
float price ;
int pages ;
} b1, b2, *b3 ;
or even...
struct
{
char name ;
float price ;
int pages ;
} b1, b2, *b3 ;
struct book b1 = { "x", 13 } ;
struct book b2 = { "x", 31 } ;
Accessing Structure Elements
They use a dot (.) operator. So to refer to pages
of the structure defined in our sample program
we have to use,
b1.pages
b3=&b1;
b3->name="xx";
b3 a pointer to a structure
C provides an operator ->, called an arrow operator
to refer to the structure elements.
printf ( "\n%s ", b3->name) ;
WAP TO FIND LARGEST AND SECOND LARGEST AMONG N NUMBER.
#include<stdio.h>
#define SIZE 100
int main(void)
{
int a[SIZE];
int i,j,n;
printf("\nHOW MANY ELEMENTS TO BE ENTERED IN AN ARRAY : \n");
scanf("%d", &n);
printf("\nENTER THE ELEMENTS IN AN ARRAY : \n");
for(i = 0; i < n; i++)
{
scanf("\n%d",&a[i]);
}
printf("\nTHE GIVEN ARRAY IS : ");
for(i = 0; i < n; i++)
{
display(a[i]);
}
large(a, n);
}
display(int f)
{
printf("\n\n%d", f);
}
large(int w[], int x)
{
int i,j;
for(i = 0 ; i < x ; i++)
{
if(w[i] < w[i+1])
{
j = i+1;
}
}
printf("\n\nTHE LARGEST VALUE IN ARRAY IS\n%s%d", " ", w[j]);
printf("\n\nTHE SECOND LARGEST VALUE IN ARRAY IS\n%s%d", " ", w[j]);
}