scanf() problems in C - arrays

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]);

Related

Getting inputs with scanf for an array

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.

Output the input Array in C [closed]

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:

How to add 'nothing' into int array in C

I have a task to sort an integer array into an even number array and odd number array. Then i have to show what digits has been placed in which. However, in my code not all places of the array are occupied, so in the end i receive random numbers when I want to show what the arrays odds and evens contain. Instead of random numbers I would like to have literally nothing added in their place.
I did the following:
int main()
{
int evens[10], whole[10], odds[10], i;
printf("Enter 10 integer(/whole) numbers\n");
for (i = 0; i < 10; i++)
{
scanf("%d", &whole[i]);
if (whole[i] % 2 == 0)
{
evens[i] = whole[i];
else odds[i] = whole[i];
}
}
printf("Your even numbers are the following:\n");
for (i = 0; i < 10; i++)
{
printf("%d\n", evens[i]);
}
printf("Your odd numbers are the following:\n");
for (i = 0; i < 10; i++)
{
printf("%d\n", odds[i]);
}
return 0;
}
and then I get this output for having entered digits from 1 to 10:
Your even numbers are the following:
-1832565259
2
1985901418
4
4200864
6
4200958
8
74
10
Your odd numbers are the following:
1
4200864
3
6356652
5
1986281400
7
1985964450
9
1985901427
So how do i get an odds/even array without these random digits like 1985964450 in between? Is there a command to add literally nothing instead?
You should have a counter of odds and a counter of evens.
int oddcount = 0;
int evencount = 0;
When you decide that a number is even, you use this counter to know where in the array it should go. For example:
if (whole[i] % 2 == 0) {
evens[evencount] = whole[i];
evencount++;
}
Notice that evencount not only gives you the number of even numbers, but since arrays indices begin at zero, it also tells you what is the position of the next even number.
Then you modify your for loops at the end to use the actual number of even and odd numbers that were typed. You can even check for zero and print a specific message such as No even numbers supplied.
Also, unless you have been specifically asked to keep the input numbers in an array, you don't need whole. You can do just like so:
int input;
for (i=0; i<10; i++)
{
scanf("%d", &input);
if (input %2 == 0)
/* ... */
else
/* ... */
}
As a final remark, you should indent your code. Indentation is simply augmenting the number of spaces before the code (like I did inside the ifs above). It is very important to indent your code because it makes the structure of your code clear. For a more comprehensive discussion on this, read here: Importance of code indentation.
It is better to have two variables that represents indexes, one you use to add odd numbers, other to add even numbers. Then you will have two arrays without redundant data :)
int evensIndex = 0;
int oddsIndex = 0;
for (i=0; i<10; i++)
{
scanf("%d", &whole[i]);
if (whole[i] %2 == 0)
{
evens[evensIndex] = whole[i];
evensIndex++;
}
else
{
odds[oddsIndex] = whole[i];
oddsIndex++;
}
}
int main()
{
int evens[10], temp, odds[10], i;
int oddIndex = 0, evenIndex = 0;
printf("Enter 10 integer(/whole) numbers\n");
for (i=0; i<10; i++)
{
scanf("%d", &temp);
if(temp%2)
odd[oddIndex++]=temp;
else
even[evenIdex++]=temp;
}
printf("Your even numbers are the following:\n");
for (i=0; i<10; i++)
printf("%d\n", evens[i]);
printf("Your odd numbers are the following:\n");
for (i=0; i<10; i++)
printf("%d\n", odds[i]);
return 0;
}

How to compare the digits of 2 integer numbers in c (without arrays and strings)

I am making simple example of little game about guessing numbers.
And I want to build a function which check the numbers and make two values as follows:
1) hits-the number of digits that contain in both number and in same place for both numbers.
2) misses-the number of the digits which contain in both number but not in the same place.
For example:
int systemNumber=1653;
int userGuess=5243;
in this example, in both numbers there are the digits 5 and 3. In both numbers the digit 3 in the same place. But, the digit 5 in systemNumber is not in the same place as userNumber. So, we have here 1 hit and 1 miss.
I've written the code for it with arrays, and I'd like to know if there is a way that I will be able to do this without array and strings.
Here is my code. Please, if you have any improvement for my code, I'd like to know it :)
#include <stdio.h>
#include <stdlib.h>
void checkUserCode(int num1[4], int num2[4]); // declare the function which check the guess
int hits=0, misses=0; // hits and misses in the guess
int main(void)
{
int userCode=0;
int userCodeArray[4];
int systemCodeArray[4]={1, 4, 6, 3};
int i=0;
// printing description
printf("welcome to the guessing game!\n");
printf("your goal is to guess what is the number of the system!\n");
printf("the number have 4 digits. Each digit can be between 1 to 6\nGood Luck!\n");
// input of user guess
printf("enter number: ");
scanf("%d", &userCode);
for (i=3; i>=0; i--)
{
userCodeArray[i]=userCode%10;
userCode=userCode/10;
}
checkUserCode(systemCodeArray, userCodeArray);
printf("there are %d hits and %d misess", hits, misses); // output
return 0;
}
/*
this function gets two arrays and check its elements
input (parameters): the two arrays (codes) to check
output (returning): number of hits and misses
if the element in one array also contains in the other array but not the same index: add a miss
if the element in one array also contains in the other array and they have the same index: add a hits
*/
void checkUserCode(int num1[4], int num2[4])
{
int i=0, j=0;
for (i=0; i<4; i++)
{
for (j=0; j<4; j++)
{
if(num1[i]==num2[j])
{
if (j==i)
hits++;
else
misses++;
}
}
}
}
Here is an example I wrote a while ago, which I tweaked for your problem:
I basically uses two for loops, the outer loop going over the first number, 1653, and the inner loop going over the second number, 5243. It basically compares each individual number in the first number against all the numbers in the second number.
Depending on the counters, it evaluates if equal numbers have been matched in the same positions, using modulo %10 to compare each number.
This is the code:
#include <stdio.h>
#include <stdlib.h>
int
main(void) {
int num1 = 1653;
int num2 = 5243;
int pos1, pos2, hit = 0, miss = 0, i, j;
pos1 = 0;
for (i = num1; i > 0; i /= 10) {
pos2 = 0;
for (j = num2; j > 0; j /= 10) {
if (i % 10 == j % 10) {
if (pos1 == pos2) {
hit++;
} else {
miss++;
}
}
pos2++;
}
pos1++;
}
printf("hits = %d\n", hit);
printf("misses = %d\n", miss);
return 0;
}

Returning to the start of a for loop in C

Even though this question has been asked a million times I just haven't found an answer that actually helps my case, or I simply can't see the solution.
I've been given the task to make a program that takes in a whole number and counts how many times each digit appears in it and also not showing the same information twice. Since we're working with arrays currently I had to do it with arrays of course so since my code is messy due to my lack of knowledge in C I'll try to explain my thought process along with giving you the code.
After entering a number, I took each digit by dividing the number by 10 and putting those digits into an array, then (since the array is reversed) I reversed the reverse array to get it to look nicer (even though it isn't required). After that, I have a bunch of disgusting for loops in which I try to loop through the whole array while comparing the first element to all the elements again, so for each element of the array, I compare it to each element of the array again. I also add the checked element to a new array after each check so I can primarily check if the element has been compared before so I don't have to do the whole thing again but that's where my problem is. I've tried a ton of manipulations with continue or goto but I just can't find the solution. So I just used **EDIT: return 0 ** to see if my idea was good in the first place and to me it seems that it is , I just lack the knowledge to go back to the top of the for loop. Help me please?
// With return 0 the program stops completely after trying to check the digit 1 since it's been checked already. I want it to continue checking the other ones but with many versions of putting continue, it just didn't do the job. //
/// Tried to make the code look better. ///
#include <stdio.h>
#define MAX 100
int main()
{
int a[MAX];
int b[MAX];
int c[MAX];
int n;
int i;
int j;
int k;
int counter1;
int counter2;
printf("Enter a whole number: ");
scanf("%i",&n);
while (1)
{
for (i=0,counter1=0;n>10;i++)
{
a[i] = n%10;
n=n/10;
counter1+=1;
if (n<10)
a[counter1] = n;
}
break;
}
printf("\nNumber o elements in the array: %i", counter1);
printf("\nElements of the array a:");
for (i=0;i<=counter1;i++)
{
printf("%i ",a[i]);
}
printf("\nElements of the array b:");
for (i=counter1,j=0;i>=0;i--,j++)
{
b[j] = a[i];
}
for (i=0;i<=counter1;i++)
{
printf("%i ",b[i]);
}
for (i=0;i<=counter1;i++)
{
for(k=0;k<=counter1;k++)
{
if(b[i]==c[k])
{
return 0;
}
}
for(j=0,counter2=0; j<=counter1;j++)
{
if (b[j] == b[i])
{
counter2+=1;
}
}
printf("\nThe number %i appears %i time(s)", b[i], counter2);
c[i]=b[i];
}
}
The task at hand is very straightforward and certainly doesn't need convoluted constructions, let alone goto.
Your idea to place the digits in an array is good, but you increment counter too early. (Remember that arrays in C start with index 0.) So let's fix that:
int n = 1144526; // example number, assumed to be positive
int digits[12]; // array of digits
int ndigit = 0;
while (n) {
digits[ndigit++] = n % 10;
n /= 10;
}
(The ++ after ndigit will increment ndigit after using its value. Using it as array index inside square brackets is very common in C.)
We just want to count the digits, so reversing the array really isn't necessary. Now we want to count all digits. We could do that by counting all digits when we see then for the first time, e.g. in 337223, count all 3s first, then all 7s and then all 2s, but that will get complicated quickly. It's much easier to count all 10 digits:
int i, d;
for (d = 0; d < 10; d++) {
int count = 0;
for (i = 0; i < ndigit; i++) {
if (digit[i] == d) count++;
}
if (count) printf("%d occurs %d times.\n", d, count);
}
The outer loop goes over all ten digits. The inner loop counts all occurrences of d in the digit array. If the count is positive, write it out.
If you think about it, you can do better. The digits can only have values from 0 to 9. We can keep an array of counts for each digit and pass the digit array once, counting the digits as you go:
int count[10] = {0};
for (i = 0; i < ndigit; i++) {
count[digit[i]]++;
}
for (i = 0; i < 10; i++) {
if (count[i]) printf("%d occurs %d times.\n", i, count[i]);
}
(Remember that = {0} sets the first element of count explicitly to zero and the rest of the elements implicitly, so that you start off with an array of ten zeroes.)
If you think about it, you don't even need the array digit; you can count the digits right away:
int count[10] = {0};
while (n) {
count[n % 10]++;
n /= 10;
}
for (i = 0; i < 10; i++) {
if (count[i]) printf("%d occurs %d times.\n", i, count[i]);
}
Lastly, a word of advice: If you find yourself reaching for exceptional tools to rescue complicated code for a simple task, take a step back and try to simplify the problem. I have the impression that you have added more complicated you even you don't really understand instead.
For example, your method to count the digits is very confused. For example, what is the array c for? You read from it before writing sensible values to it. Try to implement a very simple solution, don't try to be clever at first and go for a simple solution. Even if that's not what you as a human would do, remeber that computers are good at carrying out stupid tasks fast.
I think what you need is a "continue" instead of a return 0.
for (i=0;i<=counter1;i++) {
for(k=0;k<=counter1;k++) {
if(b[i]==c[k]) {
continue; /* formerly return 0; */
}
for(j=0,counter2=0; j<=counter1;j++)
if (b[j] == b[i]){
counter2+=1;
}
}
Please try and see if this program can help you.
#include <stdio.h>
int main() {
unsigned n;
int arr[30];
printf("Enter a whole number: ");
scanf("%i", &n);
int f = 0;
while(n)
{
int b = n % 10;
arr[f] = b;
n /= 10;
++f;
}
for(int i=0;i<f;i++){
int count=1;
for(int j=i+1;j<=f-1;j++){
if(arr[i]==arr[j] && arr[i]!='\0'){
count++;
arr[j]='\0';
}
}
if(arr[i]!='\0'){
printf("%d is %d times.\n",arr[i],count);
}
}
}
Test
Enter a whole number: 12234445
5 is 1 times.
4 is 3 times.
3 is 1 times.
2 is 2 times.
1 is 1 times.
Here is another offering that uses only one loop to analyse the input. I made other changes which are commented.
#include <stdio.h>
int main(void)
{
int count[10] = { 0 };
int n;
int digit;
int elems = 0;
int diff = 0;
printf("Enter a whole number: ");
if(scanf("%d", &n) != 1 || n < 0) { // used %d, %i can accept octal input
puts("Please enter a positive number"); // always check result of scanf
return 1;
}
do {
elems++; // number of digits entered
digit = n % 10;
if(count[digit] == 0) { // number of different digits
diff++;
}
count[digit]++; // count occurrence of each
n /= 10;
} while(n); // do-while ensures a lone 0 works
printf("Number of digits entered: %d\n", elems);
printf("Number of different digits: %d\n", diff);
printf("Occurrence:\n");
for(n = 0; n < 10; n++) {
if(count[n]) {
printf(" %d of %d\n", count[n], n);
}
}
return 0;
}
Program session:
Enter a whole number: 82773712
Number of digits entered: 8
Number of different digits: 5
Occurrence:
1 of 1
2 of 2
1 of 3
3 of 7
1 of 8

Resources