Get the unknown length of number from input [duplicate] - c

This question already has answers here:
how to scanf unknown amount of integer numbers into array in C?
(3 answers)
Closed 6 years ago.
I am doing a assignment which requires the input of a list of numbers and get the output when I press Enter on the keyboard. This is the code I am trying the use to get the list of numbers when I enter, but it doesn't work:
#include <stdio.h>
int main(){
int arra[100];
int i ;
int j = -1;
while (scanf("%d",&i) != 1){
arra[++j] = i;
}
printf("\n");
int k;
for(k = 0; k < j; k++){
printf("%d",arra[k]);
}
return 0;
}
I want to print the elements of arra.

First off, massive kudos for testing the return value from scanf, most people just blindly assume it works. It's just a shame you're using it in the wrong way :-)
You want the loop to continue as long as the return value is 1, meaning that you managed to scan an integer. That means it should be:
while (scanf ("%d", &i) == 1) {
That also means that any non-numeric input will cause scan failure and hence the while loop will exit. So, if you enter:
3 1 4 1 5 9 stop
you should successfully see the numeric values from the array.
The only other thing is to clean up your j handling since the k loop will stop early. This can be done with:
for (k = 0; k <= j; k++) {
Alternatively, leave that loop alone and just change how you initialise and modify j:
int j = 0;
:
arra[j++] = i;
I tend to find the second choice more C-like since j is then a count of the elements in the array rather than the maximum index.
And, of course, you're open to a buffer overflow attack at the moment since you assume nobody will enter more than a hundred numbers. So, don't use this as a homework solution (what you have is good enough with the slight bug fixes) but I'd tend to write it as something like:
#include<stdio.h>
#define SZ 100
int main (void){
int arra[SZ], i, nxt = 0;
while ((nxt < SZ) && (scanf ("%d", &(arra[nxt])) == 1))
nxt++;
printf ("\n");
for (i = 0; i < nxt; i++)
printf ("%d ", arra[i]);
return 0;
}

Check the below code:
#include<stdio.h>
int main(){
int arra [100];
int i ;
int k;
int j = 0; /* index from 0 */
printf("Keep entering numbers and press q once done \n");
while (scanf("%d",&i) == 1){ /* scan for integers */
arra[j++] = i;
}
printf("\n");
for(k = 0; k < j; k++){
printf("%d",arra[k]);
}
return 0;
}

Related

how to prevent the user from entering symbols and letters in [duplicate]

This question already has answers here:
Validate the type of input in a do-while loop
(5 answers)
How to check if input is an integer in C?
(2 answers)
Closed 3 months ago.
I'm trying to prevent the user from entering a wrong value(letters and symbols) in this C program but I did not find any information on this and I have no idea how to do it in my code please help me I will be very grateful
#include <stdio.h>
void main ()
{
int number[30];
int i, j, a, n;
printf("Enter the value of N\n");
scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; ++i)
scanf("%d", &number[i]);
// sorting begins
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (number[i] < number[j])
{
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
printf("The numbers arranged in descending order are given below\n");
for (i = 0; i < n; ++i)
{
printf("%d\n", number[i]);
}
}
You can't stop a user from entering invalid input, but what you can do is try to validate it.
From the man page:
RETURN VALUE:
On success, these functions return the number of input items successfully matched and assigned; this can be fewer than provided for, or even zero, in the event of an early matching failure.
if((scanf("%d", &n) != 1)
{
... print error message here
exit(EXIT_FAILURE);
}
Note: Scanf would happily match and assign the value to n if the input was a floating point number, by discarding the mantissa.
A number followed by some alphabets would also be accepted, and the trailing junk would be left in the input buffer for subsequence input calls to deal with.
A better option would be to read a whole line with fgets, and parse it with sscanf, strtol etc.
You can refer to their man pages for help.

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.

C - Break while loop when typing the number 0 into a vector

I have this simple code that inserts the number entered in the terminal at the position of the vector at each loop.
int main()
{
int vector[5];
int i;
for (i = 0; i < 5; i++)
{
printf("Number: ");
scanf_s("%d", &vector[i]);
}
system("pause");
return 0;
}
My question is how I break the loop as soon as I type the number 0.
For example, imagine that my vector have 50 positions and I type 10 positions with positive integers numbers and now I want the loop ends when I enter zero and the rest of the 40 positions remain blank.
I imagine it's with the while loop, but I could not even get close to the result I want.
#define MAX_SIZE (5)
int main()
{
int vector[MAX_SIZE] = {0};
int i;
memset(vector, 0xFF, sizeof(vector)); //sets all vector[i] to -1 on init;
for (i = 0; (i < MAX_SIZE) && (i?vector[i-1]:1) ; i++) //you can add the condition to break from the for loop here. This is more complicated but its just for demonstration.
{
printf("Number: ");
scanf_s("%d", &vector[i]);
}
system("pause");
return 0;
}
The above sample code demonstrates the using the for loops conditional expression as a means to break the loop. The ternary in there prevents the i=0 case resulting in an out of bounds index, due to the way you structured your loop. The better/more readable way is below:
#define MAX_SIZE (5)
int main()
{
int vector[MAX_SIZE] = {0};
int i;
memset(vector, 0xFF, sizeof(vector)); //sets all vector[i] to -1 on init;
for (i = 0; i < MAX_SIZE; i++)
{
printf("Number: %d\n", i);
scanf_s("%d", &vector[i]);
if(vector[i] == 0)
{
break;
}
}
//system("pause");
printf("Broke the loop when i was %d\n", i);
return 0;
}
The difference between the two besides readability is that i will be incremented one extra time in the first one. Also, make sure to initialize all the variables you declare (all your vector elements are stack garbage, the 0xFF memset assigns them all to -1).

Question regarding allocating memory for array, sorting and numbers only in C programming

I have a program that I would like to dynamically allocate an array that gets filled by the user through the terminal argument line in Linux. After the user enters the numbers, the array of numbers should be sorted.
#include <stdio.h>
#include <stdlib.h>
int main(){
int i;
int array[100];
int count = 0;
while(1){
printf("please enter a number: \n");
scanf("%d", &i);
if(i == 0){
for (int k = 0; k < count -1; k++) {
if(array[k] <= array[k + 1]){
int temp = array[k];
array[k] = array[k+1];
array[k+1] = temp;
}
}
for (int j = 0; j < count; ++j)
{
printf("%d ", array[j]);
}
printf("\n");
break;
} else {
array[count] = i;
count++;
}
}
}
This only sorts the array if I type the numbers in low to high, but if I enter the numbers from high to low eg. 4, 3, 2 and then 1, it prints 2, 3, 1 and then 4, instead of the 1,2,3,4 that it does if I type it that way.
I don't want to initialize the array with 100, I just can't get it to work if I don't initialize it. I want it to be increased if necessary.
Thank you :)
Errors/Deviations from the proposed program:
As mentioned, you want to use command line arguments - You need main(argc,*argv[]) instead of main().
For dynamic allocation you need malloc/calloc but instead of that you have used static array.
Your code shows you are not clear about concept of sorting, leave the program aside and use a pen and paper first to clear that.

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