Write a program that creates three vector<float> objects. Fill the first two obj
ID: 3780422 • Letter: W
Question
Write a program that creates three vector<float> objects. Fill the first two objects with 25 floating-point numbers using a for loop as follows:
1. fill the first vector object with the loop counter value;
2. fill the second vector object with the loop counter value squared;
3. finally, write a for loop that adds the corresponding elements in the first two vectors, and puts the result in the corresponding element of the third vector.
Display all three vectors using the format “for counter; element + element = element”.
Explanation / Answer
import java.util.Vector;
public class VectorAdd {
public static void main(String a[]){
Vector<Float> v1=new Vector<>(25);
Vector<Float> v2=new Vector<>(25);
Vector<Float> v3=new Vector<>(25);
//run i from 0 to 12.5 with increment of 0.5
for(float i=0.0f;i<12.5f;i=i+0.5f){
v1.add(i);
}
for(float i=0.0f;i<12.5f;i=i+0.5f){
v2.add(i*i);
}
for(int i=0;i<v1.capacity();i++){
v3.add(v1.get(i)+v2.get(i));
}
for(int i=0;i<v1.capacity();i++){
System.out.println(i+"; "+v1.get(i)+"+"+v2.get(i)+"="+v3.get(i));
}
}
}
Output:
0; 0.0+0.0=0.0
1; 0.5+0.25=0.75
2; 1.0+1.0=2.0
3; 1.5+2.25=3.75
4; 2.0+4.0=6.0
5; 2.5+6.25=8.75
6; 3.0+9.0=12.0
7; 3.5+12.25=15.75
8; 4.0+16.0=20.0
9; 4.5+20.25=24.75
10; 5.0+25.0=30.0
11; 5.5+30.25=35.75
12; 6.0+36.0=42.0
13; 6.5+42.25=48.75
14; 7.0+49.0=56.0
15; 7.5+56.25=63.75
16; 8.0+64.0=72.0
17; 8.5+72.25=80.75
18; 9.0+81.0=90.0
19; 9.5+90.25=99.75
20; 10.0+100.0=110.0
21; 10.5+110.25=120.75
22; 11.0+121.0=132.0
23; 11.5+132.25=143.75
24; 12.0+144.0=156.0
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.