DSA Lab Session 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Lab session 1: Array and Structure

Objective

The objective of lab session 1 is


 To initializing and using arrays
 To use single and multi-dimensional arrays
 To declare and use arrays and arrays of data structures.
 To declare and use structure.

Pre-lab Exercise

1. For the below array declaration, how many values will the array hold?
a. double num[7];
b. int n[ ] = { 2,3,15,8,48,13 };
2. Create an array (size 20) of structure for the below structure declaration
a. struct Employee{
string emp_id;
string emp_name;
string emp_sex;
};
3. Write the output of the following C++ code fragment.
a. int i;
int values[ 10 ] = { 4, 1, 1, 3, 4, 9, 9, 2, 1, 7 };
cout << "Element" << “ “ << "Value" << endl;
for ( i = 0; i < 10; i++ )
cout << i << “ “ << values[ i ] << endl;

b. char string1[] = "How are you?";


cout << "string1 is: " << string1 << endl;
for ( int i = 0; string1[ i ] != '\0'; i++ )
cout << string1[ i ] << "_";

1|Page
c. const int arraySize = 10;
int a[ arraySize ] = { 4, 3, 7, 1, 13, 6, 0, 2, 9, 5 };
for ( int i = 0; i < arraySize; i++ )
{
for ( int j = 0; j < a [ i ]; j++ )
cout << "*";
cout << endl;
}

d. struct Person
{
char name[50];
int age;
float height;
};
int main()
{
Person p1;
strcpy(p1.name,”Alex Degefa”);
p1.age=23;
p1.salary=1980.56;
cout << "Displaying Information." << endl;
cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << " Height: " << p1.height;
return 0;
}

2|Page
4. Write a block of code that declares a structure called Employee with
these data members: age, yearsOfService, and Salary.
5. Write a block of code that will read up to ten non-negative integers into
an array called number_array.
6. Create a struct declaration with a single member, and then create a
definition for that member. Create an object of your new data type, and
call the member function.

In-lab Exercise

7. Write a program that asks the user to type 10 integers of an array. The
program must compute and write how many integers are greater than or
equal to 10.
8. Suppose you want to keep track of your books in a library. You might want
to track the following attributes about each book: title, author, subject
and book Id. Create a structure to hold two books information and print
books information.
9. Write a program which takes 2 arrays of 4 integers each, a and b. c is an
array with 8 integers. The program should put into c the appending of b to
a, the first 4 integers of c from array a, the latter 4 from b. Then the
program should display c.

Post-lab Exercise

10. What is the limitation of array?


11. Is there ever a reason to use a structure in a C++ program?
12. In the structure manipulation, what is the dot operator, and what is it used
for?

3|Page

You might also like