While loop to read interger values from standard input - c

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++;
}

Related

Cannot re-initialize after first initialize value to integer array

I first initialize 0 to counter[10], and it is OK. However, somewhere I want to re-initialize with 0 again but fail.
The error message is
[Warning] extended initializer lists only available with -std=c++11 or -std=gnu++11
#include <stdio.h>
#include <stdbool.h>
int main(void) {
int digit, counter[10] = {0}; //Declare variable "digit" to store individual number to be compared and declare an array for the input numbers
bool rep_digits; //Declare a boolean variable to determine whether the input numbers has repetitive numbers or none
int n; //Declare variable "n" to store the input numbers
while (true) { //This while loop serves as a loop for the user input
printf("\nEnter a number (capped at on this compiler): ");
scanf("%d", &n);
if (n == 0) { //The user input loop terminates when the user input a 0
break;
}
printf("Repeated digits(s): \n");
while (n > 0) { //If the condition is true, execute the arguments inside
digit = n % 10; //Obtain the remainder of the input number
counter[digit]++; //Increase the counter for the obtained remainder in the array
if (counter[digit] == 2) { //If the counter of that particular remainder is equal (and only equal) to 2, print out the number
printf("%2d\n", digit);
rep_digits = true; //Set the boolean variable to true if there is a repetitive number in the input
}
n /= 10; //Divide the input number by 10 to determine the next number either repetitive or not
}
counter[10] = {0}; // re-initialize to 0
if (rep_digits == false) { //If the boolean variable stays false then display this message
printf("No repeated digits\n");
}
}
return 0;
}
counter[10] = {0}; writing beyond the array size causes undefined behavior.
suppose you have array size as int counter[10], you should write only from counter[0] till counter[9]
if you want to initialize all the array elements to 0, then you can do it two ways.
int counter[10] = {0}; \\this works only at the same place where you declare
memset(counter,0,sizeof(counter)); \\ this can be done at any other place in the program
In your program replace counter[10] = {0}; with memset(counter,0,sizeof(counter));
it should work just fine.
Instead of using int counter[10] = {0}
Use memset
int counter[10]; memset(counter,0,sizeof(counter));
The above memset line fills every value of counter array to 0.

Outputting huge number when using an array to print out even and odd numbers on C

I was asked to code a program that asks for an integer 'n', then scan for 'n' integers, and then sort and print those integers in even numbers, ascending, then the odd numbers, descending.
So I began by having the even numbers in the first column of an array, and then the odd numbers in the second column, and then print them, but at the end I'm getting nothing but huge, similar numbers instead of the values I initially entered.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int array1_size, unfill;
printf("How many integers do you wish to enter?\n");
scanf("%d",&array1_size);
int array1[array1_size][2];
for (int i = 0; i < array1_size; ++i)
{
printf("Enter integer number %d\n", i+1);
scanf("%d",&array1[i][0]);
}
for (int i = 0; i < array1_size; ++i)
{
if ( (array1[i][0] % 2) != 0 )
{
array1[i][1] = array1[i][0];
array1[i][0] = unfill;
}
}
printf("Your even numbers are:\n");
for (int i = 0; i < array1_size; ++i)
{
printf("%d\n", array1[array1_size][0]);
}
printf("...and your odd numbers are:\n");
for (int i = 0; i < array1_size; ++i)
{
printf("%d\n", array1[array1_size][1]);
}
return(0);
}
You declare
int array1[array1_size][2];
The highest-index legally accessable element inside that is
array1[array1_size-1][2-1]
This line is hence highly suspicious
printf("%d\n", array1[array1_size][1]);
Also you do not initialise unfill but copy its content elsewhere here
array1[i][0] = unfill
You possible leave the content of any array1[i][0] non initialised, because your code is vulnerable by a failing scanf(), because here you ignore the usually very helpful return value, which could warn you in case anything went wrong with scanning.
scanf("%d",&array1[i][0])
Any of these issues could be the explanation of your observed huge numbers, which sometimes are a symptom of using non-initialized variables or content of illegally accessed memory.

Why is my for loop running infinitly?

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)

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
}

How to count Integer array elements like char based strlen() in C?

I would like to count the number of elements in an integer array(sized, like: array[1000]) after input without counting manually while inputting(using scanf() which is = number of arguments passed to scanf).Though int arrays are not null terminated as well as scanf() cannot be used like getchar() or gets() and no availale function like strlen() for int arrays,is it possible to write a C program to prompt the user to input as many numbers as he wishes and the program will count them(total arguments passed to scanf()) and print the maximum using arrays or pointers?
Without having a termination value, you will have to count the inputs as they are made. You could do this by defining a struct to hold the array. Your program does not know how many integers you will enter, and this code allocates more memory when the array is full, keeping track of the array size and elements used.
#include <stdio.h>
#include <stdlib.h>
#define ARRAY_STEP 10 // increment in array size
typedef struct {
int maxlen; // capacity of array
int length; // elements used
int *array; // the array pointer
} istruct;
int main(void) {
istruct intarr = {0}; // empty array
int i;
printf ("Enter some integers:\n");
while (scanf("%d", &i) == 1) {
if (intarr.length >= intarr.maxlen) {
intarr.maxlen += ARRAY_STEP; // increase array size
intarr.array = realloc(intarr.array, intarr.maxlen * sizeof(int));
if (intarr.array == NULL) {
printf("Memory allocation error\n");
exit (1);
}
}
intarr.array[intarr.length++] = i;
}
printf ("You entered:\n");
for (i=0; i<intarr.length; i++)
printf ("%-10d", intarr.array[i]);
printf ("\n");
if (intarr.array)
free(intarr.array);
return 0;
}
strlen() iterates on the character array until the C string termination character (ASCII \0) is encountered. So it is COUNTING the elements. If you want to do that for an int array I guess you could also have a reserved 'terminator' value for your array, make room for it (allocate one more int in your array for the terminator) and implement your own int_array_len() similar to strlen. However, in your case counting the elements while inputting them seems like a much better way to go.
Smart vertion:
#include <stdio.h>
int main()
{
double a[100000],mx=0;
int i,j,c=0;
printf("Enter as many numbers as you wish . Press Ctrl+D or any character to stop inputting :\n");
/*for(i=0;i<100000;i++)
a[i]=0;*/
for(i=0;i<100000;i++)
{
if((scanf("%lf",&a[i]))==1)
c++;
//else break;
}
for(j=0;j<c;j++)
{
if(a[j]>mx) mx=a[j];
}
printf("You have inserted %d values and the maximum is:%g",c,mx);
return 0;
}
It's pretty simple.
just declare of your desired "initial size". And keep checking if input is a valid integer or not.
if((scanf("%d",&a[i]))==1) this would be true if and only if the input is a valid integer. hence the moment the input is not an int, it exits the loop. You can count the number of input values within the same loop and also the max values.
Here is the code:
#include <stdio.h>
#include<limits.h>
int main()
{
int a[100],max = INT_MIN;
int i,j,count=0;
printf("Start Entering the integers... Give any non-integer input to stop:\n");
for(i=0;i<100;i++)
{
if((scanf("%d",&a[i]))==1) {
count++;
if(a[i]>max) {
max = a[i];
}
}
else
break;
}
printf("number of input values: %d;\nThe maximum input value: %d",count,max);
return 0;
}

Resources