Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Task 1 Please generate a vector of the following values: 12,32,33,44 and assign this vector to a variable x. Then extract the first element and

Task 1

Please generate a vector of the following values:

12,32,33,44

and assign this vector to a variable x.

Then extract the first element and the last element from this vector

Task 2

Following the previous question, please use a for loop to calculate the sum of all elements in the vector x.

Task 3

Check the length of the vector x.

If the length is greater than 2, then remove the last element.

Keep doing this until the length is no longer greater than 2.

Hint: to remove the last element of vector x, you can use x[1:length(x)-1]. To update the vector x after removing the last element, use x= x[1:length(x)-1]. Basically, we first remove the last element from x and then assign the leftovers to the variable x again.

You will need the repeat and the break statement mentioned in section 10 of the code snippet.

THESE ARE THE CODES I GOT FOR TASK 1, 2, and 3. ARE THEY CORRECT?

# Task 1

#include using namespace std;

int main() { vector x; int n, inp; cin >> n; // number of input while(n--){ cin >> inp; // give input x.push_back(inp); }

cout << " first element : " << x[0] << endl; cout << " last element : " << x[x.size() -1] ;

return 0; }

# Task 2

x <- c(12, 32, 33, 44);

sum <- 0;

# Loop through the vector

for(i in 1:length(x)){

sum <- sum + x[i];

}

print(sum)

# Task 3

x <- c(12, 32, 33, 44);

while(length(x) > 2){

x = x[1:length(x) - 1];

}

print(x);

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Oracle 12c SQL

Authors: Joan Casteel

3rd edition

1305251032, 978-1305251038

More Books

Students also viewed these Databases questions