Está en la página 1de 54

ARRAYS

1. What is an array? How to declare and initialize arrays? Explain with examples
Ans: Array:-
An array is defined as an ordered set of similar data items. All the data items of an
array are stored in consecutive memory locations in RAM. The elements of an array
are of same data type and each item can be accessed using the same name.

Declaration of an array:- We know that all the variables are declared before they are
used in the program. Similarly, an array must be declared before it is used. During
declaration, the size of the array has to be specified. The size used during declaration
of the array informs the compiler to allocate and reserve the specified memory
locations.

Syntax:- data_type array_name[n];


where, n is the number of data items (or) index(or) dimension.
0 to (n-1) is the range of array.
Ex: int a[5];

float x[10];
Initialization of Arrays:-
We can initialize the elements of arrays in the same way as the ordinary variables
when they are declared.

The general form of initialization of arrays is

type array-name[size]={ list of values};

Initializing all specified memory locations:- Arrays can be initialized at the time of
declaration when their initial values are known in advance. Array elements can be
initialized with data items of type int, char etc.

Ex:- int a[5]={10,15,1,3,20};


During compilation, 5 contiguous memory locations are reserved by the compiler for the
variable a and all these locations are initialized as shown below

1
int a[3]={9,2,4,5,6};//error: no. of initial vales are more than the size of array.

2. How can we declare and initialize 2D arrays? Explain with examples.


Ans: An array consisting of two subscripts is known as two-dimensional array. These
are often known as array of the array. In two dimensional arrays the array is divided
into rows and columns. These are well suited to handle a table of data. In 2-D array
we can declare an array as :

Declaration:-
Syntax: data_type array_name[row_size][column_size];

Ex:- int arr[3][3];


where first index value shows the number of the rows and second index value shows
the number of the columns in the array.

Initializing two-dimensional arrays:


Like the one-dimensional arrays, two-dimensional arrays may be initialized by
following their declaration with a list of initial values enclosed in braces.

Ex: int a[2][3]={0,0,0,1,1,1}; initializes the elements of the first row to zero and the
second row to one. The initialization is done row by row.

The above statement can also be written as


int a[2][3] = {{ 0,0,0},{1,1,1}};
by surrounding the elements of each row by braces.
We can also initialize a two-dimensional array in the form of a matrix as shown

below int a[2][3]={ {0,0,0}, {1,1,1} };

When the array is completely initialized with all values, explicitly we need not

specify the size of the first dimension.

Ex: int a[ ] [ 3 ]={ {0,2,3}, {2,1,2} };

2
If the values are missing in an initializer, they are automatically set to zero.

Ex: int a[2][3]={ {1,1}, {2} };


Will initialize the first two elements of the first row to one, the first element of the second
row to two and all other elements to zero.

3. Explain how two dimensional arrays can be used to represent

matrices. (or) Define an array and how the memory is allocated

for a 2D array?

Ans: These are stored in the memory as given below.


Row-Major order Implementation

Column-Major order Implementation

In Row-Major Implementation of the arrays, the arrays are stored in the memory in
terms of the row design, i.e. first the first row of the array is stored in the memory then
second and so on. Suppose we have an array named arr having 3 rows and 3 columns
then it can be stored in the memory in the following manner :

int arr[3][3];

arr[0][0] arr[0][1] arr[0][2]

arr[1][0] arr[1][1] arr[1][2]

arr[2][0] arr[2][1] arr[2][2]

Thus an array of 3*3 can be declared as follows :


arr[3][3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
and it will be represented in the memory with row major implementation as follows :

3
1 2 3 4 5 6 7 8 9

In Column-Major Implementationof the arrays, the arrays are stored in the memory in
the term of the column design, i.e. the first column of the array is stored in the memory
then the second and so on. By taking above eg. we can show it as follows :

arr[3][3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
and it will be represented in the memory with column major implementation as follows :

1 4 7 2 5 8 3 6 9

Two-dimensional arrays of variable length


An array consisting of two subscripts is known as two-dimensional array. These are often
known as array of the array. In two dimensional arrays the array is divided into rows and
columns,. These are well suited to handle the table of data. In 2-D array we can declare
an array as :

Declaration:-
Syntax: data_type array_name[row_size][column_size];
Ex: int arr[3][3] ;
Where first index value shows the number of the rows and second index value shows the
no. of the columns in the array.

These are stored in the memory as given below.

arr[0][0] arr[0][1] arr[0][2]

arr[1][0] arr[1][1] arr[1][2]

arr[2][0] arr[2][1] arr[2][2]

4
Initialization :-
To initialize values for variable length arrays we can use scanf statement and loop
constructs.
Ex:-
for (i=0 ; i<3; i++)
for(j=0;j<3;j++)
scanf(%d,&arr[i][j]);

4. Define multi-dimensional arrays? How to declare multi-dimensional arrays?

Ans: Multidimensional arrays are often known as array of the arrays. In


multidimensional arrays the array is divided into rows and columns, mainly while
considering multidimensional arrays we will be discussing mainly about two dimensional
arrays and a bit about three dimensional arrays.

Syntax: data_type array_name[size1][size2][size3]------[sizeN];


In 2-D array we can declare an array as :
int arr[3][3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

where first index value shows the number of the rows and second index value shows the
number of the columns in the array. To access the various elements in 2-D array we can
use:

printf("%d", a[2][3]);
/* output will be 6, as a[2][3] means third element of the second row of the array */
In 3-D we can declare the array in the following manner :
int arr[3][3][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,

16, 17, 18,19, 20, 21,22, 23, 24,25, 26, 27 };

5
/* here we have divided array into grid for sake of convenience as in above
declaration we have created 3 different grids, each have rows and columns */
If we want to access the element the in 3-D array we can do it as follows :
printf("%d",a[2][2][2]);
/* its output will be 26, as a[2][2][2] means first value in [] corresponds to the grid no.
i.e. 3 and the second value in [] means third row in the corresponding grid and last []
means third column */

Ex:-
int arr[3][5][12];
float table[5][4][5][3];
arr is 3D array declared to contain 180 (3*5*12) int type elements. Similarly table is a 4D
array containing 300 elements of float type.

5. Write a program to perform matrix

addition. Ans: /*ADDITION OF TWO

MATRICES*/

#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
int a[10][10],b[10][10],c[10][10];
int i,j,m,n,p,q;
printf("\n Enter the size of Matrix A:");
scanf("%d%d", &m,&n);
printf("\n Enter the size of Matrix B:");
scanf("%d%d", &p,&q);

6
if(m!=p || n!=q)
{ printf("Matrix addition not possible.");
exit(0); }
printf(" Enter the Matrix A values:\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf(" Enter the Matrix B values:\n");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf("%d",&b[i][j]);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
c[i][j]=a[i][j]+b[i][j];
printf("\n The Matrix A is\n");

for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf(" %d",a[i][j]);
printf("\n");
}
printf("\n The Matrix B is\n");
for(i=0;i<p;i++)
{ for(j=0;j<q;j++)
printf(" %d",b[i][j]);

7
printf("\n");
}
printf("\n The Output Matrix C is\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf(" %d",c[i][j]);
printf("\n");
} }
OUTPUT:

Enter the size of Matrix A:2


3
Enter the size of Matrix B:2
3
Enter the Matrix A values:
1

Enter the Matrix B values:

8
3

1
The Matrix A is
123
456
The Matrix B is
654
321
The Output Matrix C is
777
777

6. Write a program to perform matrix


multiplication Ans: /*MATRIX
MULTIPLICATION*/
#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
int a[10][10],b[10][10],c[10][10];
int i,j,k,m,n,p,q;
printf("\ Enter the size of Matrix A:");
scanf("%d%d", &m,&n);
printf("\ Enter the size of Matrix B:");
scanf("%d%d", &p,&q);

9
if(n!=p)
{
printf("Matrix Multiplication not possible.");
exit(0);
}
printf(" Enter the Matrix A values:\n");

for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf(" Enter the Matrix B values:\n");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf("%d",&b[i][j]);
for(i=0;i<m;i++)
for(j=0;j<q;j++)
{ c[i][j]=0;

for(k=0;k<n;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j]; }
printf("\n The Matrix A is\n");
for(i=0;i<m;i++)
{ for(j=0;j<n;j++)
printf(" %d",a[i][j]);
printf("\n"); }
printf("\n The Matrix B is\n");

10
for(i=0;i<p;i++)
{ for(j=0;j<q;j++)
printf(" %d",b[i][j]);
printf("\n"); }
printf("\n The Output Matrix C is\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
printf(" %d",c[i][j]);
printf("\n");
}
}
OUTPUT:
Enter the size of Matrix A:2
3

Enter the size of Matrix B:3


2
Enter the Matrix A values:

2
2

2
2
2

11
2

Enter the Matrix B values:


3
3
3
3
3
3

The Matrix A is
222
222

The Matrix B is
33
33
33

The Output Matrix C is

15 15

15 5

12
Strings
7. Define C string? How to declare and initialize C strings with an

example? Ans: C Strings:-

In C language a string is group of characters (or) array of characters, which is terminated


by delimiter \0 (null). Thus, C uses variable-length delimited strings in programs.

Declaring Strings:-
C does not support string as a data type. It allows us to represent strings as character
arrays. In C, a string variable is any valid C variable name and is always declared as an
array of characters.

Syntax:- char string_name[size];


The size determines the number of characters in the string name.
Ex:- char city[10];
char name[30];
Initializing strings:-
There are several methods to initialize values for string variables.

Ex:- char city[8]=NEWYORK;


char city[8]={N,E,W,Y,O,R,K,\0};

The string city size is 8 but it contains 7 characters and one character space is for NULL
terminator.

Storing strings in memory:-


In C a string is stored in an array of characters and terminated by \0 (null).

13
A string is stored in array, the name of the string is a pointer to the beginning of the
string.
The character requires only one memory location.
If we use one-character string it requires two locations. The difference is shown below,
The difference between array and string is shown below,

Because strings are variable-length structure, we must provide enough room for
maximum-length string to store and one byte for delimiter.

Why do we need null?


A string is not a datatype but a data structure. String implementation is logical not
physical. The physical structure is array in which the string is stored. The string is
variable-length, so we need to identify logical end of data in that physical structure.

String constant (or) Literal:-


String constant is a sequence of characters enclosed in double quotes. When string
constants are used in C program, it automatically initializes a null at end of string.

Ex:- Hello Welcome Welcome to C Lab

8. Explain about the string Input/ Output functions with

example? Ans: Reading and Writing strings:-

C language provides several string handling functions for input and output.

14
String Input/Output Functions:-
C provides two basic methods to read and write strings. Using formatted input/output
functions and using a special set of functions.

Reading strings from terminal:-


(a) formatted input function:- scanf can be used with %s format specification to read a
string.

Ex:- char name[10];


scanf(%s,name);
Here dont use & because name of string is a pointer to array. The problem with
scanf is that it terminates its input on the first white space it finds.

Ex:- NEW YORK


Reads only NEW (from above example).
(b) Unformatted input functions:-

(1) getchar():- It is used to read a single character from keyboard. Using this function
repeatedly we may read entire line of text

Ex:- char
ch=z;
ch=getch
ar();

(2) gets():- It is more convenient method of reading a string of text including blank
spaces.

Ex:- char

line[100];

gets(line);

Writing strings on to the screen:-


(1) Using formatted output functions:- printf with %s format specifier we can print
strings in different formats on to screen.

15
Ex:- char name[10];
printf(%s,name);
Ex:- char name[10];
printf(%0.4,name);

/* If name is JANUARY prints only 4 characters ie., JANU */

Printf(%10.4s,name);

printf(%-10.4s,name);

(2) Using unformatted output functions:-

(a) putchar():- It is used to print a character on the screen.

Ex:- putchar(ch);

(b) puts():- It is used to print strings including blank spaces.

Ex:- char line[15]=Welcome to lab;


puts(line);

9. Explain about the following string handling functions with example programs.
(i) strlen (ii) strcpy (iii) strcmp (iv) strcat
Ans:
C supports a number of string handling functions. All of these built-in functions are
aimed at performing various operations on strings and they are defined in the header
file string.h.

16
(i). strlen( )
This function is used to find the length of the string excluding the NULL character. In
other words, this function is used to count the number of characters in a string. Its
syntax is as follows:
Int strlen(string);

Example: char str1[ ] = WELCOME;


int n;
n = strlen(str1);

/* A program to calculate length of string by using strlen() function*/


#include<stdio.h>
#include<string.h>
Void main( )
{
char string1[50];
int length;
printf(\n Enter any string:);

gets(string1);
length=strlen(string1);
printf(\n The length of string=%d,length);
}
(ii). strcpy( )
This function is used to copy one string to the other. Its syntax is as follows:
strcpy(string1,string2);

where string1 and string2 are one-dimensional character arrays.

17
This function copies the content of string2 to string1.
E.g., string1 contains master and string2 contains madam, then string1 holds
madam after execution of the strcpy (string1,string2) function.

Example: char str1[ ] = WELCOME;


char str2[ ] =HELLO;
strcpy(str1,str2);
/* A program to copy one string to another using strcpy() function */
#include<stdio.h>
#include<string.h>
Void main( )
{
char string1[30],string2[30];
printf(\n Enter first string:);
gets(string1);
printf(\n Enter second string:);
gets(string2);
strcpy(string1,string2);
printf(\n First string=%s,string1);
printf(\n Second string=%s,string2);
}

(iii). strcmp ( )
This function compares two strings character by character (ASCII comparison) and
returns one of three values {-1,0,1}. The numeric difference is 0 if strings are equal .If
it is negative string1 is alphabetically above string2 .If it is positive string2 is
alphabetically above string1.

Its syntax is as follows:

18
Int strcmp(string1,string2);

Example: char str1[ ] = ROM;


char str2[ ] =RAM;
strcmp(str1,str2);
(or)
strcmp(ROM,RAM);
/* A program to compare two strings using strcmp() function */
#include<stdio.h>
#include<string.h>
Void main()
{
char string1[30],string2[15];
int x;
printf(\n Enter first string:);
gets(string1);
printf(\n Enter second string:);
gets(string2);
x=strcmp(string1,string2);
if(x==0)
printf(\n Both strings are equal);
else if(x>0)
printf(\n First string is bigger);
else
printf(\n Second string is bigger); }
(iv). strcat ( )

19
This function is used to concatenate two strings. i.e., it appends one string at the end of
the specified string. Its syntax as follows:
strcat(string1,string2);

where string1 and string2 are one-dimensional character arrays.


This function joins two strings together. In other words, it adds the string2 to
string1 and the string1 contains the final concatenated string. E.g., string1 contains prog
and string2 contains ram, then string1 holds program after execution of the strcat()
function.

Example: char str1[10 ] = VERY;


char str2[ 5] =GOOD;
strcat(str1,str2);
/* A program to concatenate one string with another using strcat() function*/
#include<stdio.h>
#include<string.h>
Void main()
{
char string1[30],string2[15];
printf(\n Enter first string:);
gets(string1);
printf(\n Enter second string:);
gets(string2);
strcat(string1,string2);
printf(\n Concatenated string=%s,string1); }

20
Pointers
A pointer is a variable whose value is the address of another variable, i.e., direct address
of the memory location. Like any variable or constant, you must declare a pointer before
using it to store any variable address. The general form of a pointer variable declaration
is

Syntax: type *var-name;

Here, type is the pointer's base type; it must be a valid C data type and var-name is the
name of the pointer variable. The asterisk * used to declare a pointer is the same asterisk
used for multiplication. However, in this statement the asterisk is being used to designate
a variable as a pointer. Take a look at some of the valid pointer declarations

Examples:

int *ip; /* pointer to an integer */

double *dp; /* pointer to a double */

float *fp; /* pointer to a float */

char *ch /* pointer to a character */

Picture for how pointer variable stores address of the variable

How to Use Pointers?


There are a few important operations, which we will do with the help of pointers very
frequently. (a) We define a pointer variable, (b) assign the address of a variable to a
pointer and (c) finally access the value at the address available in the pointer variable.

21
This is done by using unary operator * that returns the value of the variable located at the
address specified by its operand. The following example makes use of these operations

#include <stdio.h>

int main ( )
{

int var = 20; /* actual variable declaration */


int *ip; /* pointer variable declaration */

ip = &var; /* store address of var in pointer variable*/

printf("Address of var variable: %x\n", &var );

/* address stored in pointer variable */


printf("Address stored in ip variable: %x\n", ip );

/* access the value using the pointer */


printf("Value of *ip variable: %d\n", *ip );

return 0;
}

When the above code is compiled and executed, it produces the following result
Output:
Address of var variable: bffd8b3c
Address stored in ip variable: bffd8b3c
Value of *ip variable: 20

NULL Pointers
It is always a good practice to assign a NULL value to a pointer variable in case you do
not have an exact address to be assigned. This is done at the time of variable declaration.
A pointer that is assigned NULL is called a nullpointer.
The NULL pointer is a constant with a value of zero defined in several standard libraries.
Consider the following program
#include <stdio.h>

22
int main ( )
{
int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr );

return 0;
}
When the above code is compiled and executed, it produces the following result
The value of ptr is 0
In most of the operating systems, programs are not permitted to access memory at
address 0 because that memory is reserved by the operating system. However, the
memory address 0 has special significance; it signals that the pointer is not intended to
point to an accessible memory location. But by convention, if a pointer contains the null
(zero) value, it is assumed to point to nothing.
To check for a null pointer, you can use an 'if' statement as follows
if(ptr) /* succeeds if p is not null */
if(!ptr) /* succeeds if p is null */
Pointers in Detail
Pointers have many but easy concepts and they are very important to C programming.
The following important pointer concepts should be clear to any C programmer

S.N. Concept & Description

1 Pointer arithmetic
There are four arithmetic operators that can be used in pointers: ++, --, +, -

2 Array of pointers
You can define arrays to hold a number of pointers.

3 Pointer to pointer
C allows you to have pointer on a pointer and so on.

4 Passing pointers to functions in C


Passing an argument by reference or by address enable the passed argument to
be changed in the calling function by the called function.

5 Return pointer from functions in C


C allows a function to return a pointer to the local variable, static variable, and

23
dynamically allocated memory as well.

#include<stdio.h>
#include<conio.h>

void main() {
int int_var = 10, *int_ptr;
char char_var = 'A', *char_ptr;
float float_val = 4.65, *float_ptr;

/* Initialize pointers */
int_ptr = &int_var;
char_ptr = &char_var;
float_ptr = &float_val;

printf("Address of int_var = %u\n", int_ptr);


printf("Address of char_var = %u\n", char_ptr);
printf("Address of float_var = %u\n\n", float_ptr);

/* Incrementing pointers */
int_ptr++;
char_ptr++;
float_ptr++;
printf("After increment address in int_ptr = %u\n", int_ptr);
printf("After increment address in char_ptr = %u\n", char_ptr);

24
printf("After increment address in float_ptr = %u\n\n", float_ptr);

/* Adding 2 to pointers */
int_ptr = int_ptr + 2;
char_ptr = char_ptr + 2;
float_ptr = float_ptr + 2;

printf("After addition address in int_ptr = %u\n", int_ptr);


printf("After addition address in char_ptr = %u\n", char_ptr);
printf("After addition address in float_ptr = %u\n\n", float_ptr);

getch();
return 0;
}

Output
Address of int_var = 2293300
Address of char_var = 2293299
Address of float_var = 2293292

After increment address in int_ptr = 2293304


After increment address in char_ptr = 2293300
After increment address in float_ptr = 2293296

After addition address in int_ptr = 2293312


After addition address in char_ptr = 2293302
After addition address in float_ptr = 2293304

Generic Pointers

When a variable is declared as being a pointer to type void it is known as a generic


pointer. Since you cannot have a variable of type void, the pointer will not point to any
data and therefore cannot be dereferenced. It is still a pointer though, to use it you just
have to cast it to another kind of pointer first. Hence the term Generic pointer.

This is very useful when you want a pointer to point to data of different types at different
times.

25
Here is some code using a void pointer:

generic_pointer.c

int
main()
{
int i;
char c;
void *the_data;

i = 6;
c = 'a';

the_data = &i;
printf("the_data points to the integer value %d\n", *(int*) the_data);

the_data = &c;
printf("the_data now points to the character %c\n", *(char*) the_data);

return 0; }

C programming allows passing a pointer to a function. To do so, simply declare


the function parameter as a pointer type.

Following is a simple example where we pass an unsigned long pointer to a function and
change the value inside the function which reflects back in the calling function

#include <stdio.h>
#include <time.h>
void getSeconds(unsigned long *par);
int main ( )
{

unsigned long sec;


getSeconds( &sec );

/* print the actual value */


printf("Number of seconds: %ld\n", sec );

26
return 0;
}

void getSeconds(unsigned long *par) {


/* get the current number of seconds */
*par = time( NULL );
return;
}
When the above code is compiled and executed, it produces the following result
Number of seconds :1294450468
The function, which can accept a pointer, can also accept an array as shown in the
following example
#include <stdio.h>

/* function declaration */
double getAverage(int *arr, int size);

int main ( )
{
/* an int array with 5 elements */
int balance[5] = {1000, 2, 3, 17, 50};
double avg;

/* pass pointer to the array as an argument */


avg = getAverage( balance, 5 ) ;

/* output the returned value */


printf("Average value is: %f\n", avg );
return 0;
}

double getAverage(int *arr, int size)


{

int i, sum = 0;
double avg;

27
for (i = 0; i < size; ++i) {
sum += arr[i];
}

avg = (double)sum / size;


return avg;
}

When the above code is compiled together and executed, it produces the following result

Average value is: 214.40000

Pointers and Arrays

Arrays are closely related to pointers in C programming but the important difference
between them is that, a pointer variable takes different addresses as value whereas, in
case of array it is fixed.
This can be demonstrated by an example:
#include <stdio.h>
int main()
{ char charArr[4];
int i;
for(i = 0; i < 4; ++i)
{ printf("Address of charArr[%d] = %u\n", i, &charArr[i]); }

28
return 0; }
When you run the program, the output will be:
Address of charArr[0] = 28ff44
Address of charArr[1] = 28ff45
Address of charArr[2] = 28ff46
Address of charArr[3] = 28ff47
Note: You may get different address of an array.
Notice, that there is an equal difference (difference of 1 byte) between any two
consecutive elements of array charArr.
But, since pointers just point at the location of another variable, it can store any address.

Relation between Arrays and Pointers


Consider an array:
int arr[4];

In C programming, name of the array always points to address of the first element of an
array.
In the above example, arr and &arr[0] points to the address of the first element.
&arr[0] is equivalent to arr
Since, the addresses of both are the same, the values of arr and &arr[0] are also the same.
arr[0] is equivalent to *arr (value of an address of the pointer)
Similarly,
&arr[1] is equivalent to (arr + 1) AND, arr[1] is equivalent to *(arr + 1).
&arr[2] is equivalent to (arr + 2) AND, arr[2] is equivalent to *(arr + 2).
&arr[3] is equivalent to (arr + 3) AND, arr[3] is equivalent to *(arr + 3).
..
&arr[i] is equivalent to (arr + i) AND, arr[i] is equivalent to *(arr + i).
In C, you can declare an array and can use pointer to alter the data of an array.
Example: Program to find the sum of six numbers with arrays and pointers

29
#include <stdio.h>
int main()
{
int i, classes[6],sum = 0;
printf("Enter 6 numbers:\n");
for(i = 0; i < 6; ++i)
{
// (classes + i) is equivalent to &classes[i]
scanf("%d",(classes + i));

// *(classes + i) is equivalent to classes[i]


sum += *(classes + i);
}
printf("Sum = %d", sum);
return 0;
}
Output
Enter 6 numbers: 2 3 4 5 3 4
Sum = 21

Difference between array and pointer in C/C++

Pointer Array
1. A pointer is a place in 1. An array is a single, pre
memory that keeps allocated chunk of
address of another place contiguous elements (all
inside of the same type), fixed in
size and location.
2. Pointer cant be 2. Array can be initialized
initialized at definition. at definition. Example
int num[] = { 2, 4, 5}
3. Pointer is dynamic in 3. They are static in
nature. The memory nature. Once memory is
allocation can be resized allocated , it cannot be
or freed later. resized or freed
dynamically.
4. The assembly code of 4. The assembly code of

30
Pointer is different than Array is different than
Array Pointer.

How to pass arrays to a function in C Programming?

In C programming, a single array element or an entire array can be passed to


a function. This can be done for both one-dimensional array or a multi-
dimensional array.

Passing One-dimensional Array In


Function
Single element of an array can be passed in similar
manner as passing variable to a function.
C program to pass a single element of an array to function
#include <stdio.h>
void display(int age)
{
printf("%d", age);
}

31
int main()
{
int ageArray[ ] = { 2, 3, 4 };
display(ageArray[2]); //Passing array element ageArray[2] only.
return 0;
}
Output
4

Passing an entire one-dimensional array to a


function
While passing arrays as arguments to the function, only the name of the array is passed
(,i.e, starting address of memory area is passed as argument).
C program to pass an array containing age of person to a function. This function
should find average age and display the average age in main function.
#include <stdio.h>
float average(float age[]);

int main()
{
float avg, age[ ] = { 23.4, 55, 22.6, 3, 40.5, 18 };
avg = average(age); /* Only name of array is passed as argument. */
printf("Average age=%.2f", avg);
return 0;
}

float average(float age[ ])


{
int i;
float avg, sum = 0.0;
for (i = 0; i < 6; ++i) {
sum += age[i];

32
}
avg = (sum / 6);
return avg;
}
Output
Average age=27.08

Structures
A structure allows you to wrap one or more variables that may be in different
data types into one. It can contain any valid data type like int ,char, float, array,
pointer or even structures. Each variable in the structure is called a structure
member.
Defining a structure
To define a structure, you use the struct keyword.

struct struct_name{ structure_member };


The following example defines the person structure:
struct person{
char first[32]; //first field an array of chars
char last[32]; //second field an array of chars
int age; //third field an int
};
Note that the above code is only defining a person structure. There are two
ways to declare a structure variable:
Declaring a structure
You can declare structure variables together with the structure defintion:
struct struct_name {
structure_member;
...
} instance_1,instance_2 instance_n;

33
Or, you can declare the structure variable after you define the structure:
struct struct_name instance_1,instance_2 instance_n;

keyword to create a synonym for a


Using typedef
For more concise code, you can use the typedef
structure. So when you want to create a strucuture variable, you can
omit the keyword struct.

typedef struct{
char first[32]; //first field an array of chars
char last[32]; //second field an array of chars }person;

person student;
person teacher;

Accessing a structure member


To access a structure member, we use the dot operator . (DOT operator )
between the structure name and member:

structure_name.structure_member
The following example demonstrates how to access the first name of
structure person:
person student;
student.first = "Richard";
We can also use the dot operator to access a nested structure and its members:
typedef struct{
person teacher[0];
person students[50];
}course;

34
course COMP2401;
COMP2401.students[0].first = "Richard";
Advantages of structures
Having a label that refers to the entire structure is convenient for two reasons.
First, it allows assignment statements between structure variables. This
allows you to copy data from one structure to another:
struct_intance1 = struct_intance2
Second, is passing a structure as a parameter to a function:
displayStudent(person info){
printf( %s %s: %d, info.first info.last, info.age);
}
Arrays and Structures
Just like you can have an array of any data type, you can have an array of structs.
typedef struct{

char first[32]; //first field an array of chars


char last[32]; //second field an array of chars
int age; //third field an int
}person;

person students[60]; //array of struct person


strcpy(students[0].first, Richard);

strcpy(students[0].last, Ison);
students[0].age = 19;

35
Pointers and Structures
The address of a structure variable can be stored in a pointer variable, just
like the address of any other type of variable.
struct fraction {
int x, y; };
struct fraction f[3], *g;
f[0].x=3;
f[0].y = 5;
g = &(f[0]);
There are two syntaxes to access the bytes of the structure using the
pointer variable.
(*g).x = 5;

g>y=11; //preferred syntax


A pointer variable for a structure can also be used to dynamically allocate memory.
g = (struct fraction *) malloc (sizeof(struct fraction));

Union
Definition
A union is a type of structure that can be used where the amount of memory used is a
key factor. Similarly to the structure the union can contain different types of data types.
Each time a new variable is initialized from the union it overwrites the previous and uses
that memory location. This is most useful when the type of data being passed through
functions is unknown, using a union which contains all possible data types can remedy
this problem.

Defining a Union
union person {
char name;
int age;
double height; };

36
Declaring a Union
Since the union is still a type of structure the method for declaring it is as follows:
union person {
char name;
int age;
double height;
} newPerson;
Or Person newPerson;
Initializing a Union

The process of initializing variables in a union is the same as a union but the results
are what make unions unique. The dot operator is still used in order to reach the data
types inside of the union.

Person newPerson;

newPerson.age = 20;

newPerson.height = 6.2;
Once the height variable is initialized the variable age is overwritten and no longer exists.

ENUM
Defining an Enumeration
An enumeration provides the data type with a set of values. An enumeration constant is a
type of an integer. A variable type takes and stores the values of the enumeration set
defined by that type. Enumerations can be used with indexing expressions also as
operands with arithmetic and relational operators. Enumerations can be also be used as an
alternate way to use #define.
An enumeration is a user-defined data type that consists of integral constants. To define
an enumeration, keyword enum is used.
enum flag { const1, const2, ..., constN };
Here, name of the enumeration is flag.
And, const1, const2,...., constN are values of type flag.

37
By default, const1 is 0, const2 is 1 and so on. You can change default values of enum
elements during declaration (if necessary).

// Changing default values of enum


enum suit {
club = 0,
diamonds = 10,
hearts = 20,
spades = 3};
Enumerated Type Declaration
When you create an enumerated type, only blueprint for the variable is created. Here's
how you can create variables of enum type.
enum boolean { false, true };
enum boolean check;
Here, a variable check of type enum boolean is created. Here is another way to declare
same check variable using different syntax.
enum boolean
{ false, true } check;
Example: Enumeration Type
#include <stdio.h>
enum week { sunday, monday, tuesday, wednesday, thursday, friday, saturday };
int main()
{
enum week today;
today = wednesday;
printf("Day %d",today+1);
return 0;

38
}
Output
Day 4
Advantages of Enumerations

1. Numeric values are automatically assigned

2. It allows your code to become generally understandable by others or yourself

3. Enums allow certain debuggers to print the values of an enumeration constant

File Handling in C Language


A file represents a sequence of bytes on the disk where a group of related data is
stored. File is created for permanent storage of data. It is a ready made structure.
In C language, we use a structure pointer of file type to declare a file.

FILE *fp;

C provides a number of functions that helps to perform basic file operations. Following
are the functions,

Function description

fopen() create a new file or open a existing file

fclose() closes a file

getc() reads a character from a file

putc() writes a character to a file

fscanf() reads a set of data from a file

fprintf() writes a set of data to a file

getw() reads a integer from a file

putw() writes a integer to a file

fseek() set the position to desire point

39
ftell() gives current position in the file

rewind() set the position to the begining point

Opening a File or Creating a File


The fopen() function is used to create a new file or to open an existing file.
General Syntax :
*fp = FILE *fopen(const char *filename, const char *mode);
Here filename is the name of the file to be opened and mode specifies the purpose of
opening the file. Mode can be of following types,
*fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or
created) file.

Reading and writing to a text file


For reading and writing to a text file, we use the functions fprintf() and fscanf().
They are just the file versions of printf() and scanf(). The only difference is that, fprint
and fscanf expects a pointer to the structure FILE.
Writing to a text file
Example 1: Write to a text file using fprintf()
#include <stdio.h>
int main()
{
int num;
FILE *fptr;
fptr = fopen("C:\\program.txt","w");

if(fptr == NULL)
{
printf("Error!");
exit(1);
}

printf("Enter num: ");


scanf("%d",&num);

fprintf(fptr,"%d",num);
fclose(fptr);

return 0;
}
This program takes a number from user and stores in the file program.txt.

40
After you compile and run this program, you can see a text file program.txt created in C
drive of your computer. When you open the file, you can see the integer you entered.

Closing a File
The fclose() function is used to close an already opened file.
General Syntax :
int fclose( FILE *fp );
Here fclose() function closes the file and returns zero on success, or EOF if there is an
error in closing the file. This EOF is a constant defined in the header file stdio.h.

File I/O Streams in C Programming Language :

1. In C all input and output is done with streams


2. Stream is nothing but the sequence of bytes of data

3. A sequence of bytes flowing into program is called input stream

4. A sequence of bytes flowing out of the program is called output stream

5. Use of Stream make I/O machine independent.

Predefined Streams :

stdin Standard Input

stdout Standard Output

stderr Standard Error

The Stream File


A very important concept in C is the stream. In C, the stream is a common, logical
interface to the various devices that comprise the computer. In its most common form,
a stream is a logical interface to a file. As C defines the term "file", it can refer to a
disk file, the screen, the keyboard, a port, a file on tape, and so on. Although files differ
in form and capabilities, all streams are the same. The stream provides a consistent
interface and to the programmer one hardware device will look much like another.

41
A stream is linked to a file using an open operation. A stream is disassociated from
a file using a close operation. The current location, also referred to as the current
position, is the location in a file where the next file access will occur. There are two
types of streams: text (used with ASCII characters some character translation takes
place, may not be one-to-one correspondence between stream and what's in the file)
and binary (used with any type of data, no character translation, one-to-one between
stream and file).

To open a file and associate it with a stream, use fopen(). Its prototype is shown
here: FILE *fopen(char *fname,char *mode);

The fopen() function, like all the file-system functions, uses the header stdio.h . The
name of the file to open is pointed to by fname (must be a valid name). The string
pointed at for mode determines how the file may be accesed as shown:

Mode Meaning
r Open a text file for reading
w Create a text file for writing
a Append to a text file
rb Open a binary file for reading
wb Open a binary file for writing
ab Append to a binary file
r+ Open a text file for read/write
w+ Create a text file for read/write
a+ Append or create a text file for
read/write
r+b Open a binary file for read/write
w+b Create a binary file for
read/write
a+b Append a binary file for
read/write

If the open operation is successful, fopen() returns a valid file pointer. The
type FILE is defined in stdio.h. It is a structure that holds various kinds of information
about the file, such as size.The file pointer will be used with all other functions that
operate on the file and it must never be altered or the object it points to.

42
If fopen() fails it returns a NULL pointer so this must always be checked for when
opening a file. For example:

FILE *fp;

if ((fp = fopen("myfile", "r")) ==NULL){

printf("Error opening file\n");

exit(1);

To close a file, use fclose(), whose prototype is

int fclose(FILE *fp);

The fclose() function closes the file associated with fp, which must be a valid file
pointer previously obtained using fopen(), and disassociates the streamfrom the file.
The fclose() function returns 0 if successful and EOF (end of file) if an error occurs.

Once a file has been opened, depending upon its mode, you may read and/or write
bytes to or from it using these two functions.

int fgetc(FILE *fp);

int fputc(int ch, FILE *fp);

The getc() function reads the next byte from the file and returns its as an integer and
if error occurs returns EOF. The getc() function also returns EOFwhen the end of file is
reached. Your routine can assign fget()'s return value to a char you don't have to
assign it to an integer.

The fput() function writes the bytes contained in ch to the file associated with fp as an
unsigned char. Although ch is defined as an int, you may call it using simply a char.
The fput() function returns the character written if successful or EOF if an error occurs.

TYPES OF FILES

43
There are 2 kinds of files in which data can be stored in 2 ways either in characters coded in
their ASCII character set or in binary format. They are
Text Files.
Binary Files
TEXT FILES
A Text file contains only the text information like alphabets ,digits and special symbols. The ASCII code of
these characters are stored in these files.It uses only 7 bits allowing 8 bit to be zero.
1.w(write):
This mode opens new file on the disk for writing.If the file exist,disk for writing.If the file exist, then it will
be over written without then it will be over written without any confirmation.
SYNTAX:

1 fp=fopen("data.txt","w");
2 "data.txt" is filename
3 "w" is writemode.
2. r (read)
This mode opens an preexisting file for reading.If the file doesnt Exist then the compiler
returns a NULL to the file pointer
SYNTAX:
fp=fopen("data.txt","r");
3. w+(read and write)
This mode searches for a file if it is found contents are destroyed If the file doesnt found
a new file is created.
SYNTAX:
fp=fopen("data.txt","w+");
4.a(append)
This mode opens a preexisting file for appending the data.
SYNTAX:
fp=fopen("data.txt","a");

5.a+(append+read)

44
the end of the file.
SYNTAX:
fp=fopen("data.txt","a+");
6.r+ (read +write)
This mode is used for both Reading and writing

BINARY FILES
A binary file is a file that uses all 8 bits of a byte for storing the information .It is the form
which can be interpreted and understood by the computer.
The only difference between the text file and binary file is the data contain in text file can
be recognized by the word processor while binary file data cant be recognized by a word
processor.
1.wb(write)
this opens a binary file in write mode.
SYNTAX:
fp=fopen(data.dat,wb);
2.rb(read)
this opens a binary file in read mode
SYNTAX:
fp=fopen(data.dat,rb);
3.ab(append)
this opens a binary file in a Append mode i.e. data can be added at the end of file.
SYNTAX:
fp=fopen(data.dat,ab);
4.r+b(read+write)
this mode opens preexisting File in read and write mode.
SYNTAX:
fp=fopen(data.dat,r+b);
5.w+b(write+read)

45
this mode creates a new file for reading and writing in Binary mode.
SYNTAX:
fp=fopen(data.dat,w+b);
6.a+b(append+write)
this mode opens a file in append mode i.e. data can be written at the end of file.
SYNTAX:
fp=fopen(data.dat,a+b);

Random Access To File


There is no need to read each record sequentially, if we want to access a particular
record.C supports these functions for random access file processing.
1. fseek()
2. ftell()
3. rewind()
1. fseek():
This function is used for seeking the pointer position in the file at the specified byte.
Syntax: fseek( file pointer, displacement, pointer position);
Where
file pointer ---- It is the pointer which points to the file.
displacement ---- It is positive or negative.This is the number of bytes which are skipped
backward (if negative) or forward( if positive) from the current position.This is attached
with L because this is a long integer.
Pointer position:
This sets the pointer position in the file.

Value pointer position


0 Beginning of file.
1 Current position

46
2 End of file

Ex:
1) fseek( p,10L,0)

0 means pointer position is on beginning of the file,from this statement pointer position is
skipped 10 bytes from the beginning of the file.

2)fseek( p,5L,1)

1 means current position of the pointer position.From this statement pointer position is
skipped 5 bytes forward from the current position.

3)fseek(p,-5L,1)

From this statement pointer position is skipped 5 bytes backward from the current
position.

2. ftell()
This function returns the value of the current pointer position in the file.The value is
count from the beginning of the file.
Syntax: ftell(fptr);
Where fptr is a file pointer.
rewind()
This function is used to move the file pointer to the beginning of the given file.
Syntax: rewind( fptr);

47
Where fptr is a file pointer.

Example program for fseek():


Write a program to read last n characters of the file using appropriate file
functions(Here we need fseek() and fgetc()).

#include<stdio.h>

#include<conio.h>

void main()

FILE *fp;

char ch;

clrscr();

fp=fopen("file1.c", "r");

if(fp==NULL)

printf("file cannot be opened");

else

{
printf("Enter value of n to read last n characters");
scanf("%d",&n);

fseek(fp,-n,2);

while((ch=fgetc(fp))!=EOF)

printf("%c\t",ch);

48
}

fclose(fp);

getch();

OUTPUT: It depends on the content in the file.


3. rewind()
The C library function void rewind(FILE *stream) sets the file position to the beginning of
the file of the given stream.
Declaration :Void rewind(FILE *stream)
Example
The following example shows the usage of rewind() function.
#include <stdio.h>
int main()
{ char str[] = "This is tutorialspoint.com";
FILE *fp;
int ch;
/* First let's write some content in the file */
fp = fopen( "file.txt" , "w" );
fwrite(str , 1 , sizeof(str) , fp );
fclose(fp);
fp = fopen( "file.txt" , "r" );
while(1)
{ ch = fgetc(fp);
if( feof(fp) )
{
break ;
}

49
printf("%c", ch);
}
rewind(fp);
printf("\n");
while(1)
{
ch = fgetc(fp);
if( feof(fp) )
{
break ;
}
printf("%c", ch);

}
fclose(fp);

return(0);
}
Let us assume we have a text file file.txt that have the following content
This is tutorialspoint.com
Now let us compile and run the above program to produce the following result
This is tutorialspoint.com
This is tutorialspoint.com

feof
int feof ( FILE * stream );

Check end-of-file indicator


Checks whether the end-of-File indicator associated with stream is set, returning a value
different from zero if it is.

50
This indicator is generally set by a previous operation on the stream that attempted to
read at or past the end-of-file.
Notice that stream's internal position indicator may point to the end-of-file for the next
operation, but still, the end-of-file indicator may not be set until an operation attempts to
read at that point.

This indicator is cleared by a call to clearerr, rewind, fseek, fsetpos or freopen. Although
if the position indicator is not repositioned by such a call, the next i/o operation is likely
to set the indicator again.

Parameters
Stream- Pointer to a FILE object that identifies the stream.
Return Value
A non-zero value is returned in the case that the end-of-file indicator associated with the
stream is set. Otherwise, zero is returned.

Example
/* feof example: byte counter */
#include <stdio.h>

int main ()
{
FILE * pFile;
int n = 0;
pFile = fopen ("myfile.txt","rb");
if (pFile==NULL) perror ("Error opening file");
else
{
while (fgetc(pFile) != EOF) {

51
++n;
}
if (feof(pFile)) {
puts ("End-of-File reached.");
printf ("Total number of bytes read: %d\n", n);
}
else puts ("End-of-File was not reached.");
fclose (pFile);
}
return 0;
}

This code opens the file called myfile.txt, and counts the number of characters that it
contains by reading all of them one by one. The program checks whether the end-of-file
was reached, and if so, prints the total number of bytes read.

Input/Output operation on File


In the above table we have discussed about various file I/O functions to perform reading
and writing on file. getc() and putc() are simplest functions used to read and write
individual characters to a file.
#include<stdio.h>
#include<conio.h>
main()
{
FILE *fp;
char ch;
fp = fopen("one.txt", "w");
printf("Enter data");
while( (ch = getchar()) != EOF) {
putc(ch,fp);
}
fclose(fp);
fp = fopen("one.txt", "r");

while( (ch = getc(fp)! = EOF)


printf("%c",ch);

52
fclose(fp);
}

Reading and Writing from File using fprintf() and fscanf()


#include<stdio.h>
#include<conio.h>
struct emp
{
char name[10];
int age;
};

void main()
{
struct emp e;
FILE *p,*q;
p = fopen("one.txt", "a");
q = fopen("one.txt", "r");
printf("Enter Name and Age");
scanf("%s %d", e.name, &e.age);
fprintf(p,"%s %d", e.name, e.age);
fclose(p);
do
{
fscanf(q,"%s %d", e.name, e.age);
printf("%s %d", e.name, e.age);
}
while( !feof(q) );
getch();
}
In this program, we have create two FILE pointers and both are refering to the same file
but in different modes. fprintf() function directly writes into the file, while fscanf() reads
from the file, which can then be printed on console usinf standard printf() function.
Command Line Argument
Command line argument is a parameter supplied to the program when it is invoked.
Command line argument is an important concept in C programming. It is mostly used
when you need to control your program from outside. command line arguments are
passed to main() method.

53
Syntax :
int main( int argc, char *argv[])
Here argc counts the number of arguments on the command line and argv[ ] is a pointer
array which holds pointers of type char which points to the arguments passed to the
program.

Example for Command Line Argument


#include <stdio.h>
#include <conio.h>
int main( int argc, char *argv[] )
{ int i;
if( argc >= 2 )
{ printf("The arguments supplied are:\n");
for(i=1;i< argc;i++)
{ printf("%s\t",argv[i]); } }
else
{ printf("argument list is empty.\n"); }
getch();
return 0; }
Remember that argv[0] holds the name of the program and argv[1] points to the first
command line argument and argv[n] gives the last argument. If no argument is supplied,
argc will be one.

54