Reputation: 39
In the main method below I'm trying to call a sort function and after function selects that latter from the user input it has to print the sort accordingly with the for loop at the end. But I have a warning that reads "loop will run at most once (loop increment never executed)" pointing at the array[arraySize]
. Does it have to do with the return type or the other for loop above? What's happening here? Can anyone point out and explain please. Thanks much! Here's the code below:
int main()
{
long array[100], arraySize;
char sort;
long maxi = 100;
for(arraySize = 0; arraySize < maxi; arraySize++)
{
printf("Enter any positive integer, enter 0 to stop: ");
scanf("%li", &num);
if(num < 0) {
arraySize--;
printf("I said positive!");
count++;
}
else if(num == 0) {
maxi = arraySize;
}
else {
array[arraySize]=num;
arraySize--;
}
}
printf("Please enter A for ascending or D for descending order\n");
scanf("%s", &sort);
bubble_sort(array, arraySize, sort); //calling the sort function
printf(" Sorted list in the selected order:\n");
for (arraySize = 0; arraySize < num; arraySize++) {
printf("%ld \n", array[arraySize]);
puts("");
return 0;
}
}
EDIT: Thanks everyone for all your suggestions. I did make a few changes and here's what I have so far. Now it's skipping the A/D user input along with the bubble_sort
function logic. Here's what it does as a final output: Note: long num
is declared as a global variable!
int main()
{
long array[100], arraySize;
char sort;
long maxim = 100;
for(arraySize = 0; arraySize < maxim; arraySize++)
{
printf("Enter any positive integer, enter 0 to stop: ");
scanf("%li", &num);
if(num < 0)
{
arraySize--;
printf("I said positive! \n");
count++;
}
else if(num == 0)
{
maxim = arraySize;
}
else
{
array[arraySize]=num; //arraySize--;
}
}
printf("Please enter A for ascending or D for descending order: \n");
scanf("%c", &sort);
bubble_sort(array, maxim, sort); //calling the sort function
printf("Sorted list in the selected order:\n");
for (arraySize = 0; arraySize < maxim; arraySize++)
{
printf("%ld \n", array[arraySize]);
}
puts("");
return 0;
}
Any more suggestions will be appreciated!
Upvotes: 2
Views: 716
Reputation: 2033
The last character entered gets stored in sort
and that character is most probably \n
.
Changing scanf("%c", &sort);
to scanf(" %c", &sort);
should solve the problem.
Note the space before %c
.
Upvotes: 1
Reputation: 367
It seems your print loop has a typo, and should be corrected to:
for (arraySize = 0; arraySize < maxi; arraySize++) {
Also the call to bubble_sort() should use maxi rather than arraySize.
Upvotes: 2
Reputation: 81926
There are a few other problems, but let's talk about your warning. You have this code:
for (arraySize = 0; arraySize < num; arraySize++) {
printf("%ld \n", array[arraySize]);
puts("");
return 0;
}
The corrected indentation should make it obvious why that loop will run at most once.
Upvotes: 3