Hi there, this is my first time here, so hello to you all :)
I read some tutorials from this site and was interested to visit the forums, I am hoping that I will find a solution to my problem :)
I just started using C++, so bare with me.
I am trying to understand how a user can input a number, and this number is saved into an array, and be called later on. I read the tutorials about arrays so I understand how it works, but not loops.
for example :
{
User enters "20"
Array saves the number 20
Program calls Array(20) * 5
Answer = 100
---repeat for new number in a new array }
This is my try :
I declared an array of 20 values, w[20]
Now to initiate the loop, should I use :
for (n=0,n<=20,n++){
printf("Enter number\n");
scanf("%d",&w[n]);
}
printf("%d",w[n]);
Now the problem is, this loop will only input whatever the user inputs .. How can I loop it while every new value is stored into a new array ?
Maybe I should use w[] (size not declared) ???
Please help and explain why should I use that method, I am trying my best to learn.
It is important to note the difference between Array(20) and Array[20].
Also, it should be n < 20, not n <= 20. If you have an array of [20], the indices are 0 to 19, and 20 is not a valid index.
You can't use an array whose size is not declared. You can declare an array in that manner but it will be treated as a pointer. You'd have to DMA that and judging from your experience with normal arrays that will only confuse you, so don't worry about that unless you really wanna find out.
So then, let me try to understand your real question: You only want to keep getting values as long as a value is not entered twice?
Yes I realized that it should be <20 and changed it in my script :)
My question is : i want the user to input 20 values, and each value is saved into a different array.
This will allow me to use each specified array for another function -- AFTER the user input the 20 values . ( random example : multiplying array[2] by array[5])
I got this btw :
#include<stdio.h>
main(){
int numb,n,g,w[21];
numb=0;
for (n=1;n<21;n++){ //using n=1 just so that w[1]=Student 1 and w[0] is not used.
numb++;
printf("\nEnter the Weight of student %d \n",numb);
scanf("%d",&w[n]);
}
printf("%d",w[7]);
}
This seems to work .. Am I using the code correctly ?
An array is a set of elements. The distinction is critical if you plan on using arrays or any container ever.
And yes, you could theoretically have that happen. cin >> firstvar >> secondvar;
If you input 20 20, each variable will contain the value 20. In other words, just separate with spaces and press enter at the end and that should work fine.
And if you have really long code to post put it on pastebin or something.