do while for array in c - c

i work for a question that generate random number and sort in array, then display numbers from biggest to smallest.
here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 40
int main()
{
int array[SIZE];
int inner, outter, temp, i;
srand((unsigned)time(NULL));
//do... while to assign array value
i=0;
do{
array[i] = (int)((rand()%101)+1);
i++;
}while(i<SIZE);
puts("Original array:");
for(outter=0; outter<SIZE-1;outter++){
printf("%d\t", array[outter]);
}
//bubble sort
for(outter=0; outter<SIZE-1;outter++){
for(inner=outter+1; inner<SIZE; inner++ ){
if(array[outter] > array[inner]){
temp = array[outter];
array[outter] = array[inner];
array[inner] = temp;
}
}
}
puts("\n");
puts("Sorted array:");
printf("i= %d\n",i);
printf("%d\n", array[39]);
for(outter=0; outter<SIZE;outter++){
printf("%d\t", array[outter]);
}
puts("\n");
for(outter=SIZE-1; outter>0;outter--){
printf("%d\t", array[outter]);
}
puts("\n");
// try using do while loop to display reverse number from biggest to smallest numbers
do{
printf("i= %d\n", i-1);
i--;
}while(i>-1);
}
when i used do while for displaying reverse array number, my code goes crush.
However, i display the value the "i" that used for looping array, it displayed from 39 to -1. I don not why i have -1 for "i" value since i set "i>-1".

TL;DR: Either change your printf to this: printf("i= %d\n", i); or change your while loop to while(i > 0);. Either way, it should fix your problem.
A do while loop does the action in the curly braces and then checks the condition. I'm not quite understanding your question, but it seems to me that it's printing -1 because it's doing first, then checking the condition. Furthermore, you're using i - 1 in your printf function (which is probably where you've confused yourself the most).
EDIT: To be even more explicit about the while loop, the problem is that your condition is (i > -1). That means that when you reach 0, your code will check: is 0 greater than -1?. It will return true and then move on the i = -1 where it prints -1. Then it reaches the while condition once more where it sees that -1 is not greater than -1 which is when the code terminates.

Your main problem is probably the starting value for i.
After the first do ... while loop it equals 40 when the condition fails.
Therefore you could make things a lot easier if you adjust your starting value for the second loop:
i--; // or i = SIZE-1;
do{
printf("i= %d\n", i);
i--;
} while (i >= 0);
Then you don't have any headache by shifting your values by one and can just use the values you want.
If you insist on doing it the way you did, then check the limits...
do{
printf("i= %d\n", i-1); // last value to be printed is 0 ==> i == 1
i--; // The last wanted value of i now is 0.
} while (i>0); // Stop if we reach last wanted value

Related

What is wrong with my C code? C code warning

#include<stdio.h>
int main(void)
{
int i=2,number;
printf("Enter another number greater than 5\':");
scanf("%d",number);
while (number>5);
for (; i<=3; i++)
{
printf("Hi\n");
++i;
}
printf("Enter another number greater than 5\' to continue the cycle:");
scanf("%d",number);
printf("finish");
return 0;
}
First, within the two scanf functions you need to add & to the number parameter. It is because &number gets the address of number, and the value entered by the user is stored in that address. Also, your code never leaves the loop. Try like this:
#include <stdio.h>
int main(void){
int number;
printf("Enter a number greater than 5: ");
scanf("%d",&number);
while (number>5){
for (int i = 0; i<1; i++){
printf("Hi\n");
}
printf("Enter another number to continue the cycle: ");
scanf("%d", &number);
}
printf("finish");
return 0;
}
Remember that for loop already increments the counter i by itself, so the i++ statement inside loop is unnecessary if you wanted to print "Hi!" only once (even the for loop is useless if you only wanted to print it once, but I guess you did it because you are learning).
There are several problems:
1 Incorrect usage of scanf
scanf takes format string and then addresses to variables, so it could write to memory, where the variables are located.
So correct usage is
scanf("%d",&number);
Best would be to check also return value of scanf. scanf returns count of successfully loaded arguments. So in you case
if (scanf("%d", &number) != 1) {
// print error message, or something else
}
If there were more arguments, then the condition would be different
if (scanf("%d %f %c %d", &a, &b, &c, &d) != 4) {
// ...
}
2 Infinite while loop
while (number>5); is infinite loop if number is greater then 5.
number is not changed within the loop, so the condition for while loop would be always truthy.
3 Possibly wrong incrementation of i variable in for loop
// int i = 2;
for (; i<=3; i++)
{
printf("Hi\n");
++i;
}
There is suspicious ++i; in the for loops body. This does not change the for loops behaviour, but I assume you are a beginner, so I will explain it anyway.
It will work like this:
for loop starts with no initialization (i is initialized to 2 outside of the loop)
condition i <= 3 gets evaluated to 1 (C does not have boolean [true,false], so there are used numbers instead [0 == false, anything else == true])
printf("Hi\n"); gets evaluated -> "Hi\n" gets printed
++i; gets evaluated -> i gets incremented to 3
update of for loop gets called (which is i++) -> i gets incremented to 4
condition i <= 3 gets evaluated as 0, because 4 (value of i) is greater then 3
for loop gets finished
My point here is that the i is incremented twice every loop.
So it's the same like
for(; i <= 3; i += 2) {
scanf("%d", &number);
}

My C program to find closest pair of numbers from user input is not printing the right output?

I am trying to find the closest pair of numbers entered by the user. My C code isn't working right and I can't figure out what's wrong. I think it might have something to do with storing the values but I don't know where to go from here.
#include <stdio.h>
#include <math.h>
int main()
{
int i, j,arr[50], first,second;
//loop input
for(i=0;i<50;i++) //loop 50 times
{
scanf("%d", &i); //scan
//break if i=-1
if (i==-1)
break;
//if not print
}
//2nd num - 1st num < 3rd num-1st num, closest = 1st and 2nd num
//i[0]=num1, j[0+i]=2nd num, i= 4 , 5, 7, ans=arr,
//if j[0+i]-i[0]= ans < j[0+i]-i[i]=ans
//arr[i]=8,2,17,4,25
for(i=0;i<50;i++)
{
for(j=i+1;j<50;j++)
{
if(arr[j]-arr[i]<arr[j+1]-arr[i])
{
first = arr[i];//3
second = arr[j+1];//5
}
}
}
printf("%d %d\n", first, second);
return 0;
}
Don't post it as answer, prefer editing your code instead. Anyway, the problem is here :
for (j = i + 1; j < len; j++)//j<i <-why is it wrong?
How isn't it wrong? You've initialised j with the value i+1. How's it supposed to be ever less than i? And due to that, it's picking up values from outside the array and providing you with unexpected results.
The correct form is :
for (j = 0; j < i; j++)
The problem is with this chunk of code. You're scanning in the counter variable i instead of array. And then you're manipulating stuff using array arr. Why should that work in any scenario?
for(i=0;i<50;i++) //loop 50 times
{
scanf("%d", &i); //scan
//break if i=-1
if (i==-1)
break;
//if not print
}
And i can never be -1 unless it's a miracle.

Why this for loop ends in the second index?

I wrote a program that it's duty is to read 20 numbers from user and put them in a list, after that it prints the value in array from bottom to starting point.
But program stops exactly after reading second value from input.
Source code :
#include <stdio.h>
#define N 20
int main(void)
{
int numbers[N];
int i;
for(i=0;i<N;i++)
{
scanf("%i", &numbers[i]);
}
for(i=N;i<0;i--)
{
printf("%i", numbers[i]);
}
return 0;
}
I use Dev-C++ 5.6.3 as my IDE and TDM-GCC 4.8.1 as my compiler. But I don't know exactly that is this an IDE related issue or not.
If you want the loop to count downwards, then this loop
for(i=N;i<0;i--)
starts at the wrong index, and fails the test condition. It should be
for(i = N - 1; i >= 0; i--)
If you want your second loop to count down, then
for(i=N;i<0;i--)
should be
for(i=N;i>0;i--)
or the loop will not execute, as i<0 is not true to start with.
and, as #WeatherVane pointed out in the comments:
scanf("%i", numbers[i]);
should be
scanf("%i", &numbers[i]);
as you need to pass a pointer to the integer you wish to fill in with the number that scanf returns.
There is some issue with the given below for loop.
for(i=N;i<0;i--)
{
printf("%i", numbers[i]);
}
return 0;
If you Want to print the array from bottom to starting point.
You can make some changes in the for loop.
Changes :
1- Change in loop while assigning the value to i :
i = N-1 -> as the size of array is 20 and array index starts with 0.
it will go 19 to 0 to print all 20 data values.
2- changes in the condition check in for loop :
i >= 0 as we printing the reverse array.
Correct for loop should be
for(i = N-1; i >= 0; i--)
{
printf("%i", numbers[i]);
}
for(i=N-1;i>=0;i--)
For n items in an array, last index will be n-1. you need to iterate from n-1 index to 0th index.
second loop must be
for(i=N;i>=0;i--)
so index will be from 19 to 0 ( 20 number )
Try This
#include <stdio.h>
#define N 20
int main(void)
{
int numbers[N];
int i;
for(i = 0; i < N; i++)
{
scanf("%i", &numbers[i]);
}
for(i = N ; i >= 0; i--)
{
printf("%i ", numbers[i]);
}
return 0;
}
Try this:
#include <stdio.h>
#define N 20
int main(void)
{
int numbers[N];
int i;
for(i = 0; i < N; i++)
{
scanf("%i", &numbers[i]);
}
for(i = N - 1; i >= 0; i--)
{
printf("%i ", numbers[i]);
}
return 0;
}
Remember that scanf always uses pointers.
Your second loop's condition, "i<0", is false to begin with. It should be "i > -1". You also need to make sure that the first time printf is called with index 19 and not 20. That is why I use pre decrement operator -- i.
for(i = N; i > -1; )
{
printf("%i\n", numbers[--i])
};

keeping a variable from inside a while loop?

I'm trying to create a program that will take inputs into an array, and then print them all when input is terminated. My understanding was that when you declare a variable outside of the loop, it keeps the values, but I can't get this to work out. I know there's a way to do this somehow, but I'm drawing a blank.
#include <stdio.h>
int main(){
int i=0;
int n=0;
int size=0;
int numbers[i];
scanf("%d", &numbers[i]);
while ((i = 1 && numbers[i-1] != 42)){
scanf("%d", &numbers[i]);
i++;
size++;
//printf("%d",numbers[i]);
}
printf ("%d", sizeof(numbers));
while ((n = 0 && n < sizeof(numbers))){
printf("%d", numbers[i]);
printf("\n");
++i;
++n;
}
}
Your while condition:
(i = 1 && numbers[i-1] != 42)
has two problems:
i = ... actually assigns a value to i. In cas of unexpected looping, allways check if there's a =instead of an == in the condition
due to operator precedence, you assign 1 && to i. That's true value (i.e. 1) as long as you're in the loop, and as soon as numbers[i-1] is 42, i turns to 0 (because numbers[i-1]!=42 is false and 1 && false is false i.e. 0 ). This gives you impression that it didn't keep the value.
Edit: Of course, it's the same principle for n in the second loop ;-)
3 things in your code:
int numbers[i]; is trying to declare a zero element array, which accounts to undefined behavior.(although there's no bound/range checking in C)
scanf("%d", &numbers[i]), when i>=1 where is the storage allocated for this? mostly would end up in an undefined area/ over writing an existing value.
Refer the following links for more information:
Declaring an array with 0 number of elements can still store values
Why does C not define minimum size for an array?
that said you could either declare an array of fixed size or declare the size dynamically using malloc, then loop through the elements , assign and print them.
-the while loop: evaluation and priority of operators:
you could re-write your program as:
#include <stdio.h>
int main(){
int i=0;
int n=0;
int size=0;
int numbers[42];
scanf("%d", &numbers[i++]);
while (((numbers[i-1] != 42)))
scanf("%d", &numbers[i++]);
size=sizeof(numbers)/sizeof(int); /* Not necessary as array size pre-defined*/
printf("\nsize:%d\n",size);
while(n < size)
printf("%d\n", numbers[n++]);
printf("\n");
}
Note: you can change the size of the array, do keep in mind that it's an automatic variable and those array elements which haven't been explicitly initialized would be filled with junk values.
There are a lots of mistakes in your code.They are as follow-
1.int i=0;
int number[i]; which makes no sense. because you are creating an array of size 0
while ((i = 1 && numbers[i-1] != 42))
every time you while loop iterates it sets the value of i to 1 and compares numbers[0]!=42 which also makes no sense.
while ((n = 0 && n < sizeof(numbers)))
again you are assigning n to 0 and checking if n is less than sizeof(numbers) which is always true.
Although you did not specify your problem correctly I am assuming that you want to scan number till you get 42. And after that you want to print the size of the array and the numbers too.
Here is your working code.
#include <stdio.h>
int main(){
int i=0;
int n=0;
int size=1;
int numbers[10000];//I am assuming maximum input to be 10000
scanf("%d", &numbers[0]);
i=1;
while (( numbers[i-1] != 42)){
scanf("%d", &numbers[i]);
i++;
size++;
//printf("%d",numbers[i]);
}
printf ("size=%d\n", size);
while ( n < size){
printf("%d", numbers[n]);
printf("\n");
//++i;
++n;
}
}

Geting some garbage value on the second index

I'm trying to calculate HCF in C with pointers.
int-type-Pointer ptr points to an array of integers.
The inputs that i have given are 30,60,18,a. And here "a" is to terminate the list of integers and breaks off the "while".
I tried the debug mode, and found the values:
*ptr = 30
*(ptr+1)= -1163005939 //the garbage that i'm talking of.
*(ptr+2)= 60
*(ptr+3)= 30
while what i should get are 30, 60,18.
#include<stdio.h>
void main(){
int* ptr=(int*) malloc( sizeof(int)* 50);
int input=0;
int smallest;
printf ("Enter the numbers (press any alphabet when you're done )\n");
while (1)
{ input++;
if (input==1 && scanf("%d", ptr)) // the first number is stored in smallest
{smallest = *ptr; continue;}
if (!scanf("%d",ptr+input )) // if the input is a character , scanf says 0,
{input--; //! makes it 1, and we jump out of the loop
break;}
if (smallest > *(ptr+input)) // swapping
{ smallest += *(ptr+input);
*(ptr+input) = smallest- *(ptr+input);
smallest= smallest- *(ptr+input);
}
}
// code for determining the HCF
char c;
if (smallest <=0)
{
printf("", scanf("%c",&c ), printf("Answer is 0")); // it will print that the answer
exit(0); //is 0 then waits for you to
} //press any key and then it exits
//if smallest greater than 0
int i=2;
int HCF=1;
int j;
for (; i<smallest/2; i++)
{ for (j=0; j<=input;j++)
// this is where the problem is suspected
//as i ve seen in the debug mode
//it gives results divides the garbage value to i
{if (! (*(ptr+j)%i == 0)) // if the number stored in the location is not
break; //divisible by i, then leave that number i
} //and check for the next i
if (j>input)
HCF *= i;
}
printf( "", scanf("%c", c), printf("The HCF is %d ", HCF));
free(ptr);
}
So what is the problem?
And i didnt want to allocate the 50 ints memory. I wanted to just use the pointer wildly without any allocation. I know its bad practice but i just want to apply it . Is that any harm to other programs? How?
It's garbage because you never write anything to it. Look at this code
while (1)
{ input++;
if (input==1 && scanf("%d", ptr)) // the first number is stored in smallest
{smallest = *ptr; continue;}
if (!scanf("%d",ptr+input )) // if the input is a character , scanf says 0,
{input--; //! makes it 1, and we jump out of the loop
break;}
//code that doesn't assign values to ptr
}
by the time you get to scanf("%d",ptr+input ), input will be 2 if scanf("%d", ptr) returned a truthy value. That's because of this if statement:
if (input==1 && scanf("%d", ptr)) // the first number is stored in smallest
{smallest = *ptr; continue;}
notice how you continue here when input is equal to 1? that means that the while loop will skip everything else and begin again from the beginning, and the first thing that it's going to do is increment input from 1 to 2.

Resources