Reputation: 741
I want to make a program that when the user enters AB1245
and have the program change it to AB 12345
(an added space between 2nd and 3rd character)
char Bilnr[9];
for (i = 8; i < 3; i--) {
Bilnr[i++]=Bilnr[i];
}
As I understand this, this program will start with Bilnr[9] and set it to the value of Bilnr[8].
Then set Bilnr[8] to the value of Bilnr[7].
But it doesn't move any of the values. It simply prints AB1245
.
Upvotes: 3
Views: 174
Reputation: 9821
This loop condition is wrong:
for (I=8; I<3; I--) {
Bilnr[I++]=Bilnr[I];
}
I
is never less than 3 so the loop never starts. You probably wanted a >
. You would also have an infinite loop if it ever did start because you have I++
and I--
.
You want something like this:
for (I=7; I>1; I--) {
Bilnr[I+1]=Bilnr[I];
}
Furthermore, you'll have to replace that location with a space, otherwise you'll end up with 'AB112345':
Bilnr[2] = ' ';
Upvotes: 2
Reputation: 33511
It prints the same, because the loop never runs. The loop condition is wrong, it should be I>3
to start. The for
loop works as follows:
for (initialization; condition-that-has-to-be-true; optional-increment-decrement) {
}
Also remember C/C++ arrays start counting at 0, not 1.
To fix your complete code:
char Bilnr[9] = "AB12345";
for (I=7; I>2; I--) {
Bilnr[I]=Bilnr[I-1];
}
Then you have AB112345
. All you need then is put in the space:
Bilnr[2] = ' ';
Upvotes: 2
Reputation: 31184
One thing I notice is that if your loop ever actually executes, it would be infinite
for (I=8; I<3; I--) {
Bilnr[I++]=Bilnr[I];
}
I++
doesn't mean I+1
rather, it means I = I+1
but your loop won't execute, because your condition, I<3
will be false from the get-go when you initialize I
with I=8
You're also never setting I[2]
to be a ' '
you also also have to realize that arrays start at 0
, so Bilnr[0]
== 'A'
try
for(int i = 8; i > 2; i--)
{
Bilnr[i] = Bilnr[i-1];
}
Bilnr[2] = ' ';
Upvotes: 4