Why is my for loop running infinitly? - c

Entering the size of the array works. But the Enter integers for loop runs infinitely.
#include <stdio.h>
int main() {
int c, array[5], i;
printf("Enter the size of the array.");
scanf("%d", &c);
array[c];
printf("Enter the integers to fill the array.");
for (i = 0; i <= c; i++) {
scanf("%d", &array[i]);
}
for (i = 0; i <= c; i++) {
printf("%d", array[i]);
//if (array[0] >= array[i]) {
// ...
//}
}
return 0;
}

Your array is of a fixed size 5. The line array[c]; doesn't resize it. It's an array access (possibly an out of bounds access) and therefore your entire program has undefined behavior.
To define a VLA, you must move the array declaration after the call to scanf1:
int c;
printf("Enter the size of the array.");
scanf("%d",&c);
int array[c];
Then, make sure your loop condition is correct. In C array indices a 0-based, meaning we loop on the interval [0, c-1] and not [0, c].
for(int i = 0; i < c; ++i)
And as a final point of contention, notice how I moved all variable declaration to just before their initial use. Organizing your code like that (with a certain locality of data and execution) has a tendency to clarify what you write. So I strongly advise you to do this.
And be sure to check the return value of scanf. You do not want to define an array if the call to the library function failed.

array[c] refers to an element at 'c' position in array and doesn't do any fruitful job. Try removing that and check once.
In your for loop, you're reading and printing elements from 0 to c, which means you took c+1 elements instead of c elements. Make it : for(i=0;i<c;++i)

Related

I'm just trying to scan strings into an array. What am I doing wrong?

#include <stdio.h>
#include <string.h>
int main(void) {
const int NUM_VALS = 20;
int i;
int actualInput;
char userString[actualInput][NUM_VALS];
int matchCount = 0;
scanf("%d", &actualInput);
for (i = 0; i < actualInput; ++i) {
scanf("%s", userString[i]);
printf("%s", userString[i]);
}
return 0;
}
Output:
b'hellohi\x80\x07#\xd2\x05#\x9a\x16[\xea\xccp\xa6\x15\xf6\x18+\xbf\x87\x8a#\x14)\x05#\xfe\x7f'b'\x92\x1fk\xb3\xfe\x7f\xfe\x7f\x118\x08\xe8\x03\x0eY\x03k\xb3\xfe\x7f\xfe\x7f\xb2Y{\xe8C}8\r\x8b-u{\x8cx86_64'F-8sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin/usr/sbin:/usr/bin:/sbin:/binsbin:/binTF-88tf8RELOAD=/usr/lib/x86_64-linux-gnu/coreutils/libstdbuf.so64-linux-gnu/coreutils/libstdbuf.sols/libstdbuf.soout
I've tried some variations replacing userString[i] with userString in the scanf function. The result is outputting 50,000 inputs of my last string. I don't understand what's happening.
The problem is this sequence of code:
int actualInput;
char userString[actualInput][NUM_VALS];
int matchCount = 0;
scanf("%d", &actualInput);
The first line declares a variable called actualInput but doesn't assign a value to that variable.
The second line declares a variable length array (VLA) using the value in actualInput. Using the value of an uninitialized variable results in undefined behavior, which basically means that after that point in the code, anything can happen. What's likely happening (based on your description of the problem) is that actualInput is either zero, or a small number, so you get an array that's too small to hold your input.
The last line (with the scanf) finally assigns a value to actualInput. You may be thinking that the array will resize itself when actualInput is changed. That definitely does not happen. In C, after a VLA is created, its size cannot be changed.
The solution is simple, rearrange the code so that things are done in the proper order:
int actualInput;
scanf("%d", &actualInput);
char userString[actualInput][NUM_VALS];
int matchCount = 0;
As a side note, you should really do some error checking to make sure that the user inputs a reasonable number, before using that number to create an array. For example
int actualInput;
if (scanf("%d", &actualInput) != 1 || actualInput < 1 || actualInput > 1000)
{
printf("That is not a valid array size\n");
return 1;
}
char userString[actualInput][NUM_VALS];
you cant declare it as a 2D array then treat it as a normal array .
each case should include only one letter but it can't be done automatically , I suggest you add this :
for (i = 0; i < actualInput; ++i)
{
gets(stri);
for (k=0;k<strlen(stri);k++)
userString[i][j]=stri[j];
}

Pass an unknown number of integers with scanf

I need to create an array of ints of an unknown size and pass them all. My code looks like this:
int FillTable(int a[], int max){
int i;
int x = 0;
int m = 0;
for (i = 0; i < max; i++){
printf("Fill the table with integers: ");
scanf("%d", &m);
if (m != "" && m != NULL){
a[i] = m;
}else if (m != "" && m == NULL){
a[i] = 0;
}else{
break;
}
}
printf("\n");
return 0;
}
I know you can pass multiple ints separated by spaces with something like:
scanf("%d %d %d", &var1, &var2, &var3);
But I don't know how to pass a number of integers that I don't know how many will be there. Could I create a string with a bunch of %d and just repeat that for max times? I don't know, but right now, I just ask for ints until the array is full, and I need to be able to have the array be smaller than max if the user doesn't enter in enough values. Does anyone have any ideas as to how I would go about scanning for an unknown number of integers?
Does anyone have any ideas as to how I would go about scanning for an unknown number of integers?
This calls for Dynamic memory allocation!
One way of going with scanning unknown number of integers is, firstly allocate an integer array with size to hold max number of integers.
How to know whether user has ended his input?
If you are only scanning in positive integers from user at array entries then prompt him to end his input by inputting a negative number
or if you are sure about the range of input entries then break out of loop, when user enters input out of range
Example: (considering user inputs only positive numbers)
//creating a large enough array to store user inputs
int *array = malloc(sizeof(int) * max);
//check if memory was allocated or not
if(array == NULL)
{
printf("memory allocation problem!");
exit(1);
}
//integer to make note of size of array or you can use the sizeof() function instead
int size_of_array = 0;
for (i = 0; i < max; i++)
{
printf("Fill the table with integers: ");
if(scanf("%d", &m) != 1) //check for scanf return value
{
printf("wrong input, try again");
char consume; //to consume the character
scanf("%c", &consume);
i--;
continue;
}
if (m > 0) //if positive number, accept
{
array[i] = m;
size_of_array++;
}
else //else break out of scanning
{
break;
}
}
//do the program.....
//don't for get to free the memory at the end
free(array);
here's a working example: https://ideone.com/BHN4sk
You are trying to do something that is not necessary. To predict the size of the array and reallocate the appropriate exact size would be computationally more expensive (in terms of cpu time) so that benefit of saving the memory that you already had allocated is not enough.
The size of the array in c is stored somewhere that not necessarily has anything to do with the array itself. So you simply need to know how many of the array elements are interesting for the program and nothing else.
You could have something like
struct Array {
int *data;
size_t size;
size_t count;
};
where size is the total size of the array, count is the number of elements in the array and data are the elements. I use this pattern a lot and it's useful, specially if combined with realloc() as it saves from unecessarilly reallocating memory too many times which is expensive at the cost of using slightly more memory than actually needed.
But systems today have way more memory than can be used (except if you use Android Studio, which can use as much memory as your computer has).
First, m != "" && m != NULL probably does not do what you think it does. You're probably coming from a different language. What (I think) that statement does is compare the value in the integer variable m to the address of the string literal "" and then compare it to NULL (which evaluates to 0).
Second, scanf by default reads until either a space or a newline.
scanf returns a negative number on failure, so your code should look like this:
for (i = 0; i < max; i++){
printf("Fill the table with integers: ");
if(scanf("%d", &m) > 0) {
a[i] = m;
}
else {
break;
}
}
I left out the a[i] = 0 branch because I don't understand what you wanted there.
Also, you never use the variable x - unless there is more code that you left out.
your problem isn't understand for me properly,however i think this will be helped to you
int arraySize = 200; // Or whatever
int *array_ = malloc(arraySize * sizeof(int));
use this and the pass the *array_ as parameter,first defined array size or get array size as a user input,and run a for loop till size of array
You should decide how the user can stop his input (and include this info in your prompt). A quick-and-dirty way would be "enter anything that is not a number". I chose this way of terminating input, because it's easy to implement (hence, quick and dirty):
printf("Fill the table with integers; terminate with 'x':\n");
for (i = 0; i < max; i++)
{
int result = scanf("%d", &a[i]);
if (result != 1)
break;
}
Note:
The prompt tries to be user-friendly
The scanf function puts the number straight into the array, without using any intermediate variable
The scanf function returns how many numbers it read, which is normally 1; if it's not 1, then the user entered x or anything else
When the code finishes, i holds the number of iterations, which shows how many numbers were read from the user.
Your input function should return the size of the array:
return i; // instead of "return 0"
You might also want to clean the stdin buffer - discard anything that the user entered to terminate the array:
while (getchar() != '\n')
{
// do nothing - keep consuming input until end-of-line
}

While loop to read interger values from standard input

I need my program to read integer values into adjacent elements in the array, and set the counter to the total number of integers read. I also need another loop to print the values to the screen.
How do I go about doing this?
#include <stdio.h>
int main(void) {
int numArray[100];
int counter, value;
printf("Enter array length \n");
scanf("%d", &counter);
int i = 0;
while(i < counter) {
scanf("%d", &numArray[i]);
value = numArray[i];
i++;
}
return 0;
}
I need my program to read integer values into adjacent elements in the array, and set the counter to the total number of integers read. I also need another loop to print the values to the screen.
How do I go about doing this?
The overall program should work, however you need to initialize:
value = 0; /*Initialize Variables */
counter = 0;
In C when you enter a function like main variables like value and counter get initialized with random value -- if you don't initialize. It could cause you problems.
while(i < counter) /*Scans the values into the array */
{
scanf("%d", &numArray[i]);
value = numArray[i];
i++;
}
The scanf function here scans the value you entered into the array.
I'm not sure what you would use values for; your array stores the values for you. However, it could make your code shorter if you use it in a different way.
A loop to print the values would look similar to your original loop.
while(i < counter)
{
printf("%d", &numArray[i]); /*Prints the values in the array */
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;
}
}

Simple program that adds numbers from user

I am trying to write a simple program that uses scanf to input 5 numbers from the user and add them together. Here is the code I have so far..
int main()
{
int i;
int j=1;
int k=1;
for (i=1; i<= 5; i++)
{
scanf("%d\n", &j);
k = k+j;
}
printf("%d\n", k);
}
But here's what happens when I run the program:
1
2
3
4
5
5
16
Basically, it asks me for a sixth number (obviously, I just need 5), and it also adds one to the final result. (1+2+3+4+5=15).
Any thoughts on this. Am I making a simple mistake somewhere?
As others have said, you are initializing k incorrectly, but I suspect that what's causing your problem is that you are using scanf("%d\n", &j); instead of scanf("%d", &j);. scanf() ignores whitespace leading up to the match.
Initially k = 1. Then you add the numbers 1, 2, 3, 4, 5 to it. Altogether they sum up to 1+1+2+3+4+5, which is 16.
You should generally think about initializing variables.
i doesn't need to be initialized before the for loop.
j doesn't need to be initialized, since it will be read from the input.
k needs to be properly initialized. But since it has a certain purpose you should rather call it sum than k. And when you sum up things, you should start with 0.
Additionally you should check whether the call to scanf was successful. In that case the function returns 1.
if (scanf("%d", &j) == 1) {
sum += j;
} else {
fprintf(stderr, "Invalid input.\n");
break; /* exit the for loop. */
}
You seem to be initializing k (which is the number you hold your sum in) as one, then adding all the other numbers to it. Try this:
int k = 0;
instead.
Then, when you do
k = k+j
the first time, k will be 0, and not 1. You also don't need to do j=1.
That said, you can also use a shortcut for k = k +j;
k += j;
C programmers have to do this pattern so much that they built a shortcut into the language specifically for it.
In your for loop, it's convention in C to start at zero and work to < your max number, as well:
for (i = 0; i < 5; i++)
I'm not sure why it's asking an extra time, but try setting your loop as that and seeing if it works.
This is what you want, k initialized at 0 and doing a scanf input without the \n which is an endline :
int main() {
int i;
int j=0;
int k=0;
for (i=1; i<= 5; i++){
scanf("%d", &j);
k = k+j;
}
printf("%d\n", k);
}
The '\n' character is unnecessary. I suspect you are mixing up your printf and scanf syntax :P

Resources