Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
My code:
int main()
{
int menu[16];
int i;
for(i = 0; i < 16; i++)
{
printf("Input array value");
scanf("\n%d", &menu[i]);
}
printf("%d", menu[i]);
}
I'm trying to ask the user for input and add it to the array and then at the end to output the whole array e.g 1,2,3,4....16, however as of now it always returns the value 16 no matter what the user input.
You need to run loop twice. Once for taking inputs and then for displaying all numbers.
#include <stdio.h>
int main()
{
int menu[16];
int i;
for(i = 0; i < 16; i++)
{
printf("Input array value");
scanf("\n%d", &menu[i]);
}
for(i = 0; i < 16; i++)
{
printf("%d\n", menu[i]);
}
}
Your code has an array index bound check failure.
printf("%d", menu[i]);
The value of i here is going to be 16 because you are using it after the loop. The loop terminal condition is i == 16. The menu array is only defined for index values of [0..15]. The value you see in the output is entirely random depending on the state of the execution stack. You could test this by printing instead menu[65] and see random data or maybe a segmentation fault.
Printing out the array to the console is the same loop as your input, but with the printf embedded in it instead. So your code should have 2 loops in it. One loop to gather input, and the other loop to output the input.
The answer is in the comments.
for(i = 0; i < 16; i++)
{
printf("Input array value");
scanf("\n%d", &menu[i]);
}
for(i = 0; i < 16; i++)
printf("%d ", menu[i]);
you can add a loop at the end of your code like this
int main()
{
int menu[16];
int i;
for(i = 0; i < 16; i++)
{
printf("Input array value");
scanf("\n%d", &menu[i]);
}
for (i = 0;i<16;i++)
{
printf("%d ",menu[i]);
}
}
"I'm trying to ask the user for input and add it to the array and then at the end to output the whole array"
Just because it has not been suggested yet...
This can be done using a single loop, or with no loops at all.
(The looping option below is an adaptation of your code with comments describing differences.)
//The following items, are optionally
//defined here instead of in-line with code.
//they are used to clean up the scanf() and sprintf() calls below
#define data menu[0],menu[1],menu[2],menu[3],menu[4],menu[5],menu[6],menu[7],menu[8],menu[9],menu[10],menu[11],menu[12],menu[13],menu[14],menu[15]
#define input_data &menu[0],&menu[1],&menu[2],&menu[3],&menu[4],&menu[5],&menu[6],&menu[7],&menu[8],&menu[9],&menu[10],&menu[11],&menu[12],&menu[13],&menu[14],&menu[15]
const char input_format[] = {"%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d"};
const char format[] = {"%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d\n"};
//it also preferred to avoid magic numbers when possible
#define ELEMENTS 16
#define MAX_LEN_INT 11
//to demonstrate both looping and sequential methods to input and output the same thing
#define USE_LOOP 1 //change to zero for doing this with no loops
int main(void)//added void
{
int menu[ELEMENTS] = {0};
//char buffer `output` should accommodate room for max number of
//characters expressed in 32bit `int` data type: `11` (from the value: `-2147483648`)
//times count of elements to be output: ELEMENTS plus NULL terminator + punctuation.
//This should do it:
int size = ELEMENTS*MAX_LEN_INT+ELEMENTS + 1;
char output[size];//buffer for outputing final line showing user input values
memset(output, 0, sizeof(output));
#if USE_LOOP
int i;
printf("Input array values:\n");//moved outside the loop to display only once
for(i = 0; i < ELEMENTS; i++)
{
printf("enter value %d:\n", i+1);//prompt user for each input value
scanf("%d", &menu[i]);//scan value into array element
}
#else //Use sequential data entry
printf("Enter %d space delimited integer values (eg: 1 2 -45 78... 123) then <enter>:\n", ELEMENTS);
scanf(input_format, input_data);
#endif
//again, outside the loop to display only once
//place all data into printable buffer
sprintf(output, format, data);//using short representations of format specifier and data for readability
printf("%s", output);
return 0; //added return to comply with int function type.
}
Tested with largest possible number of digits using sequential method:
Related
Just getting to learn C better and I'm playing with arrays.
I would like to enter my phone number into an array like this:
#include <stdio.h>
int main()
{
int phoneNum[10];
for (int i = 0; i < sizeof(phoneNum); i++) {
printf("Insert digit %d of your phone number: \n", i + 1);
scanf("%d", &phoneNum[i]);
}
return 0;
}
This seems to fail as it keeps asking me for a new digit. So I tried to print the size of the array:
int phoneNum[10];
printf("%lu", sizeof(phoneNum));
which incredibly gives me the result of 40 even though I initialized it to be 10 (?).
I have three questions:
Why is the result 40 and not 10 in sizeof(phoneNum) ?
How can I add elements in an array successfully with scanf in the above manner?
If the above manner is silly, is there a better, more efficient way to do this? For example directly enter 10 digits into an array? I can of course use scanf("%d%d%d...", digit1, digit2, digit3, ...) but I would like a generalized way, using the size of the array (say I don't know it and it's passed from another function)
sizeof(phoneNum) returns 10 * sizeof(int). The sizeof(int) value appears to be 4 for your system.
#include <stdio.h>
int main()
{
int phoneNum[10] = {0};
const size_t size = sizeof(phoneNum) / sizeof(int);
for (int i = 0; i < size; i++) {
printf("Insert digit %d of your phone number: \n", i + 1);
scanf("%d", &phoneNum[i]);
}
for(int i = 0; i < size; ++i)
{
printf("\r\n %i \n", phoneNum[i]);
}
return 0;
}
sizeof(phoneNum) will return number in bytes, not length of array.
after the includes you could make a define like #define SIZE 10 and use SIZE like if it was a constant.
#include <stdio.h>
#define SIZE 10
int main()
{
int phoneNum[SIZE];
for (int i = 0; i < SIZE; i++)
{
//Do Something
}
}
Take into account the fact that strings should end with null terminated character (\0) so the size of the string have that space available.
I am solving the problem that compares the array that is filled with numbers which are randomly generated by the computer and array that human asked to input numbers. I did pretty well on the first one but have a problem with stacking numbers in the human array.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// numbers that are randomly generated by the computer
int Array_comp (int (*comp))
{
int j,i;
for (j = 0; j < 3; )
{
i = rand();
if (i < 10)
{
comp[j]=i;
j++;
continue;
}
}
return 0;
}
int main(void)
{
srand((int)time(NULL));
int arr_comp[3]={};
int arr_hum[3]={};
Array_comp (arr_comp);
// enter three numbers
for (int i = 0; i < 3; i++)
{
printf("number %d: ", i+1);
scanf("%d ",&arr_hum[i]);
}
// print input numbers
for (int i = 0; i < 3; i++)
{
printf("%d ",arr_hum[i]);
}
return 0;
}
these are my code for this problem. For me, it seems like there is no problem with stacking numbers in the human array.
However, the result is different from my thought.
this is the result of the code. My initial intention is to stacking numbers something like
number 1:1
number 2:2
number 3:3
and printed results different from this. I have no idea why this happens.
The problem you have is that trailing extra space in the scanf() format specifier. It needs to match additional whitespace(s) in order to get the scanning done.
scanf("%d ",&arr_hum[i]);
change to
scanf("%d",&arr_hum[i]);
I was writing a C program to find inversions in an array. The program compiles smoothly but as soon as I run it, it displays a garbage value where I take the array as a input. The program is given below:
#include <stdio.h>
#include <stdlib.h>
int checkInversions(int arr[], int n) {
int i, j, inverse_count = 0;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
inverse_count++;
}
}
}
return inverse_count;
}
int main() {
int arr[10], i, n;
printf("Enter the elements of the array: %d");
for (i = 0; i <= 10; i++) {
scanf("%d", &arr[i]);
}
n = sizeof(arr) / sizeof(arr[0]);
printf("\n The inverse is: %d", checkInversions(arr, n));
return 0;
}
Now, when the statement Enter the elements of the array: is displayed, just beside that is a garbage value like 623089. I am able to take the input but the result is not correct. What is the cause of this? Any help in this regard will be appreciated.
You are calling printf with a format specifier for %d and nothing passed to satisfy the variable expected by the format string. This is undefined behavior.
What you meant to do was merely:
printf("Enter the elements of the array: ");
Also, since arr has 10 elements, you iterate through it as such:
for(i = 0; i < 10; i++)
You don't need to use sizeof to determine the size of the array since you already know it; it's 10.
I think you are missing the variable that should populate the %d on the printf.
Try taking out the %d on the printf call so it ends up like:
printf("Enter the elements of the array: ");
Or assign the corresponding variable to display with that "%d", like this:
printf("Enter the elements of the array: %d", variable);
Check if that helps!
Your problem is printf("Enter the elements of the array: %d");. You tell the program that you want to print an integer, but you do not specify which integer that is. Remove the %d and the garbage value will be gone, like this: printf("Enter the elements of the array: ");
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
For some reason when I reallocate the size of the array created using calloc it deletes the values that have already been inputted, maybe something else is happening but i don't understand why. I have changed the code so that it includes everything it needs to work, sorry i forgot about that
#include <stdio.h>
#include <stdlib.h>
int main(void) {
unsigned int arraySize; // size of array
int moreElements; // stores user input whether more elements are to be
int additionalElements = 0; // number of elements to be added to array
unsigned int type; // stores the type of array
float sum = 0; // the sum of the elements
float *floatArrPtr; // pointer to a flaot
floatArrPtr = calloc(arraySize, sizeof(float));
for(size_t i = 0; i < arraySize; i++)
{
printf("Please enter a number for the array: ");
scanf("%f", &floatArrPtr[i]);
printf("%f\n", floatArrPtr[i]);
}
for(size_t i = 0; i < arraySize; i++)
{
sum += *(floatArrPtr+i);
}
sum /= arraySize;
printf("The average of the elements of the array is %lf\n", sum);
do
{
printf("if there are more elements to be added enter 1 and 0 if not: ");
scanf("%d", &moreElements);
} while (moreElements != 0 && moreElements != 1);
if (moreElements == 1) {
printf("please enter the number of additional elements you want to add: ");
scanf("%d", &additionalElements);
floatArrPtr = realloc(intArrPtr,(arraySize+additionalElements) * sizeof(float));
for (size_t i = arraySize; i < arraySize+additionalElements; i++)
{
printf("Please enter a number for the array: ");
scanf("%f", &floatArrPtr[i]);
}
sum = 0;
for(size_t i = 0; i < arraySize+additionalElements; i++)
{
sum += *(floatArrPtr+i);
printf("%zu, %lf, %d\n", i, floatArrPtr[i], arraySize + additionalElements);
}
sum /= (arraySize + additionalElements);
printf("The average of the elements of the array is %lf\n", sum);
}
}
That calloc code at the top is wrong. For an arraySize of 1000 it allocates a million floats, or 4MB. Look that up.
Then I assume the real problem is the intArrayPtr that slipped in from earlier code.
Use functions, they pay off. – I mean make all your code no more than 4 lines or so long per function, this will stop old variables from earlier from slipping in.
The wrong line is
floatArrPtr = realloc(intArrPtr...
You need
floatArrPtr = realloc(floatArrPtr...
I don't know the purpose of intArrPtr, but it looks like if that code compiles that its coming in from code above.
You have global variables. One must be very careful with them as they are a pain at best, at worst they cause unforeseen edge case bugs, which is what you have.
Make your project two files, one for integer and one for float, and you will see your mistake in the compiler.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm a newbie in programming.
I've tried this code to find out the maximum value in an array. I've also drawn the logic of this code on paper & it's coming out valid.
I'm wondering why this code is printing garbage value instead of max value.
Here is the code:
void main(){
int size, i, max=0;
printf("Enter the size of the array:\n");
scanf("%d", &size);
int a[size];
printf("Enter the elements:\n");
for(i=0; i<size; i++){
scanf("%d", &a[i]);
}
for(i=0; i<size; i++){
if(a[i]<a[i+1]){
max=a[i+1];
}
}
printf("\nMax value is %d", max);
}
You can try this code..
int main(){
int size, i, max=0;
printf("Enter the size of the array:\n");
scanf("%d", &size);
int a[size];
printf("Enter the elements:\n");
for(i=0; i<size; i++){
scanf("%d",&a[i]);
}
// Search Max Value
max = a[0];
for (i = 0; i < size; i++)
{
if (a[i] > max)
{
max = a[i];
}
}
printf("\nMax value is %d", max);
return 0;
}
You need to initialize max somewhere prior to searching the array (which the current copy of the post does do ... but the first one did not). However, if negative values are entered, it probably makes sense to use INT_MIN.
max = INT_MIN;
And then you need to compare the current max value against the array elements (rather than the array elements against themselves.
At this point, in your code, you're going outside of your array. You're also not comparing the element of the array to the current max, but to the next element in the array. This would be for sorting an array, but not finding the maximum value.
for(i=1; i<=size; i++){ /* i<=size */ you go one beyond
if(a[i]<a[i+1]){ /* when i==size, you're 2 outside of your array */
max=a[i+1];
}
}
You can have i<(size-2), but it's not very pretty.
You can also set max to the first element of the array, and loop from the second element.
max = a[0];
for(i=1 ; i<size ; i++){ /* loop to the end of the array */
if(a[i] > max){ /* compare current space to max */
max = a[i];
}
}
main has return type int, always. Valid prototypes:
int main()
int main(int argc, char* argv[])
Starting with 0 as initial value for maxinstead of INT_MIN means you have an implicit element of value 0.
Always test the return value of scanf, it might not succeed.
Your second loop tries reading a[size] and a[size+1], while your array only goes to index size-1.
Correct the termination condition to <.
Correct the comparison to compare a[i] with max.