0% found this document useful (0 votes)
15 views21 pages

Unit 4

The document discusses one-dimensional and two-dimensional arrays in C/C++. It covers declaring, initializing and accessing arrays. It also covers string handling functions like strcat, strcmp and strlen.

Uploaded by

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

Unit 4

The document discusses one-dimensional and two-dimensional arrays in C/C++. It covers declaring, initializing and accessing arrays. It also covers string handling functions like strcat, strcmp and strlen.

Uploaded by

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

UNIT – IV

ARRAYS :
An array is a group of related data items that share a common name.

Ex:- Students

The complete set of students are represented using an array name students. A particular
value is indicated by writing a number called index number or subscript in brackets after array
name. The complete set of value is referred to as an array, the individual values are called elements.

ONE – DIMENSIONAL ARRAYS :

A list of items can be given one variable index is called single subscripted variable or a
one-dimensional array.

The subscript value starts from 0. If we want 5 elements the declaration will be

int number[5];

The elements will be number[0], number[1], number[2], number[3], number[4]

There will not be number[5]

Declaration of One - Dimensional Arrays :

Type variable – name [sizes];


Type – data type of all elements Ex: int, float etc.,

Variable – name – is an identifier

Size – is the maximum no of elements that can be stored.

Ex:- float avg[50]

This array is of type float. Its name is avg. and it can contains 50 elements only. The
range starting from 0 – 49 elements.

Initialization of Arrays :

Initialization of elements of arrays can be done in same way as ordinary variables are
done when they are declared.

Type array name[size] = {List of

Value};Ex:- int number[3]={0,0,0};

If the number of values in the list is less than number of elements then only that elements will be
initialized. The remaining elements will be set to zero automatically.

Ex:- float total[5]= {0.0,15.75,-10};

The size may be omitted. In such cases, Compiler allocates enough space for all initialized
elements.

int counter[ ]= {1,1,1,1};

/* Program Showing one dimensional array */

#include<stdio.h>
main()

int i;

float x[10],value,total;

printf(“Enter 10 real numbers\n”);

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

scanf(“%f”,&value)

; x[i]=value;

total=0;

for(i=0;i<10;i+

+)

total=total+x[i]

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

printf(“x*%2d+=%5.2f\n”,I+1,x*I+);

printf(“total=%0.2f”,total);

TWO – DIMENSIONAL ARRAYS:

To store tables we need two dimensional arrays. Each table consists of rows and
columns. Two dimensional arrays are declare as

type array name [row-size][col-size];

/* Write a program Showing 2-DIMENSIONAL ARRAY */


/* SHOWING MULTIPLICATION TABLE */

#include<stdio.h>

#include<math.h>

#define ROWS 5

#define COLS 5

main()

int

row,cols,prod[ROWS][COLS];

int i,j;

printf(“Multiplication table”);

for(j=1;j< =COLS;j++)

printf(“%d”,j)

for(i=0;i<ROWS;i++

row = i+1;

printf(“%2d|”,row);

for(j=1;j < =

COLS;j++)

COLS=j;

prod[i][j]= row * cols;

printf(“%4d”,prod*i+*j+);

}
}

INITIALIZING TWO DIMENSIONAL ARRAYS:

They can be initialized by following their declaration with a list of initial values
enclosed in braces.

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

Initializes the elements of first row to zero and second row to one. The initialization is done by
row by row. The above statement can be written as

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

When all elements are to be initialized to zero, following short-cut method may be used.

int m[3][5] = {{0},{0},{0}};

Difference 1D and 2D Array:


Basis One Dimension Array Two Dimension Array

Store a single list of the element Store a ‘list of lists’ of the element of a similar
Definition of a similar data type. data type.

Represent multiple data items Represent multiple data items as a table


Representation as a list. consisting of rows and columns.

The declaration varies for


different programming
language: The declaration varies for different
programming language:
1. For C++,
datatype 1. For C++,
variable_name[row] datatype variable_name[row][column]
2. For Java, 2. For Java,
datatype [] variable_name= datatype [][] variable_name= new
Declaration new datatype[row] datatype[row][column]

Dimension One Two


size of(datatype of the variable size of(datatype of the variable of the array)*
Size(bytes) of the array) * size of the array the number of rows* the number of columns.

Address of a[i][j] can be calculated in two


ways row-major and column-major
1. Column Major: Base Address + Size of
each element (number of rows(j-lower
bound of the column)+(i-lower bound of
the rows))
2. Row Major: Base Address + Size of each
Address of a[index] is equal to element (number of columns(i-lower
Address (base Address+ Size of each bound of the row)+(j-lower bound of the
calculation. element of array * index). column))

int arr[2][5]; //an array with two rows and


int arr[5]; //an array with one
five columns will be created.
row and five columns will be
created. a b c d e
{a , b , c , d , e} f g h i j
Example

STRINGS(CHARACTER ARRAYS) :
A String is an array of characters. Any group of characters (except double quote sign
)defined between double quotes is a constant string.

Ex: “C is a great programming language”.

If we want to include double quotes.

Ex: “\”C is great \” is norm of programmers “.

Declaring and initializing strings :-

A string variable is any valid C variable name and is always declared as an array.
char string name [size];

size determines number of characters in the string name. When the compiler assigns a character
string to a character array, it automatically supplies a null character (‘\0’) at end of String.
Therefore, size should be equal to maximum number of character in String plus one.

String can be initialized when declared as

1. char city*10+= “NEW YORK’;


2. char city[10]= ,‘N’,’E’,’W’,’ ‘,’Y’,’O’,’R’,’K’,’/0’-;
3.
C also permits us to initializing a String without specifying size.

Ex:- char Strings* += ,‘G’,’O’,’O’,’D’,’\0’-;

READING STRINGS FROM USER:

%s format with scanf can be used for reading String. char

address[15];

scanf(“%s”,address);

The problem with scanf function is that it terminates its input on first white space it finds. So scanf
works fine as long as there are no spaces in between the text.

Reading a line of text :

If we are required to read a line of text we use getchar(). which reads a single characters.
Repeatedly to read successive single characters from input and place in character array.

/* Program to read String using scanf & getchar */

#include<stdio.h>

main()
{

char line[80],ano_line[80],character;

int c;

c=0;

printf(“Enter String using scanf to read \n”);

scanf(“%s”, line);

printf(“Using getchar enter new line\n”);

do

character = getchar();

ano_line[c] = character;

c++;

- while(character

!=’\n’); c=c-1;

ano_line*c+=’\0’;

STRING HANDLING/MANIPULATION FUNCTIONS:

strcat( ) Concatenates two Strings

strcmp( ) Compares two Strings

strcpy( ) Copies one String Over another


strlen( ) Finds length of String

strcat() function:

This function adds two strings together.

Syntax: char *strcat(const char *string1, char *string2);

strcat(string1,string2);

string1 = VERY

string2 = FOOLISH

strcat(string1,string2);

string1=VERY

FOOLISH string2 =

FOOLISH

Strncat: Append n characters from string2 to stringl.

char *strncat(const char *string1, char *string2, size_t n);

strcmp() function :
This function compares two strings identified by arguments and has a value 0 if they are
equal. If they are not, it has the numeric difference between the first non-matching characters in
the Strings.

Syntax: int strcmp (const char *string1,const char *string2);

strcmp(string1,string2);

Ex:- strcmp(name1,name2);

strcmp(name1,”John”);

strcmp(“ROM”,”Ram”

);

Strncmp: Compare first n characters of two strings.

int strncmp(const char *string1, char *string2, size_t n);

strcpy() function :

It works almost as a string assignment operators. It takes the form

Syntax: char *strcpy(const char *string1,const char *string2);

strcpy(string1,string2);

string2 can be array or a constant.

Strncpy: Copy first n characters of string2 to stringl .


char *strncpy(const char *string1,const char *string2, size_t n);

strlen() function :
Counts and returns the number of characters in a string.

Syntax:int strlen(const char *string);

n= strlen(string);

n integer variable which receives the value of length of string.

/* Illustration of string-handling */

#include<stdio.h>

#include<string.h

>main()

char s1[20],s2[20],s3[20];

int X,L1,L2,L3;

printf(“Enter two string constants\n”);

scanf(“%s %s”,s1,s2);

X=strcmp(s1,s2)

; if (X!=0)

printf(“Strings are not equal\n”);

strcat(s1,s2);
}

else

printf(“Strings are equal \n”);

strcpy(s3,s1);

L1=strlen(s1);

L2=strlen(s2)
;

L3=strlen(s3)
;

printf(“s1=%s\t length=%d chars

\n”,s1,L1); printf(“s2=%s\t length=%d chars

\n”,s2,L2); printf(“s3=%s\t length=%d chars

\n”,s3,L3);

STRUCTURES :
A Structure is a collection of elements of dissimilar data types. Structures provide the
ability to create user defined data types and also to represent real world data.
Suppose if we want to store the information about a book, we need to store its name
(String), its price (float) and number of pages in it(int). We have to store the above three items as
a group then we can use a structure variable which collectively store the information as a book.
Structures can be used to store the real world data like employee, student, person etc.

Declaration :
The declaration of the Structure starts with a Key Word called Struct and ends with ; .
The Structure elements can be any built in types.

struct <Structure name>


{
Structure element 1;
Structure element 2;
-
-
-
Structure element n;
};

Then the Structure Variables are declared as

struct < Structure name > <Var1,Var2>;

Eg:- struct emp


{
int empno.
char ename[20];
float sal;
};
struct emp e1,e2,e3;

The above Structure can also be declared as :

struct emp struct


{ {
int empno; int empno;
char ename[20]; (or) char ename[20];
float sal; float sal;
}e1,e2,e3; }e1,e2,e3;

Initialization :

Structure Variables can also be initialised where they are declared.


struct emp
{
int empno;
char ename[20];
float sal;
};
struct emp e1 = { 123,”Kumar”,5000.00};
To access the Structure elements we use the .(dot) operator.
To refer empno we should use e1.empno
To refer sal we whould use e1.sal

Structure elements are stored in contiguous memory locations as shown below. The
above Structure occupies totally 26 bytes.

e1.empno E1.ename E1.sal


123 Kumar 5000.00
2000 2002 2022

1. Program to illustrate the usage of a Structure.

main()
{
struct emp
{
int empno;
char ename[20];
float sal;
};
struct emp e;
printf (“ Enter Employee number: \n”);
scanf(“%d”,&e.empno);
printf (“ Enter Employee Name: \n”);
scanf(“%s”,&e.empname);
printf (“ Enter the Salary: \n”);
scanf(“%f”,&e.sal);
printf (“ Employee No = %d”, e.empno);
printf (“\n Emp Name = %s”, e.empname);
printf (“\n Salary = %f”, e.sal);
}

/* Program to read Student Details and Calculate total and average using structures */

#include<stdio.h>
main()
{
struct stud
{
int rno;
char sname[20];
int m1,m2,m3;
};
struct stud s;
int tot;
float avg;

printf(“Enter the student roll number: \n”);


scanf(“%d”,&s.rno);
printf(“Enter the student name: \n”);
scanf(“%s”,&s.sname);
printf(“Enter the three subjects marks: \n”);
scanf(“%d%d%d”,&s.m1,&s.m2,&s.m3);

tot = s.m1 + s.m2 +s.m3;


avg = tot/3.0;

printf(“Roll Number : %d\n”,s.rno);


printf(“Student Name: %s\n”,s.sname);
printf(“Total Marks : %d\n”,tot);
printf(“Average : %f\n”,avg);
}

/* Program to read Item Details and Calculate Total Amount of Items*/

#include<stdio.h>
main()
{
struct item
{
int itemno;
char itemname[20];
float rate;
int qty;
};
struct item i;
float tot_amt;

printf(“Enter the Item Number \n”);


scanf(“%d”,&i.itemno);
printf(“Enter the Item Name \n”);
scanf(“%s”,&i.itemname);
printf(“Enter the Rate of the Item \n”);
scanf(“%f”,&i.rate);
printf(“Enter the number of %s purchased ”,i.itemname);
scanf(“%d”,&i.qty);

tot_amt = i.rate * i.qty;

printf(“Item Number: %d\n”,i.itemno);


printf(“Item Name: %s\n”,i.itemname);
printf(“Rate: %f\n”,i.rate);
printf(“Number of Items: %d\n”,i.qty);
printf(“Total Amount: %f”,tot_amt);
}

ARRAY OF STRUCTURES :
To store more number of Structures, we can use array of Structures. In array of
Structures all elements of the array are stored in adjacent memory location.

/* Program to illustrate the usage of Array of Structures.

main()
{
struct book
{
char name[20];
float price;
int pages;
};
struct book b[10];
int i;
for (i=0;i<10;i++)
{
print(“\n Enter Name, Price and Pages”);
scanf(“%s%f%d”, b[i].name,&b[i].price,&b[i].pages);
}
for (i i=0;i<10;i++)
printf(“ \n%s%f%d”, b[i].name,b[i].price,b[i].pages);
}

UNIONS :
Union, similar to Structures, are collection of elements of different data types. However,
the members within a union all share the same storage area within the computer‟s memory,
whereas each member within a Structure is assigned its own unique Storage area.
Structure enables us to treat a member of different variables stored at different places in
memory, a union enables us to treat the same space in memory as a number of differentvariables.
That is, a union offers a way for a section of memory to be treated as a variable of onetype on one
occasion and as a different variable of a different type on another occasion.

Unions are used to conserve memory. Unions are useful for applications involving multiple
members, where values need not be assigned to all of the members at any given time. An attempt
to access the wrong type of information will produce meaningless results.

The union elements are accessed exactly the same way in which the structure elements are
accessed using dot(.) operator.

The difference between the structure and union in the memory representation is as follows.

struct cx

int i;

char ch[2];

};

struct cx s1;

The Variable s1 will occupy 4 bytes in memory and is represented as

---------- s.i ------- s.ch[0] s.ch[1]

4002 4003 4004 4005


The above datatype, if declared as union then

union ex

int i;

char ch[2];

union ex u;

u.i

u.ch[0] u.ch[0]

/* Program to illustrate the use of unions */

main()
{

union example

int i;

char ch[2];

};
union exaple u;

u.i = 412;

print(“\n u.i = %d”,u.i);

print(“\n u.ch*0+ =

%d”,u.ch*0+); print(“\n u.ch*1+ =

%d”,u.ch*1+);

u.ch[0] = 50; /* Assign a new value */

print(“\n\n u.i = %d”,u.i);

print(“\n u.ch*0+ = %d”,u.ch[0]);

print(“\n u.ch*1+ =

%d”,u.ch*1+);

Output :

u.i = 512

u.ch[0] =

0u.ch[1]

=2

u.i = 562

u.ch[0] =

50u.ch[1]

=2

A union may be a member of a structure, and a structure may be a member of a union. And also
structures and unions may be freely mixed with arrays.
/* Program to illustrate union with in a Structure */

main()
{

union id

char color;

int size;

};

struct {

char supplier[20];

float cost;

union id desc;

}pant, shirt;

printf(“%d\n”, sizeof(union

id)); shirt.desc.color = ‘w’;

printf(“%c %d\n”, shirt.desc.color, shirt.desc.size);

shirt.desc.size = 12;

printf(“%c %d\n”, shirt.desc.color, shirt.desc.size);

Similarities between Structure and Union


1. Both are user-defined data types used to store data of different types as a single unit.
2. Their members can be objects of any type, including other structures and unions or arrays. A member
can also consist of a bit field.
3. Both structures and unions support only assignment = and sizeof operators. The two structures or
unions in the assignment must have the same members and member types.
4. A structure or a union can be passed by value to functions and returned by value by functions. The
argument must have the same type as the function parameter. A structure or union is passed by value
just like a scalar variable as a corresponding parameter.
5. ‘.’ operator or selection operator, which has one of the highest precedences, is used for accessing
member variables inside both the user-defined datatypes.
Differences between Structure and Union are as shown below in tabular format as shown below as
follows:

You might also like