Wednesday, October 27, 2010

Basic structure of c- programmme



Basic structure of c- programmme



Basic structure of c- programmme

Documentation section(comment section)
Link section
Define section
Global declaration section
Main( ) ------- main function section
{

Declaration part
Executable part
}

Sub program section
Function 1
Function 2
Function 3 [ user defined functions]
--- ---- ----- ----
--- -------- -----
Function n

C program can be viewed as a group of building blocks called functions. A function is a sub routine that may include one or more statements designed to perform a specific task. To write a C program first creates function and then put them together .C program may contain one or more sections.

Documentation section :
Documentation section consists of a set of comment lines giving the name of the program, author, date and other details.

Line section :
Line section provides the instructions to the compiler to link functions from the system library.
Definition section:
Defines all symbolic constants.

Global declaration section:
There are some variables that are used in more than one function such variables are called global variables and are declared in global declaration i.e., outside of all the functions. The variables which is defined in function is called local variable(private variable).

Main function:
Declaration part
Executable part (input, arithmetic, output, control statements etc)

Sub program section :
This section contains all the user defined functions that are called in the main function. User defined functions are generally placed immediately after the main function although they may appear in any order.

Rules ;

1) each and every instruction in a C program is written in a separate statement, A complete C programme comprises a series of statement. The statements must appear in same order in which we wish them to be executed.
2) Usually all statements are entered in small case letters.
3) C has no specific rules for the position at which the statement is to be written that’s why it is often called free form language.
4) Every statement should always end with a semi colon.

Relational operators : 21/9/07
Symbol Associativity Description
> Left to right Is greater than
>= Left to right Is greater than or equal
< Left to right Is less than
<= Left to right Is less than or equal
== Is equal to
!= or <> Not equal

Note : the value of a relational expression is either non-zero
value (1) or zero value.
It is one if the specified relation is true and zero if specified relation is false.

Logical operators :

Symbol Associativity Description
&& Left to right Expressions must be satisfied
|| Left to right Any one of expression must be satisfied.
! (exclamatory) Right to left These operators reverse the value of an expression. It makes true expression as false and false expression as true.




Truth table :

Op-1 Op-2 Value of the
op1&&op2 Value of the
op1 || op2
Non-zero Non-zero Non-zero Non-zero
Non-zero zero zero Non-zero
Zero Non-zero zero Non-zero
Zero zero zero Zero


Note :
Like simple relational expressions, A logical expressions yields a value of one or zero.

6) Bit wise operators :
‘C’ as a distinction of supporting a special operator
known as operators. For manipulation of data at bit-level. These operators are used for testing the bits or shifting them from right to left.
Note: Bit wise operators maynot be applied to float or double.

Operator Meaning
&(amposand) Bitwise and
|(pipe) Bitwise or
^(carot) Bitwise exclusive or
<< Shift left
>> Shift right
Special operators :

Special operators are comma(,) operator,size of ( ) operator.
Syntax: sizeof (datatype);
Pointer operators are & and * and
Member selection operators -> and .
Example of comma operator :
X=(a-5,b=6,a+b);

Note : ANSI commity has introduce two pre processor operators string as “string zing” and “token pasting”
The operators are # and ## .

Control structures in C :-

Decision control structure or Bi directional conditional structures :-
There are three types of IF statements
1) simple if (simple conditional statements)
2) multiple if or if ladder (multiple conditional statements)
3) nested if (nested conditional statements)
C uses the keyword ‘IF’ to implement the decision control instruction the keyword if tells the compiler that what follows is the decision control instruction.
The condition following the keyword is always enclosed with a pair of parenthesis . if the condition is true the statement is executed and if the condition is false then the statement is not executed instead the program skips.

I syntax :-
If ()
{
Statements ;
}
Statements x;
Or
If ()
Statements ;
II syntax :
If ()
Statements ;
Else
Statements;
Statements x;
III syntax :
If()
{
Statements ;
}
Else
{
Statements ;
}
Statements x;


The if statement by itself will execute a single statement or a group of statements.
1) The group of statements of the if and not included else is called if block statement.
2) Similarly the statement after the else called else block statement.


Accept any two integer values and find whether the two integers are equal or not . ?

Program :

/* Equal of two numbers created on 22-09/07 */

#include
#include
main()
{
int x=0,y=0;
clrscr();
printf("enter x integer value :");
scanf("%d",&x);
printf("enter y integer value:");
scanf("%d",&y);
if(x==y)
printf("Both numbers are equal ");
else
printf("not equal");
getch();
return 0;
}


Accept any two integers and find the biggest value ? 22/9/07

Program :

/* Biggest of two numbers created on 22-09/07 */

#include
#include
main()
{
int x=0,y=0;
clrscr();
printf("enter x integer value :");
scanf("%d",&x);
printf("enter y integer value:");
scanf("%d",&y);
if(x>y)
printf("X is biggest ");
else
printf("Y is biggest");
getch();
return 0;
}

Case studies :
1) Accept any integer value and find whether the given integer is positive or negative.
program

/* To find the integer value is positive or negative */

#include
#include
main()
{
int a=0;
clrscr();
printf("enter integer value ");
scanf("%d",&a);
if(a>0)
printf("the integer value %d is positive ");
else
printf("the integer value %d is negative");
getch();
return 0;
}

2) Accept any integer value and find whether the given integer is even or odd?
Program :
/* To find the integer value is even or odd created on 23-09-07 */

#include
#include
main()
{
int x=0;
clrscr();
printf("enter integer value ");
scanf("%d",&x);
if(x%2==0)
printf("the integer value %d is an even number");
else
printf("the integer value %d is an odd number");
getch();
return 0;
}


3) Accept any alphabatical value and find whether the given alphabet is vowel or consonant ?
Program 24/09/07

/* To find the given character is vowel or consonant created on 24/9/07*/

#include
#include
main()
{
char x;
clrscr();
printf("enter a character\t");
scanf("%c",&x);
if(toupper(x)=='A'||toupper(x)=='E'||toupper(x)=='I'||toupper(x)=='O'||toupper(x)=='U')

[( or ) /* if(x=='a'||x=='A'||x=='e'||x=='E'||x=='i'||x=='I'||x=='u'||x=='U'||x=='o'||x=='O')]
*/ printf("it is a vowel");
else
printf("it is a consonant");
getch();
}
Program : 24/9/07
/* To find the character which is in upper case or lower case by using three methods */
/* created on 24/09/07 */

#include
#include
main()
{
char n;
clrscr();
printf("enter the character:\t");
scanf("%c",&n);
if(isupper(n))
printf("the given character is upper case letter");
else
printf("the given character is lower case letter");
/* SECOND METHOD

if(n>=65&&n<=90)
printf("the given character is uppercase letter");
else
printf("the given character is lowercase letter ");

THIRD METHOD

if(n>='A'&&n<='Z')
printf("the given character %c is uppercase letter");
else
printf("the given characte %c is lowercase letter");*/
getch();
return 0;
}



2) Multiple if(the if else ladder) :-
Syntax :
If()
{
Statements ;
}
Else if()
{
Statements;
}
Else if()
{
Statements;
}
- - - -- - - - - - - - - - -
- - - - - - - - - - - -
- - - - - - - - -- - - -
- ------ - - - - - - - -

Else
{
Statements;
}
Statements x;

There is another way putting if’s together when multiple path decisions are involved. A multiple path decision is a chain of if’s , if the statement associated with each else is as on if.
Program :
/* ABC sales data created on 24/09/07 */

#include
#include
main()
{
int ino=0;
unsigned int qty=0;
float r=0,dp=0.00,amt=0,damt=0,net=0;
/* dp=discount percent,damt=discount amount */
char iname[15];
clrscr();
printf("enter the item number :");
scanf("%d",&ino);
printf("enter the item name :");
scanf("%s",&iname);
printf("enter the quantity of particular item : ");
scanf("%u",&qty);
printf("enter the rate of the item :");
scanf("%f",&r);
amt=qty*r;
if(amt>=20000)
dp=0.1;
else if(amt>=10000&&amt<20000 br=""> dp=0.07;
else if(amt>=5000&&amt<10000 br=""> dp=0.05;
else
dp=0.02;
damt=amt*dp;

/* {
damt=(amt*0.1);
printf("the discount of the item is gives 10percent %f" ,damt);
}
else if(amt>=10000 && amt<20000 br=""> {
damt=(amt*0.07);
printf("the discount of the item gives 7percent is %f",damt);
}
else if(amt>=5000&&amt<10000 br=""> {
damt=(amt*0.05);
printf("the discount of the item gives is 5percent is %f",damt);
}
else
{
damt=(amt*0.02);
printf("the discount of the item is gives 2percent is %f",damt);
} */
net=amt-damt;
printf("\nthe total amount is %f\n the discount received is %f \ndiscount percent is%f \n total net is %f",amt,damt,dp,net);
getch();
return 0;
}


Gotoxy(C,R) : 25/9/7
This function will help us to keep the cursor at a desired location with in the limits of text mode x-columns, y-rows(80 columns,25rows
Program :
/* To calculate the electricity bill created on 25-9-07 */

#include
#include
main()
{
int cr=0,pr=0,nou=0;
float R=0,bill=0;
char mno[5],cname[20];
clrscr();
gotoxy(32,4);
printf("ELECTRICITY BILL ");
gotoxy(60,4);
printf("DATE :25/09/2007");
gotoxy(5,5);
printf("*******************************************************************");
gotoxy(5,7);
printf("Enter meter no :");
gotoxy(50,7);
printf("Enter Cname :");
gotoxy(5,8);
printf("********************************************************************");
gotoxy(32,9);
printf("Enter CR :");
gotoxy(32,11);
printf("Enter PR :");
gotoxy(5,13);
printf("********************************************************************");
gotoxy(5,15);
printf("No.of.Units :");
gotoxy(32,15);
printf("Rate :");
gotoxy(50,15);
printf("Bill :");
gotoxy(5,17);
printf("*********************************************************************");
gotoxy(32,19);
printf("THANK Q");
gotoxy(22,7);
scanf("%s",mno);
gotoxy(64,7);
scanf("%s",cname);
gotoxy(42,9);
scanf("%d",&cr);
gotoxy(42,11);
scanf("%d",&pr);
nou=cr-pr;
if(nou>=800)
{
R=5.50;
}
else if(nou>=600&&nou<800 br=""> {
R=3.50;
}
else if(nou>=300&&nou<600 br=""> {
R=2.50;
}
else if(nou>=100&&nou<300 br=""> {
R=1.50;
}
else
{
R=1.00;
}
bill=nou*R;
gotoxy(24,15);
printf("%d",nou);
gotoxy(44,15);
printf("%f",R);
gotoxy(60,15);
printf("%f",bill);
getch();
return 0;
}





EXAMAPERS123.BLOGSPOT.COM

'ARRAYS' in C LANGUAGE



'ARRAYS' in C LANGUAGE


'ARRAYS' in C LANGUAGE

HIGH-LEVEL LANGUAGES

So far, it has been necessary to know how many items are to be stored and to declare a variable for each item. Further more, if a large amount of data is to be stored, would be a long and tedious task to think of a separate variable name for each data, and then to type the declaration for each one of these variables.

Arrays are the solution to this problem. They are such an important part of the art of programming that they are included in every

What is an Array?
In C, as in other computer languages, it is possible to assign a single name to a whole group of similar data. For example, if we are interested in a large number of recorded Celsius temperature, we can assign a common name such as C_temp to all of the data. Then we can refer to each element in terms of its position within the list of items. This is done in mathematics, as well as in computer programming, using an entity called an array.

An array is a group of elements that share a common name and that are differentiated from one another by their positions within the array. For example, if we have five numbers, all of which are named x, they may be listed:

X
58
63
49
18
7

The position of each of these elements can be indicated by means of a subscript:

X1 = 58
X2 = 63
X3 = 49
X4 = 18
X5 = 7

In mathematics, a subscript is a number written to the right of the variable name, slightly below the line, and usually in small type. The subscript indicates the position of the particular element with respect to the rest of the elements.

For those movie buffs who are fans of the old Charlie Chan detective movies, you will remember that whenever it became necessary for Mr. Chan to introduce his sons to clients, he would always introduce them as: “This is my number one son…my number two son….” Etc. It is clear from this that even though computers were made, Mr. Chan actually resorted to the method of introducing his sons by their subscripts!

Since it is impossible to display subscripted numbers on the standard computer terminal, the usual recourse is to enclose the subscript in parentheses or brackets. In C (as in Pascal), square brackets are used. The following five statements are valid in C.
X[1] = 58;
X[2] = 63;
X[3] = 49;
X[4] = 18;
X[5] = 7;
HOW ARRAYS ARE USEFUL
To see the usefulness of arrays, consider the problem of reading the age of 5 persons, printing them out individually and computing the average. Here is a solution that does not use arrays.

#include
main()
{
int a1, a2, a3, a4, a5;
float sum=0;
printf (“Age:”);
scanf(“%d”, &a1);
sum += a1;
printf (“Age:”);
scanf(“%d”, &a2);
sum += a2;
printf (“Age:”);
scanf(“%d”, &a3);
sum += a3;
printf (“Age:”);
scanf(“%d”, &a4);
sum += a4;
printf (“Age:”);
scanf(“%d”, &a5);
sum += a5;
printf (“The ages that were input are:\n”);
printf(“%d\n”, a1);
printf(“%d\n”, a2);
printf(“%d\n”, a3);
printf(“%d\n”, a4);
printf(“%d\n”, a5);
printf (“Average =%f\n”, sum /5);
}
The program is very simple. It reads the ages of 5 persons, adds them up in a variable called sum, and at the end, divides sum by 5 to get the average age. Needless to say, this is a very clumsy way to write a program. If there are a large number of persons, the number of statements increases proportionately. To avoid this, use a loop. But the problem is that different variables are needed to store the ages of different persons and hence, the loop will have to store and print different variables each time. A more elegant way is to use an array of integers to store the ages, as shown in the example below. Notice the declaration of the array variable in the first line of main().

#include
void main()
{
int age[5]; /* Array of 5 ages, declaration for an array */
int i, n;
float sum = 0;
printf (“Number of persons:”);
scanf(“%d”, &n);
if (n<=0 || n>5)
printf (“Invalid number of persons entered.\n”);
else
{
for (i=0; i {
printf (“Age:”);
scanf(“%d”, &age[i]);
sum += age[i];
}
printf (“the ages input are :\n”);
for (i=0; i printf (“%d\n”, age[i]);
printf (“The average is : %f\n:, sum /n);
} /* end main */
Run
Number of persons: 5
Age: 10
Age: 20
Age: 30
Age: 40
Age: 50
The ages input are:
10
20
30
40
50
The average is : 30.000000

(i) Declaration
The previous program is examined now. Recall that all variables in C must be declared before use. Hence, we must first declare the array. It is done at the beginning of the function main() with the statement
int age[5];

This statement states that age is an array of 5 integers. Note the use of square braces after the array name (i.e., age) enclosing the integer 5 that gives the number of elements in the array. This statement reserves enough memory for age to hold 5 integers. Once the declaration is made, ag [0] refers to the first integer in the array, age [1] refers to the second integer and so on. Finally, age [4] refers to the last integer in the array. In C, array indices always begin with zero. Figure 7.1 shows the declaration of an array.

Fig. 7.1 Array definition

(ii) Accessing array elements
To access a particular element in an array, specify the array name, followed by square braces enclosing an integer, which is called array index. The array index indicates the particular element of the array which we want to access. The numbering of elements starts from zero (i.e. age[0] is the age of the first person). Figure 7.2 depicts the elements of an array in memory. It is assumed that each element of the array (i.e., each integer) occupies two bytes.

Next, observe the loop used to input the elements. It is reproduced here for convenience.

for (i=0; i {
printf (“Age:”);
scanf(“%d”, &age[i]);
sum += age[i];
}

The variable i was from 0 to n-1 (0 to 4 in the above sample run). The function scanf is called to input an integer value. The address of the ith element is passed to scanf. This makes scanf store the integer input into successive integer positions each time the loop is executed. Note that
&age[i];
in the scanf statement refers to the memory location of the integer at the ith position.

The statement
sum+= age[I];
adds the value of the ith integer to sum.

The rest of the program illustrates the use of the array variable in various situations. The first for loop is used to add to the variable sum, and in the second, to print out the values of age that are input.

An element such as age[i] can be used just like any other ordinary integer. Statements such as





Fig 7.2 Elements of the array age

age[i]++; (to increment the value of the ith integer in the array age) and age [i]=11; are perfectly valid.

(iii) Initialization of single dimensional array
Arrays can be initialized once they are declared. The declaration of an array can be done as follows:

int a[5] = { 13, 34, 2, 6, 234 };

Here, a is an array of 5 integers. The initial value of the five integers are specified in order, between the curly braces, separated by commas. The above declaration causes a [0] to be initialized to 13, a[1] to 34 and so on, till a [4], which is initialized to 234. A semicolon always follows the closing brace.

The array size may be omitted during declaration, as shown below.

int a[] = {13, 34, 2, 6, 234};

This declaration is equivalent to the first one. In this case, the subscript is assumed to be equal to the number of elements in the array (5 in this case). Figure 7.3 shows the initialization of an array.

Fig. 7.3 Array Initialization
(iv) Warning
C does not check the validity of the subscript when you use arrays. For example, take a look at the program below:

void main()
{
int a[40];
a[50] = 11;
a[50]++;
}

In essence, the program declares a as an array of 40 integers, and then modifies the 51st element! When you compile the above program, you do not get any error. The executable code is produced. When it is run, the results are unpredictable. Hence, we must be very careful while using array subscripts. A wrong subscript in a large program can cause it to behave erratically, demanding a lot of debugging time.

Similar to an array of integers, we can have an array of any data type. For example, the declaration for an array of 50 floating-point numbers is:
float f[50];
The individual floating-point numbers in this array are accessed as before, i.e., f[0] is the first floating-point number and f(49) the last.

(v) Name of the array
Take the case where f is an array of floating point numbers. It is declared as:

float f[50];

The name of the array is f. If it is used as it is, without any subscript, then it refers to the memory location of the first floating-point number in the array. Recall that placing an ampersand (&) before a variable name refers to its memory location. Thus, the array name f is equivalent to &f[0]. The statement

scanf(“%f”, &f[0]);
is equivalent to
scanf(“%f”, f);

Perhaps, this may not seem to be very useful now. But its potential will be made evident later, in the chapter on pointers.



SUCCESS FOR CAREER





Example 7.1
An example to find out the largest and smallest element in an array is illustrated below:

/* large1.c: largest and smallest element in the vector */
#include
main()
{
int i,n;
float a[50], large, small;
printf (“Size of vector ?”);
scanf (“%d, &n);
printf (“\n Vector elements?\n”);
for (i=0; i scanf (“%f”, &a[i]);

/* Initialization */
large = a[0];
small = a[0];
/* largest and smallest elements */
for (i=l; i {
if(a[i] > large)
large = a[i];
else if (a[i] < small)
small = a[i];
}
printf (“\n Largest element in vector is %8.2f\n”, large);
printf(“\n Smallest element in vector is %8.2f\n”, small);
}

Run:
Size of vector ? 7
Vector elements ?
3.400 -9.00 12.00 10.00 -6.00 0.00 36.00
Largest element in vector is 36.00
Smallest element in vector is -9.00

Example
/* sort.c: sorting the vector elements in ascending order */
#include
main ()
{
int i,j,k,n;
float a[50], temp;
printf (“Size of vector ?”);
scanf(“%d”, &n);
printf (“\n Vecntor elements ?\n”);
for (i=0; i scanf(“%f”, &a[i]);
/* sorting vector A using selection sort */
for (i=0; I for(j=i+l;j {
/* To sort in descending order change the ‘>’ */
/* operator to ‘<’ in the IF structure */
if (a[I] < a[j])
{
temp = a[i];
a [i] = a[j]
a[j] = temp;
}
}
printf (“\n Vector elements in ascending order: \n”);
for (i=0; i printf (“%8.2f’,a(i]);
}
Run:
Size of vector ? 8
Vector elements ?
91.00 20.00 1.00 7.00 34.00 11.00 -2.00 6.00
Vector elements in ascending order:
-2.00 1.00 6.00 7.00 11.00 20.00 34.00 91.00

Example

/* insert.c: inserting an element into an vector */
#include
main()
{
Int i,j,k,n,pos;
float a[50], item;
printf (“size of vector ?”);
scanf(“%d”,&n);
printf(\n vector elements ? \n”);
for (i=0; i scanf (%f”, &a[i];
printf (“\n element to be inserted ?”);
scanf (“%f”, &item);
printf (“\n position of insertion ? “);
scanf (“%d”, &pos);
/ * Pushing down elements */
n++;
for (k=n; k>=pos; k--_
a[k] = a[k-1];
a[--pos] = item; /* item inserted */
printf (“\n Vector after insertion : \n”);
for (i=0; i printf (“%6.2f”, a[i]);
printf (“\n”);
}

Run:
Size of vector? 6
Vector elements ?
1.00 2.00 3.00 4.00 5.00 6.00
Element to be inserted ? 10.00
Position of insertion ? 1
Vector after insertion :
10.00 1.00 2.00 3.00 4.00 5.00 6.00

Run 2:
Size of vector? 5
Vector elements ?
1.00 2.00 4.00 5.00 6.00
Element to be inserted ? 3.00
Position of insertion ? 3
Vector after insertion :
1.00 2.00 3.00 4.00 5.00 6.00

7.3 MULTIDIMENSIONAL ARRAYS
Often, there is a need to store and manipulate two-dimensional data structures such as matrices and tables. Here, the array has two subscripts. One subscript denotes the row, and the other, the column. As before, all subscripts (row and column) start with 0.

(i) Declaration
The declaration of a two-dimensional array is as follows:
float m[10][20];
Here, m is declared as a matrix having 10 rows (numbered 0 through 9) and 20 columns (numbered 0 through 19). The first element in the matrix (the element at the first row and first column) is:
m[0] [0]
and that at the last row and last column is:
m[9] [19]

(ii) Elements of multidimensional arrays
A two dimensional array marks [4] [3] is shown Figure 7.4. The first element is given by marks [0] [0] which contains 35.5, the second element is marks [0] [1] and contains 40.5 and so on. Figure 7.5 is a pictorial representation of the two dimensional array marks as stored in the memory.


Fig 7.4 Two dimensional matrix: marks [4] [3]




Fig 7.5 Two dimensional array to store marks

Note: The declaration of a two dimensional array, for example, m[10] [20] may be confusing to those who are familiar with other languages such as FORTRAN, where the array subscripts are separated by a comma. Consider the following program typed by a confused programmer.



# include
void main( )
{
int m[10] [20];
m[5] [16] = 13;
printf (“%d\n”, m[5,16]);
}

The first two lines in main() are fine, but the third line wrongly uses a comma inside the square braces, instead of enclosing the two subscripts separately. The danger lies in the fact that comma is an operator in C. Recall that the comma operator causes the expressions to be evaluated from left to right, and the value of the right most expression becomes the value of the entire expression containing the comma operators. In this case, the result of the expression with 5,16 inside the square braces, evaluates to 16 and hence, the printf statement shown above is equivalent to:
printf(“%d\n”, m[16]);

But since the array m is two dimensional, one would feel that m[16] would give a compile time error. But this is not so, since m[16] actually refers to the memory location of the first element in the 17th row. Even though there is no 17th row, C does not check this fact. So there will be no compile time errors on this account. At run time, instead of 13, some other number may get printed, or the program may crash. Needless to say, such errors made in a large program are difficult to detect.

(iii) Accessing two dimensional array elements
The elements of a two dimensional array can be accessed by the following expression:
marks [i][j]
where i refers to the row number and j, the column number.

(iv) Initializing two dimensional arrays
Initialization of a two-dimensional array during declaration is done by specifying the elements in row major order (i.e., with the elements of the first row in a sequence, followed by those of the second, and so on). An example is given below:

int two_dim_int[3] [4] =
{
{1, 2, 3, 4},
{2, 3, 4, 5},
{5, 6, 7, 8}
};

The variable two_dim_int is declared as a two dimensional integer array with certain initial values. The first subscript can be omitted. For example, the declaration below wherein the number of rows(3) is not explicitly specified, is equivalent to the previous one.
int two_dim_int[ ] [4] =
{
{1, 2, 3, 4},
{2, 3, 4, 5},
{5, 6, 7, 8}
};

Also, the inner braces can be omitted, giving the numbers in one continuous sequence. For example, has the same effect as the previous example, but is not as readable as before.

(v) Passing arrays to functions
Arrays can be passed as arguments to functions. Consider the following example:

/* arrfunc.c: passing arrays to functions */
#include
const int Rollno =4;
const int Subject = 3;

/* function declaration */
void display (float marks [Rollno] [Subjects]);

main()
{
float marks [Rollno] [Subjects] =

/* array initialization */
{
{35.5, 40.5, 45.5},
{50.5, 55.5, 60.5},
{65.0, 70.0, 75.5}
{80.0, 85.0, 90.0}
};
/* function call with array as an argument */
display (marks);
} /* end main */
/* function definition to display elements */
void display (float Studentmarks [Rollno] [Subjects])
{
int r,s;
for (r=0; r {
printf (“\n Rollno %d”);
for (s=0; s printf (“%10.24”, Studentmarks [r] [s]);
} /* end for */
} /* end display */

The function declaration in the above program,
void display (float marks [Rollno] [Subjects]);
can also be written as,

void display (float marks [ ] [Subjects]);

The function display visualizes marks as an array, where the number of columns is Subjects. While calling the function, the name of the array is sufficient as an argument. Hence, the function call in main is of the form:
display (marks); /* function call */

The name marks represents the memory address of the array and is similar to using a reference argument. Elements of an array are not copied but the function works with a different name, on the original array itself. Hence, any modifications done to the array in the function are reflected in the array of the caller too. Passing by reference is efficient, as arrays can be very large and copying the entire array into a function consumes time and memory.

The function definition.
void display (float StudentMarks [Rollno] [Subject])
uses the name of the array, datatype and their sizes. Inside the function the elements of the array are accessed by:
studentmarks [r][s]

Example

/* addmat.c: program to add tow matrices */
#include
main()
{
int a[10] [10], vb[10] [10], c[10] [10], i,j,m,n,p,q;
printf (“Input row and column of A matrix \n”);
scanf(“%d %d”, &n, &m);
printf (“Input row and column of B matrix \n”);
scanf(“%d %d”, &p, &q);
/* checks if matrices can be added */
if(n==p)&&(m==q))
{
printf(“matrices can be added\n”);
printf(“Input A-matrix\n”);
for(i=0; i for(j=0; j scanf(“%d”, &a[i][j]);
pritnf (“Input B-matrix \n”);
for(i=0; i for(j=0; j /* Addition of two matrices */
for(i=0; i for(j=0; j c[i][j] = a[i][j] + b[i][j];
printf (“sum of A and B matrices :\n”);
for (i=0, i {
for (j=-; j printf (“%5d”,c[i][j]);
printf(“\n”);
}
} /* endif */
else
printf (“matrices cannot be added \n”);
} /* main */

Run 1:
Input row and column of A matrix
3 3
Input row and column of B matrix
1 2
Matrices cannot be added

Run 2:
Input row and column of A matrix
3 3
Input row and column of B matrix
3 3
Matrices can be added

Input A-matrix
1 2 3
4 5 6
7 8 9

Input B-matrix
1 2 3
4 5 6
7 8 9

Input A and B-matrix
2 4 6
8 10 12
14 16 18

Example
/* trace.c: Trace of the matrix */
#include
main()
{
int a[10] [10], i,j, n, trace;
printf (“Enter the order of A matrix \n”);
scanf (“%d”, &n);
printf (“Input A-matrix\n”);
for (i=0; i for (j=0; j scanf (“%d”, &a[i[ [j]);
/* Trace = Sum of the diagonal elements of the matrix */
trace = 0;
for (i=0; i trace += a[i] [i];
printf (“trace = %d \n”, trace);
} /* main */

Run:
Enter the order of A matrix
3
Input A-matrix
1 2 3
4 5 6
7 8 9
Trace = 15

Example

/* mult.c: program to multiply tow matrixes */
#include
main()
{
int a [10] [10], b [10] [10], c[10] [10], i,j, m,n,ip,k,p,q;
printf (“Input row and column of A matrix :”);
scanf (“%d %d”, &m,&n);
printf (“Input row and column of B matrix:”);
scanf (“% %d, &k, &q);
if (n==k)
{
printf (“matrices can be multiplied \n”);
printf (“resultant matrix is %d X %d\n”,m,q);
printf (“input A-matx \n”);
read_mat (a,m,n);
printf(“Input B-matrix \n”);
/* function call to read the matrix */
read_mat(b,k,q);
/* Multiplication of two matrices */
for (i=0; i for )j=0; j {
c[i] [j] = 0;
for(ip=0; ip c[i] [j] = c[i] [j] + a[i] [ip] * b[ip] [j];
}
printf (“Resultant of A and B matrices :\n”);
write_mat (c,m,q);
} /* end if */
else
{
printf (“Col of matrix A must be equal to row of matrix B \n”);
printf (“matrices cannot be multiplied \n”);
} /* end else */
} /* End of main */
/* function re ad matrix */
read_mat(a,m,n)
int a[10] [10], m,n;
{
int i,j;
for (i=0; i for (j=0; j scanf (“%d”, &a[i] [j]);
}
/* function tow rite the matrix */
write_mat (a,m,n)
int a [10] [10], m,n;
{
int i,j;
for (i=0; i {
for (j=0; j printf (“%5d”, a[i] [j]);
printf (“\n”);
}
}

Run 1:
Input row and column of A matrix: 3 3
Input row and column of B matrix: 3 3
Matrices can be multiplied
Resultant matrix ix 3 X3
Input A-matrix
1 2 3
4 5 6
7 8 9

Input B-matrix
1 2 3
4 5 6
7 8 9
Resultant of A B matrices :
30 36 42
66 81 96
102 126 150
Run 2:
Input row and column of A matrix: 1 2
Input row and column of B matrix: 3 4
Col of matrix A must be equal to row of matrix B
Matrices cannot be multiplied
Example
/* trans.c: Transpose of a matrix */
#include
main()
{
int a [10] [10], b[10] [10], i,j,m,n;
printf (“Input row and column of A matrix:”);
scanf (“%d %d”, &n, &m);
printf (“\n Inpute A-matrix \n”);
for (i=0; i for (j=0; j scanf (“%d”, &a[i] [j]);
/* the rows and columns are interchanged: transpose */
for (i=0; i for (j=0; j b[i] [j] = a[j] [i];
printf (“\n Transpose of matrix A is :\n”);
for (i=0; i {
for (j=0; j printf (“%6d”, b[i] [j]);
printf (“\n”);
}
} /* main */

Run:
Input row and column of A matrix : 3 4
Input A-matrix
1 2 3 4
5 6 7 8
9 6 7 8

Transpose of matrix A is :
1 5 9
2 6 6
3 7 7
4 8 9

STRINGS
Strings are arrays of characters, i.e., they are characters arranged on e after another in memory. To mark the end of the string. C uses the null character. Strings in C are enclosed within double quotes. So, for example,
“My age is 2 (two)”
is a string. The string is stored in memory as ASCII codes of the characters that make up the string appended with 0 (ASCII value of null). ASCII values of all characters are given in Chapter 14, with the help of which we will examine the memory occupied by the string.

Normally, each character is stored in one byte, and successive characters of the string are stored in successive bytes.

Character: M Y a g e i s 2
ASCII Code: 77 121 32 97 103 101 32 105 115 32 50 32

( t w 0 ) \0
40 116 119 111 41 0

The last character, as you can see, is the null character, having the ASCII value zero.

(i) Initializing strings
Following the discussion on character arrays (i.e., a string), the initialization of a string must have the following form, (this is similar to initializing a one dimensional array):

Char month 1[] = (‘J’, ‘a’, ‘n’, ‘u’, ‘a’, ‘r’, ‘y’, 0);
Then the string month is initialized to January. This is perfectly valid, but C offers a special way to initialize strings. The above string can be initialized as:

Char month1 [] = “January”;

The characters of the string are enclosed within a pair of double quotes. The compiles takes care of storing the ASCII codes of the characters of the string in memory and also stores the null terminator in the end. A simple program to display a string is listed below.

/* string.c: string variable */
#include
main
{
char month [15];
printf (“Enter the string”);
gets (month);
printf (“the string entered is %s”, month);
}

In this example, a string is stored in the character string variable month. The string is displayed by the statement:
printf (“The string entered is %s”, = month)

It is a one dimensional array. Each character occupies a byte. A null character (‘\0’) that has the ASCII value 0 terminates the string. Figure 7.6 shows the storage of the string January in the memory. Recall that \0 specifies a single character whose ASCII value is zero.

Fig. 7.6 String stored in a string vairable month
Example:
/* string2.c: illustration using a string literal */
#include
main ()
{
char strc [] = “This is a string literal”;
printf (“%s”, strc);
}
Run:
This is a string literal

7.5 ARRAYS OF STRINGS
An array of strings is a two dimensional array. Consider an example that initializes 5 names in an array of strings and prints them.

/* starray.c: array of strings */
#include
const int NUM = 5;
const int LENGTH = 9;
main ()
{
int j;
char Name [NUM] [LENGTH] =
(“Tejaswi”, “Prasad”, “Prasanth”, “Prakash”, “Anand”};
for (j=0; j printf (“%s\n”, Name [j]);
}
run:
Tejaswi
Prasad
Prasanth
Prakash
Anand



Fig. 7.7 Array of strings

A string is an array; and Name is an array of strings. It can be represented by a two dimensional array of size [5] [9] as shown in Figure 7.7. The second dimension LENGTH specifies the length of the longest array string (9 characters for Prasanth including the terminal character ‘\0’) and each name is accessed by Names[j]. Here, we do not need the second index. Name [j] is sufficient to access string number j in array.

7.6 FUNCTIONS IN string.h

This section describes the functions that help in manipulating strings. To use these functions, the header file string.h must be included in the program with the statement:
#include
strcat
This function concatenates two strings, i.e., it appends one string at the end of another. The function accepts two strings as parameters and stores the contents of the second string at the end of the first. An example is given below.

/* stract.c: Example program for stract */
#include
#include
void main()
{

/* Declare two strings */
char oneString [10] = “Fish”;
char twoString [] = “face”;
/* Put twoString at the end of onestring. */
strcat (oneString, twoString);
printf (oneString);
}

The output of this program is:

Fish face

The central part of the program is the statement,
Strcat (oneString, twoString);
Which places the characters of twostring at the end ofoneString.

Observe that the declaration of oneString has the subscript 10 specifying the size of the string, while the declaration of twoString does not have any size specified. Recall that in the declaration of arrays, if the subscript is omitted, it is assumed to be size of the data with which the array is initialized. So, while the size of the string oneString is 10 (which means that oneString can hold a maximum of 10 characters), the size of twoString is equal to the size of the string face. This string has 4 characters plus a null character, which makes a total of 5. So, the size of the string twoString is 5.

If we declare oneString with the statement,
Char oneString [] = “Fish”;
then oneString will be able to hold a maximum of 6 characters only. When the statement,
strcat (oneString, twoString);
appends the characters of twoString at the end of oneString, the size of oneString would not suffice. This leads to unpredictable results at run time. Hence, in the above program, onestring is declared by the statement,

char oneString[10] = “fish”;
which is safe, since after concatenation, oneString becomes Fish face, which is 10 characters in length, including the null terminator. In general, whenever you use the stract function, check to see whether the first string is large enough to hold the resultant concatenated string. Note, there is no ‘+’ operator in C that can be applied to strings in order to concatenate them. The function strcat described here exists for that purpose.

Strcomp
The function strcmp compares two strings. This function is useful while writing programs for constructing and searching strings as arranged in a dictionary. The function accepts two strings as parameters and returns an integer, whose value is:
* Less than 0 if the first string is less than the second
* Equal to 0 if both are identical
* Greater than 0 if the first string is greater than the second

The function strcmp compares the two strings, character by character, to decide the greater one. Whenever two characters in the string differ, the string which has the character with a higher ASCII value is greater. For example, consider the strings hello and Hello!!. The first character itself differs. The ASCII code for h is 104, while that for H is 72. Since the ASCII code of h is greater, the string hello is greater than the string Hello!!. Once a differing character is found, there is no need to compare the other characters of the strings. The following code fragment compares two strings and output the result.

char str[30], str2[30];
int cmpResult;
scanf(“%s %s”, str1, str2);
cmpResult = strcmp (str1, str2);
if (cmpResult<0 br=""> printf (“str1 else if (cmpResult == 0)
printf (“str1 ==2”);
else
printf (“str1 > str2”);

A sample run is shown below:

azcd abzzi
str1 > str2

Again, note that the operators <, > and == cannot be used directly with strings. To compare strings, use strcmp.

Strcpy
The strcpy function copies one string to another. The function accepts two strings as parameters and copies the second string character by character into the first one, upto and including the null character of the second string. As in the function strcat, you need to be careful to make sure that the size of the string is greater or equal to the second.

For example the following code:
char str1[] = “Will be overwritten”;
char str2[] = “Will overwrite”;
printf (“Before strcpy str1 is \n”);
printf (“%s \n”, str1);
strcpy(“str1, str2);
printf (“After strcpy str1 is \n”);
printf (“%s\n”, str1);

will output:
before strcpy stril is
Will be overwritten
After strcpy strl is
Will overwrite

The operator = cannot be used to assign one string to another. Use strcpy for this purpose.
strlen
This function returns an integer which denotes the length of the string passed. The length of a string is the number of characters present in it, excluding the terminating null character. For example,

char str[] = “Hello”;
printf (“%d\n”, strlen (str));
will output 5, since there are 5 characters in the string Hello.
More on string library functions is given in the chapter on pointers.

7.7 PROGRAMMIN EXAMPLES

Example

/* dup.c: Deleting duplicates in a Vector */
#include
main()
{
int i,j,k,n,num,flag = 0;
float a[50];
printf (“Size of vector ? “);
scanf (“%d”, &n);
num = n;
printf (“\n Vector elements ? \n”)
for (i=0; i scanf (“%f”, &a[i]);
/* removing duplicates */
for (i=0; i for (j=I+1; j {
if (a[i] == a[j])
{
n=n – 1;
for (k=j; k a[k] = a[k+1];
flag = 1;
j=j-1;
}
}
/* use of IF and ELSE statement */
if (flag == 0)
printf (“\n No duplicates found in vector \n”);
else
{
printf (“\n Vector has %d duplicates”, num –n);
printf (“Vector after deleting duplicates : \n”);
for (i=0; i printf (“% 6.2f”, a[i]);
printf (“\n”);
}
}

Run:
Size of vector 7 6
Vector elements ?
1.00 2.00 1.00 3.00 2.00 4.00
Vector has 2 duplicates
Vector after deleting duplicates:
1.00 2.00 3.00 4.00

Example
/* grade.c: Calculating grades of ‘N’ students from 3 tests */
#include
main()
{
int i,j,k,n,m;
float a[50] [10], sum, avg;
char grade [50];
printf (“Number of students ?”);
scanf (“%d”, &n);
for (i=0; i {
sum = 0.0;
printf (“\n Enter 3 scores of student-%d \n”, i+1);
for (j=0; j<3 br="" i=""> {
scanf (“%f”, &a[i][j]);
sum += a[i] [j];
}
avg = sum / 3.0;
a [i] [3] = avg;
if (avg <30 .0="" br="" else="" if..="" of="" use=""> grade [i] = ‘E’;
else if (avg <45 .0="" br=""> grade [i] = ‘D’;
else if (avg <60 .0="" br=""> grade [i] = ‘C’;
else if (avg <75 .0="" br=""> grade [i] = ‘B’;
else
grade [i] = ‘A’;
}

printf (“\n Sl.no. Scores Average Grade \n”);
printf (“\n--------------------------------------\n\n”);
for (i=0; i {
printf (“%d.”, i+1);
for (j=0; j<4 br="" j=""> printf (“%82f”, a[i] [j]);
printf (“%6c”, grade [i]);
printf (“\n”);
printf (“\n--------------------------------------\n\n”);
}
}

Run:
Number of students ? 5
Enter 3 scores of student –1
67.00 86.00 58.00
Enter 3 scores of student –2
20.00 30.00 23.90
Enter 3 scores of student –3
80.00 97.00 73.00
Enter 3 scores of student –4
56.80 47.90 62.00
Enter 3 scores of student –5
45.00 35.00 40.00

Sl.No. SCORES AVERAGE GRADE
------------------------------------------------------------------------------------------------
1. 67.00 86.00 58.00 70.33 B
2. 20.00 30.00 23.00 24.63 E
3. 80.00 97.00 73.00 83.33 A
4. 56.80 47.90 62.00 55.57 C
5. 45.00 35.00 58.00 70.33 B
------------------------------------------------------------------------------------------------

Example

/* var.c: Calculating Mean, Variance and standard deviation */
#include
#include
main()
{
int i,n;
float x[50], mean, variance, sdn;
float sumsq = 0.0, sum = 0.0;
printf (“Calculating standard deviation of a\n”);
printf (“\n Enter size of the list:”);
scanf (“%d”, &n);
printf (“\n Enter the %d items \n”, n);
for (i=0; i {
scanf (“%f”, &x[i]);
sum += x[i]);
}
mean = sum/(float) n;
/* Computing variance */
for (i=0; i sumsq = sumsq + (mean – x[i])* (mean – x[i]);
variance = sumsq/(float)n;
sdn = sqrt (variance); /* Standard deviation */
printf (“\n\n Mean of %5d items : %10.6f\n”,n,mean);
printf (“\n variance : %10.6f\n”,varaince);
printf (“\n Standard Deviation : % 10.6f\n”,sdn);
}
Run:
Calculating standard deviation of a
Enter size of the list : 7
Enter the 7 items
32.00 11.00 90.00 34.00 52.00 24.00 7.00
Mean of 7 items : 35.714287
Variance : 685.918396
Standard Deviation : 26.190044

Example

/* norm.c: Program to compute the norm of the matrix */
#include
#include
main()
{
int i,j,m,n;
float norm, a[10] [10];
float nrm (float [] [], int, int);
printf (“Input row and column of A matrix:”);
scanf (“%d %d”, &n, &m);
printf (“%d %d n”, n,m);
printf (“Input A-matrix \n”);
for (i=0; i for (j=0; j scanf (“%f”, &a[i] [j]);
norm = nrm (a,n,m);
printf (“Norm = %6.2f \n”, norm);
} /* End of main */
/* norm of a matrix = sqsuareroot of the sum of the */
/* squares of the elements of the matrix */
float nrm
(float a[] [], int n, int m)
{
int i,j;
float sum = 0.0;
for (i=0; i for (j=0; j sum = sum + a[i] [j] * a[i] [j];
printf (“Sum = %6.24\n”, sum);
return (sqrt ((double)sum));
}
Run:
Input row and column of A matrix : 3 3
Input A-marix

1.00 2.00 3.00
4.00 5.00 6.00
7.00 8.00 9.00

Sum = 285.00
Norm – 16.88

Example

/* saddle.c: Program to find saddle point in a matrix */
#include
main()
{
int a[5] [5], i,j,min,max,n,m,flag=1,p,q;
printf (“Input the size of matrix:”);
scanf (“%d %d”, &n, &m);
printf (“Enter the elements of the matrix \n”);
for (i=0; i for (j=0; j scanf (“%d”, &a[i] [j]);
/* Find minimum element in row */
for (i=0; i {
min = a[i] [0];
p=i;
q = 0;
/* To check whether ‘min’ is the maximum in column */
for (j=0; j {
if (min>a[i] [j])
{
min=a[i] [j];
p = i;
q = j;
}
}
for (j=0; j{
if(j ! = q)
{
if (a[j] [q] > a[p] [q])
flag = 0;
}
}
if (flag)
printf (“Saddle point a [%d] [%d] = %d\n”, p+1, q+1, a[p] [q]);
else
printf (“No saddle point in row %d\n”, i+1);
flag = 1;
}
}

Run:
Input the size of matrix : 3 3
Enter the elements of the matrix

7 5 5
10 5 8
6 3 3
Saddle point a[1] [2] = 5
Saddle point a [2] [2] = 5
No saddle point in row 3

Example

/* sym.c: Program to find the symmetry of the matrix */
#include
main()
{
int a[10] [10], b[10] [10],i,j,n, flag;
printf (“Input order of the A matrix);
scanf (“%d”, &n);
printf (“Input A-matrix\n”);
for (i=0; i for (j=0; j scanf (“%d”, &a[i] [j]);
/* Transpose of the given Matrix */
for (i=0; i for (j=0; j b[i][j] = a[j] [i];
printf (“Transpose of A matrix : \n”);
for (i=0; i {
for (j=0; j printf (“%5d”, b[i] [j]);
printf (“\n”);
}
/* Find symmetry of a matrix */
for (i=0; i if (a[i] [j] != b[i] [j])
flag = 1;
}
if (flag)
printf (“Matrix is not symmetric \n”);
else
printf (“Matrix is symmetric \n”);
} /* main */

Run 1:
Input order of A matrix : 2 2
Input A-matirx
1 2
3 4
Transpose of A matrix:
1 2
3 4
Matrix is not symmetric

Run 2:
Input order of A matrix : 3 3
Input A – Matrix
1 2 5
2 3 4
5 4 9
Transpose of A – Matrix
1 2 5
2 3 4
5 4 9
Matrix is symmetric


{
min = a[i] [0];
p=i;
q = 0;
/* To check whether ‘min’ is the maximum in column */
for (j=0; j {
if (min>a[i] [j])
{
min=a[i] [j];
p = i;
q = j;
}
}
for (j=0; j{
if(j ! = q)
{
if (a[j] [q] > a[p] [q])
flag = 0;
}
}
if (flag)
printf (“Saddle point a [%d] [%d] = %d\n”, p+1, q+1, a[p] [q]);
else
printf (“No saddle point in row %d\n”, i+1);
flag = 1;
}
}

Run:
Input the size of matrix : 3 3
Enter the elements of the matrix

7 5 5
10 5 8
6 3 3
Saddle point a[1] [2] = 5
Saddle point a [2] [2] = 5
No saddle point in row 3


Tutorial
1. What is an array?
2. How is the integer array a, containing 100 elements, declared in C?
3. What is the subscript of the first element of an array in C?
4. What are the rules for naming arrays?
5. How would you declare an array x containing 50 integer elements followed immediately by 50 real elements?
6. What is the purpose of initializing an array?
7. Is it possible to declare and initialize an array in C simultaneously? If, so, how?
8. If array1 and array2 are dimensioned as follows:
Char array1 [10], array2[10];
and array1 has been initialized, what is the effect of the following?
array2 = array1;
9. What purpose is served by the break statement?
10. What criticism can be leveled against the break statement?
11. Explain the operation of the following expression (assume y has the value 5):
x = (y *=2) + (z=a=4);
12. How is a string stored in an array in C?
13. What declaration would be used for the array bingo, into which the string “I love C” is to be stored?
14. What conversion specification usually is used to read in a string?
15. When the conversion specification %s is used in a scanf statement to read in a string, what is unusual about the way the name of the array is specified?
16. How can one ensure that a scanf statement used to read in a string does not read in more characters than the corresponding character array can hold?
17. Is it obligatory to use all the elements of an array?
18. When a one-dimensional array is being declared, under what condition may the dimension be omitted, with the array name followed by an empty pair of square brackets?
19. What happens if an array is being initialized within its declaration, and too few initialization values are specified within the curly braces?
20. What happens if the number of initializing values is greater than the dimension specified for the array?
21. Must the elements of an array be read in or printed out in order or subscript?
22. When sorting the elements of an array, is it necessary to use another array to store the sorted elements?
23. Where is it legal to declare a new variable?
24. What is the name of the construct used in the following statement, ad how does it operator?
A = (b>c) ? b : c;
25. What is the maximum number of dimensions an array in C may have?
26. True or false: If all the elements of a two-dimensional array are initialized in the declaration of the array, both subscriptions may be omitted.

ANSWERS TO C TUTORIAL

1. An array is an ordered collection of elements that share the same name.
2. int a[100]
3. 0 (zero)
4. The same as for naming regular variables or functions. An array cannot have the same name as a variable or function within the same program.
5. It can’t be done. (All elements of a single array must be of the same type).
6. Before any element of an array can be used, it must have a value. Initializing an array gives a value to each of its elements.
7. Yes. The array declaration is followed immediately by an equal sign. This is followed by the list of values to be assigned (separated by commas) enclosed in braces.
8. A syntax error is fledged by the compiler. One array cannot be assigned to another using the assignment operator. Each element must be assigned individually.
9. It provides a means of immediately terminating the execution of a loop.
10. It violates the tenets of structured programming, in that it permits a jump to another part of the program.
11. The first set of parentheses is evaluated first, multiplying the value of y by 2; the new value of y, 10, is returned by the sub-expression. The second set of parentheses is then evaluated, assigning 4 to a and z and returning that value. The values returned by the two sub-expressions (10 and 4) then are added together to produce the result of 14, which is assigned to x.
12. It is terminated by the null character, which has the ASCII value 0 and is written in C as ‘\0’.
13. Char bingo [9]; /* One element is reserved for the null
Character, ‘\0’ */
14. %s
15. The ampersand (&) is not used, and the array is not subscripted.
16. A maximum field width specifier should be used with the 1%s conversion specification; for example, %10s.
17. No, but the program must keep track of how many elements are are being used, and which ones.
18. If the entire array is being initialized within the declaration.
19. This is perfectly acceptable, as long as the dimension is specified explicitly in the declaration. The initialization values that are specified are assigned to consecutive elements of the array, starting with element 0. The remaining elements are initialized to zero.
20. A syntax error occurs during compilation of the program, and the compilation is aborted.
21. No. the elements of an array (even a character array) may be accessed in any order at all.
22. Not always. In this chapter, the method employed did not use another array. The advantage to using another array is that the original array is retained. Its advantage is that it uses extra memory.
23. At the beginning of the body of a function, and at the beginning of a compound statement.
24. The statement makes use of the conditional expression. If b is greater than c, the conditional expression returns the value of b (the value following the ?); otherwise, it returns the value of c (the value following the :). The returned value is assigned to a. The overall effect is that the larger of the two variables b and c is assigned to a.
25. Theoretically, there is no limit. The only practical limits are memory size and the restrictions imposed by the compiler being used.
26. False. Only the first (row) subscript can be omitted, with the first pair of square brackets left empty. The second subscript must always be explicitly specified.

Keywords
break char do double else float
for if int long return short
unsigned

Exercises
1. What are the arrays? In C, can you have arrays of any data type?
2. In C, what is the index of the first element in an array?
3. What does the name of the array signify?
4. Can array indexes be negative?
5. Illustrate the initialization of a one dimensional array with an example.
6. Illustrate the initialization of a two dimensional array with an example.
7. Show the storage of a two dimensional array in memory with the help of a diagram.
8. Write a program to determine whether a matrix singular or not (solution 4).
9. Write a program to find the inverse of a square matrix (solution 5).
10. Write a program to test for the orthogonality of a square matrix (solution 6).
11. Write a program to maintain a circular queue in an array (solution 7).
12. Implement the following sorting techniques:
(i) bubble sort (solution 8)
(ii) selection sort (solution 9)
(iii) merge sort (solution 10)
(iv) quick sort (solution 11)
(v) heap sort (solution 12)
13. Write a program to find the minimum cost spanning tree by using:
(i) Prim’s algorithm (solution 13)
(ii) Krushkal’s algorithm (solution 14).
14. Solve the 8 queens problem using backtracking (solution 15).
15. Write a program to perform polynomial addition (solution 29).
16. What is the null character and what is it used for, in the context of strings?
17. Point out the difference between:
(i) strcat and strncat
(ii) strcmp and strncmp
18. Write the name of the function in string.h which:
(i) performs case insensitive string comparison
(ii) searches for a character inside a string
(iii) searches for a string inside another string.
19. What happens if the total size of the string after strcat becomes greater than the array size of the string used to hold the concatenated string? Does the compiler report an error?
20. Write a program to concatenate two strings (solution 1).
21. Write a program to count the number of vowels, consonants and spaces in a line (solution 2).





EXAMAPERS123.BLOGSPOT.COM


Tuesday, October 26, 2010

INFOSYS PLACEMENT PAPER





INFOSYS PLACEMENT PAPER ON 10 th SEPTEMBER2006 AT CHENNAI :





SUCCESS FOR CAREER

INFOSYS PLACEMENT PAPER 
Exercise 1:
The passage given below is followed by questions based on its content. Read the passage & choose the best answer 4 the questions
The Death Car
It was cold night in September. The rain was drumming on the car roof as George & Marie Winston drove through the empty country roads towards the house of their friends, the Harrison’s, where they were going to attend a party to celebrate the engagement of the Harrison’s daughter, Lisa. As they drove, they listened to the local radio station, which was playing classical music. They were about 5 miles from the destination when the music on the radio was interrupted by a news announcement: “The Cheshire police have issued a serious warning after a man escaped from Colford Mental Hospital earlier this evening. The man, John Downey, is murderer who killed 6 people before he was captured 2 years ago. He is described as large, very strong & extremely dangerous. People in the Cheshire area are warned to keep their doors & windows locked, & to call the police immediately if they se anyone acting strangely.” Marie shivered, “A crazy killer. And he’s out there somewhere. That’s scary.” Don’t worry about it,” said her husband. “We’re nearly there now. Anyway, we have more important things to worry about. This car is losing power for some reason—it must be that old problem with the carburetor, If it gets any worse, we’ll have to stay at the Harrison’s’ tonight & get it fixed before we travel back tomorrow,” As he spoke, the car began to slow down, George pressed the accelerator, but the engine only coughed. Finally they rolled to a halt, as the engine died completely, Just as they stopped, George pulled the car off the road, & it came to rest under a large tree. “Blast!” said George angrily. “Now we’ll have to walk in the rain.” “But that’ll take us an hour at least,” said Marie. “And I have my high-held shoes & my nice clothes on. They’ll be ruined!” “Well, you’ll have to wait while I run to the nearest house & call the Harrison’s. Someone can come out & picks us up,” said George. “But George! Have you forgotten what the radio said? There’s a homicidal maniac out there! You can’t leave me alone here!” “You’ll have to hide in the back of the car. Lock all the doors & lie on the floor in the back, under this blanket. No-one will see you, when I come back, I’ll knock 3 times on the door. Then you can get up & open it. Don’t open it unless you here 3 knocks.” George opened the door & slipped out into the rain. He quickly disappeared into the blackness. Marie quickly locked the doors & settled down under the blanket in the back for a long wait. She was frightened & worried, but she was a strong-minded woman. She had not been waiting long, however, when she heard a strange scratching noise. It seemed to be coming from the roof of the car. Marie was terrified. She listened, holding her breath. Then she heard 3 slow knocks, one after the other, also on the roof of the car. Was it her husband? Should she open the door? Then she heard another knock, and another. This was not her husband. It was somebody--or something--else. She was shaking with fear. But she forced herself to lie still. The knocking continued-- bump, bump, bump, bump many hours later, as the sun rose, she was still lying there. She had not slept for a moment. The knocking had never stopped, all night long. She did not know what to do. Where was George? Why had he not come for her?
Suddenly, she heard the sound of 3 or 4 vehicles, racing quickly down the road. All of them pulled up around her, their tires screeching on the road. At last! Some one had come! Marie sat up quickly & looked out the window.
The 3 vehicles were all police cars, & 2 still had their lights flashing. Several policemen leap out. One of them rushed towards the car as Marie opened the door. He took her by the hand.
“Get out of the car & walk with me to the police vehicle. Miss. You’re safe now. Look straight ahead. Keep looking at police car. Don’t look back. Just don’t look back.”
Something in the way he spoke filled Marie with cold horror. She could not help herself. After 10 yards from the police car, she stopped, turned & looked back at the empty vehicle.
George was hanging from the tree above the car, a rope tied around his neck. As the wind blew his body back & forth, his feet were bumping gently on the roof of the car-- bump, bump, bump, bump

1) What was the reason for the news announcement on the radio?
a) 6 people. Including John Downey, had been murdered?
b) A dangerous prisoner had escaped
c) The police were warning of accidents on the roads in the bad weather
d) Some people had bens en acting strangely in the Cheshire area

2) What did George think was causing trouble with the car?
a) The carburetor
b) The rain drumming on the roof
c) The accelerator
d) He had no idea

3) Why did he pull the car off the road?
a) To have a rest
b) To go for a walk
c) To walk to the nearest house
d) It broke down

4) Why did Marie stay in the car when George left?
a) She was afraid to go out in the dark
b) So no one could steel the car
c) Her clothes weren’t suitable for the rain
d) She wanted to get some sleep

5) Where did George set off to walk?
a) The mental hospital
b) The nearest house
c) The Harrison’s house
d) The police station

6) What made Marie as frightened as she waited in the car?
a) There was a strange sound coming from the roof
b) She could see a man strangely outside the car
c) Some police cars came racing down the road
d) She was afraid of the rain and the dark

Exercise 2:
Each sentence below has 1 or 2 blanks – each blank indicating that something has been omitted. Beneath the sentence are some words. Choose the word for each blank that best fits the meaning of the sentence as a whole

7) Athletes have so perfected their techniques in track and field events that the _________ becomes _________ before record books
a) Announcement …………public
b) Meet…………………….official
c) Time…………………….authentic
d) Fantastic………………...common place

8) A________ child, she was soon bored in class; she already knew more mathematics than her junior school teachers
a) Obdurate
b) Precocious
c) Recalcitrant
d) Contemporary

9) The subtle shades of meaning, & still subtler echoes of association, make language an instrument which scarcely anything short of genius can wield with ____________ & ________________
a) Confidence----------aloofness
b) Definiteness---------certainty
c) Sincerity--------------hope
d) Eloquence------------ruthlessness

10) Unwilling to admit that they had been in error, the researchers tried to_______ tried case with more data obtained from dubious sources
a) Ascertain
b) Buttress
c) Refute
d) Dispute

11) His one vice was gluttony & so it is not surprising that as he aged he became increasingly_______________
a) Despondent
b) Corpulent
c) Carping
d) Lithe
Exercise 3:
Please read all the questions in the table below (12-21) as one continuous passage. Tick the verb with right tense or the correct word to fill in the gaps in each of the sentences.

Statement Options
12) A famous singer had been contracted to sign at a Paris opera house & ticket sales_______________ booming. a) is
b) are
c) were
d) have been
13) In fact, the night of the concert, the house was packed; every ticket ________________ a) is selling
b) was selling
c) sold
d) had been sold

14) The feeling of anticipation & excitement was in the air as the house manager__________ the stage & said, “Ladies & gentlemen, thank you for your enthusiastic support! a) took
b) takes
c) had taken
d) was taking
15) I am afraid that due to illness, the man whom you’ve all come to hear________________ performing tonight a) will not be
b) has not been
c) had not been
d) was not
16) However, we _________ a suitable substitute who, we hope, will provide you with comparable entertainment.” a) are finding
b) were finding
c) had found
d) have found
17) The crowd____________ in disappointment & failed to hear the announcer mention the stand-in’s name a) groans
b) groaned
c) had groaned
d) were groaning

18) The environment turned from excitement to frustration
The stand-in performer__________ the performance everything he had. a) will give
b) had given
c) gave
d) gives
19) When he had finished, there was nothing but an uncomfortable silence. No one _____________ a) Applauded
b) Applauds
c) Was applauding
d) Has applauded
20) Suddenly, from the balcony, a little boy stood up and____________, “Daddy, I think you’re wonderful!” a)shouts
b) was shouting
c) had shouted
d) shouted
21) The crowd_________________ into thunderous applause a) breaks
b) broke
c) had broken
d) was breaking
Exercise 4:
From each group of sentences given below, indicate the sentence that contains the error:

22) Group 1
a) Driving long distances causes’ sleepiness & sleepiness causes serious accidents.
b) On a table at the rear of the room were a notebook, a pair of scissors, & biology textbook
c) Finally, there seems to be a growing interest in vegetarianism in this country
d) Either the local chief of police or his officers are guilty of violating the rights of prisoners

23) Group 2
a) Simple cookbooks for inexperienced cooks have become quite popular in recent years they are available at many bookstores
b) Some cookbooks, such as The Joy of cooking, have been classics for generations
c) One popular cookbook is The Art of French Cooking, by Julia Child, a colorful character who charmed television audiences for many years
d) The Art of French Cooking blends classic recipes with meticulous explanation; ordinary cooks find the recipes manageable

24) Group 3
a) Around 50% of the forest is destroyed every year
b) The bus leaves tomorrow morning
c) A tiger is a dangerous animal
d) Can you please the sugar?

25) Group 4
a) There must be some mistake. I should have scored more marks
b) The number of trainees is hundred
c) 50% of the houses need repairs
d) The Commissioner, along with his family members was seen the party

26) Group 5
a) The scissors is very sharp
b) Congratulations are in order
c) One of the cases is open
d) She plays tennis well but she’ll never be a Steffi Graf

Exercise 5:
Please mark the correct statement from the pairs given below:

27) Pair 1
a) Repeated occurrences cannot be ignored
b) Repeated occurrences cannot be ignored

28) Pair 2
a) We need to get a consensus on the decision
b) We need to get a consensus on the decision

29) Pair 3
a) Only authority personnel are allowed in this area
b) Only authorized personnel are allowed in this area

30) Pair 4
a) The actress decided to sue the sleazy tabloid for deformation of her character
b) The actress decided to sue the sleazy tabloid for defamation of her character

31) Pair 5
a) Everyone knows that Hogwarts in the Harry Potter series is a mythical school
b) Everyone knows that Hogwarts in the Harry Potter series is a legendary school

32) Pair 6
a) Most people think caffeine is not good for health
b) Most people think caffeine is not good for health

Exercise 6:
Select the best word/phrase/line to complete each sentence in the most appropriate manner

33) ‘Reema’s bad-mouthing Peter only because she is jealous of him.’ Means______________
a) Peter really is a nice person
b) Peter really is a mean person
c) Peter really is a difficult person
d) Peter really is a tough person

34) If some one is “gung ho”, they are_______
a) stupid
b) Childish
c) Enthusiastic
d) Loud

35) Mr. Hughes has been asked to___________ this difficult project because of his experience working for many years in Iran
a) Undergo
b) Understand
c) Undervalue
d) Undertake

36) ‘Stop talking to those angry men, you are just adding fuel to the fire’ is the same as________
a) Stop talking to those angry men, you are just coming in the way
b) Stop talking to those angry men, you are just making it worse
c) Stop talking to those angry men, you are just adding to the noise
d) Stop talking to those angry men, you are just talking too much

37) ‘Sudhir’s work is behind schedule – I think he bit more than he could chew’ is the same as________
a) Sudhir has taken too much of work
b) Sudhir takes very long breaks
c) Sudhir does not know how to do the work
d) Sudhir is a lazy person

38) There are many__________ to our rules, and I do not think that’s fair.
a) Examples
b) exceptions
c) Instances
d) provisions
Exercise 7:
Choose the correct / most appropriate word/s to fill in the gap in the sentences given below.

39) I didn’t set _________ to do this but I’m pleased with the result.
a) in
b) out
c) on
d) down

40) This looks too heavy,______________ pick it up?
a) Can I
b) may I
c) need I
d) would I

41) I am glad so many people have passed the test. In fact, there were_________ who haven’t.
a) little
b) a little
c) few
d) a few

42) Pope John Paul II ___________ more than 90 countries.
a) has visited
b) was visited
c) visits
d) has been visiting

43) I _____________ Carl since I ______________ a little child.
a) have known, have been
b) have known, was
c) knew, have been
d) knew, was

44) I wonder if _____________ will show up at the meeting?
a) someone
b) anyone
c) one
d) everyone

45) Have you given up______________.
a) to smoke
b) smoke
c) some smoking
d) smoking




EXAMAPERS123.BLOGSPOT.COM