Вы находитесь на странице: 1из 13

Department of Electrical Engineering

Riphah College of Science & Technology


Faculty of Engineering & Applied Sciences
Riphah International University, Lahore

Program: B.Sc. Electrical engineering Semester: II


Subject CE-103 Object Oriented Programming Date: ……………….

Experiment 3: Arrays and Structures

OBJECTIVES:
An introduction with:

(i) Array, Multidimensional Array, strings and string manipulation in C++.


(ii) Structures, nested Structures and how to use structures in functions.

Group Member (s): ……………………………………………………………

No. Title Marks Obtained


Marks
1 Lab Performance 30
2 Lab report/ Coding/ Output 30
3 Viva Voce 40
4 Total 100

Remarks (if any): ………………………………….

Name & Signature of faculty: …………………………………


Riphah College of Science and Technology, Lahore
FACULTY OF Electrical Engineering

EE DEPARTMENT

Theory
Arrays
Array is a collection of elements of same type referred using a unique name. Each element of an
array is stored in memory locations indexed from 0 through n number of its elements. The lowest
indexed will be the first element and highest indexed the last element of an array.
 Single / One Dimensional Array is an array having a single index value to represent the
arrays element.
 Multi-Dimensional Array is an array with two or more index values. It is also known as
array of arrays. A two dimensional array is also a multi-dimensional array.

Declaration of Array
Type: Array_Name[numberOfElements];
For example,
int Age[5] ;
float cost[30];

Initialization of One Dimensional Array


An array can be initialized along with declaration. For array initialization it is required to place
the elements separated by commas enclosed within braces.
int A[5] = {11,2,23,4,15};
It is possible to leave the array size open. The compiler will count the array size.
int B[] = {6,7,8,9,15,12};

Referring to Array Elements


In any point of a program in which an array is visible, we can access the value of any of its
elements individually as if it was a normal variable, thus being able to both read and modify its
value. The format is as simple as:
name[index]
Examples:
cout<<age[4]; //print an array element
age[4]=55; // assign value to an array element
cin>>age[4]; //input element 4
Using Loop to input an Array from user
int age [10], i ;
for (i=0 ; i<10; i++)
Object Oriented Programming 2nd Semester-EE RCST Lahore
Riphah College of Science and Technology, Lahore
FACULTY OF Electrical Engineering

EE DEPARTMENT

{
cin>>age[i];
}

Arrays as Parameters
At some moment we may need to pass an array to a function as a parameter. In C++ it is not
possible to pass a complete block of memory by value as a parameter to a function, but we are
allowed to pass its address.
For example, the following function:
void print(int A[])
accepts a parameter of type "array of int" called A.
In order to pass to this function an array declared as:
int arr[20];
we need to write a call like this:
print(arr);
Here is a complete example:
#include <iostream>
using namespace std;
void print(int A[], int length)
{
for (int n=0; n<length; n++)
cout << A[n] << " ";
cout << "\n";
}
int main ()
{
int arr[] = {5, 10, 15};
print(arr,3);
return 0;
}

Declaration of two-dimensional array


Type arrayName[numberOfRows][numberOfColumn];
For example,
int Sales[3][5];
Object Oriented Programming 2nd Semester-EE RCST Lahore
Riphah College of Science and Technology, Lahore
FACULTY OF Electrical Engineering

EE DEPARTMENT

Initialization of two-dimensional array


An two-dimensional array can be initialized along with declaration. For two-dimensional array
initialization, elements of each row are enclosed within curly braces and separated
by commas. All rows are enclosed within curly braces.
int A[4][3] = {{22, 23, 10},
{15, 25, 13},
{20, 74, 67},
{11, 18, 14}};

Referring to Array Elements


To access the elements of a two-dimensional array, we need a pair of indices: one for
the row position and one for the column position. The format is as simple as:
name[rowIndex][columnIndex]

Examples:
cout<<A[1][2]; //print an array element
A[1][2]=13; // assign value to an array element
cin>>A[1][2]; //input element

Using loop to input an two-dimensional array from user


int mat[3][5], row, col ;
for (row = 0; row < 3; row++)
for (col = 0; col < 5; col++)
cin >> mat[row][col];

Arrays as Parameters
Two-dimensional arrays can be passed as parameters to a function, and they are passed by
reference. When declaring a two-dimensional array as a formal parameter, we can omit the size of
the first dimension, but not the second; that is, we must specify the number of columns. For
example.
void print(int A[][3],int N, int M)
In order to pass to this function an array declared as:
int arr[4][3];

Object Oriented Programming 2nd Semester-EE RCST Lahore


Riphah College of Science and Technology, Lahore
FACULTY OF Electrical Engineering

EE DEPARTMENT

we need to write a call like this:


print(arr);
Here is a complete example:
#include <iostream>
using namespace std;
void print(int A[][3],int N, int M)
{
for (int R = 0; R < N; R++)
for (int C = 0; C < M; C++)
cout << A[R][C];
}
int main ()
{
int arr[4][3] ={{12, 29, 11},
{25, 25, 13},
{24, 64, 67},
{11, 18, 14}};
print(arr,4,3);
return 0;
}
C++ Strings
There are two types of strings commonly use in C++ programming language:

 Strings that are objects of string class (The Standard C++ Library string class)
 C-strings (C-style Strings)

C-strings
In C programming, only one type of string is available and this is also supported in C++
programming. Hence it's called C-strings. C-strings are the arrays of type char terminated with
null character, that is, \0 (ASCII value of null character is 0). Consider this example:

char str[] = "C++";

In the above code, str is a string and it holds 4 character. Although, "C++" has 3 character, the
null character \0 is added to the end of the string automatically.

Other ways of defining the string:


Object Oriented Programming 2nd Semester-EE RCST Lahore
Riphah College of Science and Technology, Lahore
FACULTY OF Electrical Engineering

EE DEPARTMENT

char str[4] = "C++";

char str[] = {'C','+','+','\0'};

char str[4] = {'C','+','+','\0'};

Like arrays, it is not necessary to use all the space allocated for the string. For example:

char str[100] = "C++";

Example 1: C++ String


C++ program to display a string entered by user.
#include <iostream>
using namespace std;

int main() {
char str[100];
cout<<"Enter a string: ";
cin>>str;
cout<<"You entered: "<<str<<endl;
cout<<"\nEnter another string: ";
cin>>str;
cout<<"You entered: "<<str<<endl;
return 0;
}
Output

Enter a string: C++

You entered: C++

Enter another string: Programming is fun.

You entered: Programming

Notice that, in second example only "programming" is displayed instead of "Programming is


fun". It is because The extraction operator >> considers a space has a terminating character.
Example 2: C++ String
C++ program to read and display an entire line entered by user.
#include <iostream>
Object Oriented Programming 2nd Semester-EE RCST Lahore
Riphah College of Science and Technology, Lahore
FACULTY OF Electrical Engineering

EE DEPARTMENT

using namespace std;

int main() {
char str[100];
cout<<"Enter a string: ";
cin.get(str, 100);
cout<<"You entered: "<<str<<endl;
return 0;
}
Output

Enter a string: Programming is fun.

You entered: Programming is fun.

To read the text containing blank space, cin.get function can be used. This function takes two
arguments. First argument is the name of the string(address of first element of string) and second
argument is the maximum size of the array.
Passing String to a Function
Strings are passed to a function in a similar way arrays are passed to a function.
#include <iostream>
using namespace std;
void display(char s[]);

int main() {
char str[100];
cout<<"Enter a string: ";
cin.get(str, 100);
display(str);
return 0;
}

void display(char s[]) {


cout<<"You entered: "<<s;
}
Output

Enter a string: Programming is fun.

You entered: Programming is fun.


Object Oriented Programming 2nd Semester-EE RCST Lahore
Riphah College of Science and Technology, Lahore
FACULTY OF Electrical Engineering

EE DEPARTMENT

Structure
As we know that Array is collection of the elements of same type, but many time we have to store
the elements of the different data types. Structure is composition of the different variables of
different data types, grouped under same name.
Example
struct student
{
char name[64];
char course[128];
int age;
int year;
};

Definitions of Structures
Each member declared in Structure is called member.
char name[64];
char course[128];
int age;
int year;
Are some examples of members defined above.

Name given to structure is called as tag

student
Structure Initialization
When we declare a structure then memory won’t be allocated for the structure. i.e only writing
below declaration statement will never allocate memory

struct student
{
int mark1;
int mark2;
int mark3;
};
We need to initialize structure variable to allocate some memory to the structure.

struct student s1 = {89,54,65};


We can initialize structure variable in different ways
1. Declare and Initialize
Object Oriented Programming 2nd Semester-EE RCST Lahore
Riphah College of Science and Technology, Lahore
FACULTY OF Electrical Engineering

EE DEPARTMENT

struct student
{
char name[20];
int roll;
float marks;
}std1 = { "Pritesh",67,78.3 };
In the above code snippet, the structure is declared and as soon as after declaration we have
initialized the structure variable.

std1 = {"Pritesh",67,78.3};

This is the code for initializing structure variable.

2: Declaring and Initializing Multiple Variables

struct student
{
char name[20];
int roll;
float marks;
}
std1 = {"Pritesh",67,78.3};
std2 = {"Don",62,71.3};
In this example, we have declared two structure variables in above code. After declaration of
variable we have initialized two variables.

std1 = {"Pritesh",67,78.3};
std2 = {"Don",62,71.3};

3: Initializing Single member

struct student
{
int mark1;
int mark2;
int mark3;
} sub1={67};

Object Oriented Programming 2nd Semester-EE RCST Lahore


Riphah College of Science and Technology, Lahore
FACULTY OF Electrical Engineering

EE DEPARTMENT

Though there are three members of structure, only one is initialized, and then remaining two
members are initialized with Zero. If there are variables of other data type then their initial values
will be

Data Type Default value if not initialized

Integer 0

Float 0.00

Char NULL

4: Initializing inside main

struct student
{
int mark1;
int mark2;
int mark3;
};

void main()
{
struct student s1 = {89,54,65};
- - - - --
};

Passing Structure to Function

It can be done in 3 ways.

1. Passing structure to a function by value


2. Passing structure to a function by address(reference)
3. No need to pass a structure – Declare structure variable as global

1. Passing structure to function value


struct student
{
int id;
char name[20];

Object Oriented Programming 2nd Semester-EE RCST Lahore


Riphah College of Science and Technology, Lahore
FACULTY OF Electrical Engineering

EE DEPARTMENT

float percentage;
};

void func(struct student record);

int main()
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(record);
return 0;
}

void func(struct student record)


{
cout<<" Id is: <<record.id<<endl;
cout<<" Name is: "<<record.name<<endl;
cout<<" Percentage is: "<<record.percentage<<endl;
}

2. Passing structure to function by address

struct student
{
int id;
char name[20];
float percentage;
};

void func(struct student *record);

int main()
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(&record);
return 0;
}

Object Oriented Programming 2nd Semester-EE RCST Lahore


Riphah College of Science and Technology, Lahore
FACULTY OF Electrical Engineering

EE DEPARTMENT

void func(struct student *record)


{
cout<<" Id is: " <<record->id;
cout<<" Name is: "<< record->name;
cout<<" Percentage is: "<<record->percentage;
}

3. Declare a structure variable as global

struct student
{
int id;
char name[20];
float percentage;
};
struct student record; // Global declaration of structure

void structure_demo();

int main()
{
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
structure_demo();
return 0;
}

void structure_demo()
{
cout<<" Id is: "<< record.id;
cout<<" Name is: "<< record.name;
cout<<" Percentage is: "<< record.percentage;
}

Object Oriented Programming 2nd Semester-EE RCST Lahore


Riphah College of Science and Technology, Lahore
FACULTY OF Electrical Engineering

EE DEPARTMENT

Task Sheet

1. Twenty-five numbers are entered from the keyboard into an array. The number to be
searched is entered through the keyboard by the user. Write a program to find if the number
to be searched is present in the array and if it is present, display the number of times it
appears in the array.
2. Twenty-five numbers are entered from the keyboard into an array. Write a program to find
out how many of them are positive, how many are negative, how many are even and how
many odd.
3. Write a program to obtain transpose of a 4 x 4 matrix. The transpose of a matrix is obtained
by exchanging the elements of each row with the elements of the corresponding column.
4. Create a structure to specify data of customers in a bank. The data to be stored is: Account
number, Name, Balance in account. Assume maximum of 200 customers in the bank.
a) Print the Account number and name of each customer with balance below Rs. 100.
b) If a customer request for withdrawal or deposit, it is given in the form: Acct. no, amount,
code (1 for deposit, 0 for withdrawal) Write a program to give a message, “The balance is
insufficient for the specified withdrawal”.

Object Oriented Programming 2nd Semester-EE RCST Lahore