I just started to learn programming 2 months ago and I am still newbie in it. I just learn how to write a code of arrays with loop. This was my code.
#include <iostream>
using namespace std;
int main()
{
int array[5];
for(int x=1; x<=5; x++)
{
fidan[x]=16;
cout<<x<< " --- " << array[x]<<endl;
}
return 0;
}
I know that array is count from 0. But I want my program to start with 1. So, at for loop instead of x=0, I write x=1. Then at my last x it started to being weird.
Can someone help me with it. I would appreciate it. Thank you
array[5] means an array with 5 elements. These elements are:
array[0],array[1],array[2],array[3],array[4].
Now you can declare it as array[6] and then you will have an array[5] element. Now your code should have produced a segmentation fault when accessing the array[5] element, but this is undefined behavior so who knows to whom that memory segment belongs to.
The weird characters that you get is because that memory does not belong to the array variable and probably cannot be interpreted as int. Hope that helps.
you should use one of two ways:
for (int i = 0 ; i < 5 ; i++)
cout << array[i] << " ";
or
for (int i = 1 ; i <= 5 ; i++)
cout << array[i - 1] << " ";
Your array is with 5 elements.
When x=5 in the loop, you are accessing the 6th element, so you are out of the bounds of the array.
I know that array is count from 0.
Correct.
But I want my program to start with 1.
Well, it doesn't. As you just said.
So, at for loop instead of x=0, I write x=1.
Simply don't do that.
Then at my last x it started to being weird.
Yes, because you tried to access an array element that doesn't exist.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Here it is:
#include <iostream>
#include <cstdlib> // for rand() and srand()
#include <ctime>
using namespace
int main()
{
//cout << "How many players?" << endl;
int numplayers=1;
//cin >> numplayers;
int players[numplayers];
int x=0,y=0;
srand(time(0));
x=(rand() % 6 + 1);
y=(rand() % 6 + 1);
players[1]=players[1]+x+y;
cout << ("Your score is" + players[1]) << endl;
cin >> numplayers;
}
Ok My original problem was that this always crashed, now it prints "#"???
C++ arrays are 0 based.
players[1] is accessing a location outside the range of the array.
You will want: players[0].
cout << ("Your score is" + players[1]) << endl;
Here you're trying to use direct string concatenation, but you can't concatenate a string literal with an integer like that. You end up doing pointer arithmetic, which is definitely not what you intended.
You should instead use cout's built-in formatting:
cout << "Your score is" << players[1] << endl;
Your next problem is that players is not declared correctly; an array cannot have runtime bounds, and numplayers (despite having only the one initial value) is ultimately a "runtime" variable. You would be better off with a std::vector if the size of the array is going to change later; otherwise make numplayers a constexpr.
Your last problem is that, if the array declaration were valid, you'd be trying to access the second element of a one-element array! The first element is players[0], not players[1].
There are many things you're doing not good.
I believe you're using C++, there is no known way to me about creating arrays of dynamic size i.e. int players[numplayers]. In C++ either we can create array of fixed size i.e. int players[10] or use pointer to an array for dynamically allocated memory e.g. int* players = new int[numplayers]. This allocates an array of size numplayers and an int pointer named players is pointing to it. We can use this pointer as normal array e.g. printing 1st index of array is written as player[0] or another syntax is *(player + 0). Remember to delete this dynamically allocated memory at the end of program i.e. delete[] player.
Second thing is when you have allocated an array and are using its value for computation, always initialize it to 0 as newly allocated array contains garbage value and it will affect your computations. code for initializing it to zero may be like this:
Here is the loop:
for(int i = 0 ; i < numplayers ; i++){
player[i]=0;
//another syntax is : *(player + i) = 0;
}
C++ does not concat as you did in your std::cout statement. Make it like this:
cout << "Your score is" << players[0] << endl;
In C++, arrays always start with index zero, so 1st index will be 0 in this case. So your program will work well if it is like this:
int numplayers = 1;
int* players = new int[numplayers];
int x = 0, y = 0;
srand(time(0));
x = (rand() % 6 + 1);
y = (rand() % 6 + 1);
players[0] = 0;
players[0] = players[0] + x + y;
cout << "Your score is" << players[0] << endl;
delete[] players;
return 0;
Definitely it crashes for the below line:
players[1]=players[1]+x+y;
Because size of players array is 1, so it has only index 0. And in above line, it tries to access index 1. Take a look at Buffer Overflow and array index out of bounds.
Try to define an array with constant size.
If you need a dynamic array, use linked list or vector.
I am new with C++, so I need your help. I wrote this program,
#include<iostream.h>
int main(){
int totalAge = 0;
int age[10];
for(int j= 1; j<10; j++){
age[j] = j;
cout << age[j] << endl;
}
for(int i = 0; i<10; i++){
totalAge = age[i];
cout << "Total Age is : " << totalAge << endl;
}
system("pause");
}
Where as the output on command prompt is this:
1 2 3 4 5 6 7 8 9
Total Age is : 1700868285
Total Age is : 1
Total Age is : 2
Total Age is : 3
Total Age is : 4
Total Age is : 5
Total Age is : 6
Total Age is : 7
Total Age is : 8
Total Age is : 9
Press any key to continue . . .
The only thing I want to know is that why is first "Total Age is : 1700868285" I believe it should be "Total Age is : 0"
Please explain it.
Thanks
Your first loop never initialized age[0]. In some languages variables are automatically set to their default value. C++ is not one of them. C++ makes no guarantees about the value of an uninitialized variable. The 1700868285 value is simply whatever happened to be in the memory used to store age[0] when interpreted as an int.
Your code should read like this. Now age[0] is set to 0.
for(int j = 0; j < 10; j++)
{
age[j] = j;
cout << age[j] << endl;
}
This is a good example of why you should be very diligent about initializing variables in C++. As pointed out below by #Caesar you could start off by declaring the array and initializing it at the same time. This adds a small overhead in that you have written zeros into the array and then update it with the values you really want but this will help avoid the issue that caught you here.
You can actually do this using std::array (as pointed out by #Ben) and std::iota from the Standard Library which will make your code simpler.
std::array<int, 10> age = { 0 }; // initialize all the values to zero.
std::iota(begin(age), end(age), 0); // Set the values of the elements to 0...9
If you want to make even more C++ like you can also consider using the new form of for syntax.
for (auto a : age)
{
totalAge = a;
cout << "Total Age is : " << totalAge << endl;
}
And consider using the std:accumulate algorithm, rather than manually calculating the sum.
int totalAge = std::accumulate(begin(age), end(age), 0);
The reason you have this issue is because you never set the value for the first element in the array age. Therefore, it is value is undefined.
An easy fix is to declare your array like this int age[10] = { 0 };, initializing all the values in the array to zero.
You never initialize age[0], becuase j is never equal to 0. So in the second loop, when i=0, totalAge is assigned the uninitialized value age[0] which contains garbage value.
Array indexing begins from zero.While inputting you have given no value to age[0] while at the time of outputting you are using age[0] which gives a garbage value.So run your first loop from 0 to 9.
In your first for loop, you assign array index 1 to 1. Array index 0 is the first, which is left unassigned to anything, which means that it can have any value (because it's uninitilized). Then, in your second for loop, you access that index, which has an uninitilized value.
I think you want to change your first for loop to look something like this:
for(int j = 0; j < 10; j++){
age[j] = j;
cout << age[j] << endl;
}
Note that the only change is that it now starts from 0.
Your first loop starts from
int j= 1;
and the first element of the array is age[0]. In the second loop you're trying to get the value of age[0] and since it was never initialized you receive this long ass address number.
Write a program to input a series of 12 integers from the keyboard and store them in a one-dimensional array, x[12], then displayed them on the computer screen in reverse order.
I have a basic understanding that:
My numbers in the array will go from {0 to 11}
I am using a for loop (which I don't currently know how to do)
Now... How do I write this program?
You would do this:
loop from 0 to 11 using a for loop (for(size_t i = 0; i < 12; i++))
for each i, std::cin into the item at index i std::cin >> array[i];
To print them out you can use a while loop with i--. It will stop when i is zero and it will be backwards.
Because this is a homework question, I won't give you the full code but I hope this answer helps.
Learn about loops: while for do, while etcetera and you just might find the solution that you have been looking for
Example:
for(i = 0; i < 10; i++){
cout << i;
}
Since you know the quantity of numbers, you could insert them into the array in reverse order:
cin >> x[11]; cin >> x[10]; cin >> x[09]; //...
Next you would display the array in normal order:
cout << x[0]; cout << x[1]; cin << x[02]; //...
Since I didn't use a for loop, that's not going to help, is it?
The key concept is the 3rd parameter of the for loop, which can control the direction of a loop.
Let us investigate some examples:
for (unsigned int i = 0; i < 10; i += 2) {cout << i << endl; }
The above loop skips items because the variable is incremented by 2. That is 2 is added to index variable. This shows that loops don't always have to use ++.
So, what would happen if the index were set to the end value and then subtracted each time?
for (int i = 10; i >= 0; i -= 2) {cout << i << endl;}
This is for you to figure out.
Now, you will need to either ask questions in class, ask the professor after class or get a book that you will read and can understand easily (in addition to the one you have).
I was trying some C++, but I'm too new to this and you can say that this is my first day at C++. So I was trying to create a function but I was stuck with arrays! When I create a Character based array like this :
char x[7][7] = {"sec","min","hr","day","week","month","year"};
And when I try to fetch the data from it like this :
for (i=0;i<=7;i++){
cout << x[i] << "\n";
}
I get some strange results! Like this :
Can anyone tell me where I'm going totally wrong! And please I'm new to C++ so can you provide me a good explanation.
Since you have 7 values, and the array is indexed from 0, you only need to count up to 6, not 7. Modify your for loop as for (i=0;i < 7;i++). (< instead of <=.)
You're going over the end of the array, which may give you garbage data or may just crash your program.
for (i=0;i<=7;i++){
cout << x[i] << "\n";
}
The array indices will only range from 0 to 6, and you check for i<=7. Change that to i < 7.
The problem is not in creating the array but in printing the results. Arrays in C, C++, Java, C#... and many other languages are 0 based. When you declare an array of 7 elements you iterate from 0 to 6:
for ( int i = 0; i < 7; ++i ) {
std::cout << x[i] << std::endl;
}
Note: < and not a <=.
I'm working through a demo program written by someone else, and I'm very confused about some of the statements they are using. I'm not very familiar with C++ (moreso with Obj-C) and I'm not sure if this is valid code or not. Take, for example, the following: (comments are mine)
int main(int argv, char** argc)
{
int perm [20]; //OK, so declare an array of ints, size = 20
for (int i=0; i < 20; i++)
perm = i; //whaaaaa??? thought you need to specify an element to assign to an array...
}
That is one example - my compiler throws an "incompatible types in assignment of 'int' to 'int [20]' error, but apparently others have been able to compile the program. Am I nuts, or is this bad code?
Here's another piece I just don't get:
int d[20] = {0}; //OK, another int array of size 20, initialized to 0's
for (int i = 1; i < n; i++)
{
d = d[i - 1]; //this I don't get - assign the array to one of its own elements??
if (invperm[i - 1] < b)
d++; //this would just increment to the next element?
}
I suspect the error is one of comprehension on my part, as if the code was bad other people would've commented on that fact...if anyone has a good explanation and/or resource I can read to understand this, I would be most appreciative!
Thanks!
*EDITED TO ADD*
In response to the answers below, I did copy/paste that code, and it looks intact to me...I can only assume when the original author posted it, it mangled it somehow. Thanks for the replies, I'm glad I had the right understanding, and I'll try and contact the author to see if there is an un-mangled copy out there somewhere!
All those examples are absolutely wrong. It looks like you lost [i] when you copied the code from wherever you got it from.
I have seen something similar with code sent over messenger programs that treat certain bits of text as emotes and replace them with images that don't get copied as text, but instead get dropped.
Your understanding is fine, that code is just entirely nonsensical.
d++; //this would just increment to the next element?
It would if d were a pointer. However since d is an array, it's simply illegal.
This is most certainly a copy/paste error.
I have succumbed to the temptation of copy/pasting code at one point during a game tech project involving Lua scripts. If the Lua script fails there is no feedback/output that indicates something is failed (which is very frustrating). After debugging for hours I realised my script was using 'smart quotes'.
Whilst this code is broken it can still teach you some things about C++.
int perm [20];
cout << endl << perm << endl;
cout << endl << &perm[0] << endl;
'perm' returns the memory address of the first element of the array. so when you are trying to assign 'i' to 'perm' in that main for loop (20 times) you will know now that you were trying to assign an integer to a memory address, hence the incompatible type error.
The second section however is verry broken and I can't discern much learning from this :P.
I added in an example program to show how pointers/arrays can be used:
#include <iostream>
using namespace std;
int main()
{
int d[20] = {0}; // 20 ints, set to 0
int * ptr = d; // points to d[0]'s memory address
for(int i = 0; i < 20; i++)
{
d[i] = 0 + i; // set array values
}
for(int i = 0; i < 20; i++)
{
// iterates through d and prints each int
cout << endl << "d[i]: " << d[i] << endl;
// dereferences the ptr to get the same int
// then incraments the position of the pointer for next time
cout << endl << "*ptr++: " << *ptr++ << endl;
}
getchar();
return(0);
}