0% found this document useful (0 votes)
19 views5 pages

Assignment 2 Data Structures and Algorithms

Uploaded by

zioncalvin9
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
19 views5 pages

Assignment 2 Data Structures and Algorithms

Uploaded by

zioncalvin9
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 5

Data Structures and Algorithms

Assignment 2

Name: Ahmed Hany Mohamed Harfoush

ID: 4221382

Task I
Create ID array of size entered by the user, enter its number externally from user and print its

content in a readable way. In the previous array, sum a number of elements between two positions

entered by the user.

Code:

#include <iostream>

#include <vector>

using namespace std;

int main() {

int size;

cout << "Enter size of ID array: ";

cin >> size;

vector<int> idArray(size);

cout << "Enter " << size << " elements:\n";

for (int i = 0; i < size; i++) {

cin >> idArray[i];

}
cout << "ID Array: ";

for (int i = 0; i < size; i++) {

cout << idArray[i] << " ";

cout << endl;

int start, end;

cout << "Enter starting and ending positions to sum: ";

cin >> start >> end;

int sum = 0;

for (int i = start; i <= end; i++) {

sum += idArray[i];

cout << "Sum between positions " << start << " and " << end << ": " << sum << endl;

return 0;

Sample Output:

Enter size of ID array: 5

Enter 5 elements:

36915

ID Array: 3 6 9 1 5
Enter starting and ending positions to sum: 1 3

Sum between positions 1 and 3: 16

Task 2
Create 2D array of size entered by the user, enter its number externally from user and print its

content in a readable way, print the sum of each column and for each row.

Code:

#include <iostream>

#include <vector>

using namespace std;

int main() {

int rows, cols;

cout << "Enter number of rows and columns for 2D array: ";

cin >> rows >> cols;

vector<vector<int>> array(rows, vector<int>(cols));

cout << "Enter elements of the array:\n";

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

cin >> array[i][j];

cout << "2D Array:\n";


for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

cout << array[i][j] << " ";

cout << endl;

cout << "Row Sums:\n";

for (int i = 0; i < rows; i++) {

int rowSum = 0;

for (int j = 0; j < cols; j++) {

rowSum += array[i][j];

cout << "Row " << i << ": " << rowSum << endl;

cout << "Column Sums:\n";

for (int j = 0; j < cols; j++) {

int colSum = 0;

for (int i = 0; i < rows; i++) {

colSum += array[i][j];

cout << "Column " << j << ": " << colSum << endl;

return 0;

}
Sample Output:

Enter number of rows and columns for 2D array: 2 3

Enter elements of the array:

123

456

2D Array:

123

456

Row Sums:

Row 0: 6

Row 1: 15

Column Sums:

Column 0: 5

Column 1: 7

Column 2: 9

You might also like