How to repeat scanf() n times? - c

I ask the user to input two integers, n and x. After that, I need to ask them for a value for the a variable n times. I need to create a new a variable for each value. How do I do it? I have absolutely no idea.
Also, I need to do it in one line, so the input will be, for example, 50 30 21, not
50
30
21
Thanks.
#include <stdio.h>
int main (void) {
int a, n, x;
int i = 0;
scanf ("%d%d", &n, &x);
scanf ("%d", &a); /* what should I do here? */
}

Try this:
int arr[100]; // static allocation but you can also allocate the dynamically memory
printf("Enter the number for how many time repeat scanf()\n");
scanf("%d",&n);
for (int i = 0; i < n; i++)
{
scanf("%d",&arr[i]);
}

Try the below code:
#include <stdio.h>
int main (void) {
int a[100];
int n, x;
int i = 0;
scanf ("%d%d", &n, &x);//n cannot be greater than 100 in this case.
for(i = 0; i < n; i++)
{
scanf ("%d", &a[i]);
}
return 0;
}

Using dynamic memory:
#include <stdio.h>
#include <stdlib.h>
int main (void) {
int *a = NULL;
int n, x, i;
scanf("%d%d", &n, &x);
if (n <= 0) {
fprintf(stderr, "n must be > 0\n");
return 1;
}
a = malloc(n * sizeof(int));
if (a == NULL) {
fprintf(stderr, "failed to allocate memory for "
"%d integers\n", n);
return 1;
}
/* reading the user input */
for (i = 0; i < n; i++) {
scanf ("%d", &a[i]);
}
/* usage */
for (i = 0; i < n; i++) {
printf("a[%d] = %d\n", i, a[i]);
}
printf("x = %d\n", x);
free(a);
return 0;
}

After that, I need to ask them for a value for the a variable n times.
High Level Programming Languages and even Assembly Language (Conditional/Unconditional Jump) provide Loop constructs to a programmer. In computer programming, a loop is a sequence of instructions that is continually repeated until a certain condition is reached. In C/C++, we have for, while, do while loop constructs.
So, i order to ask a user for a value for n times, you can use for loop in your program. I have given an example below:
#include <stdio.h>
#define MAX_ARR_LEN 100
int main (void)
{
int a[MAX_ARR_LEN];
int n, x;
int i = 0;
scanf ("%d%d", &n, &x);
if (n > MAX_ARR_LEN) {
printf("You can't enter more than - %d\n", MAX_ARR_LEN);
return -1;
}
for(i = 0; i < n; i++) {
scanf ("%d", &a[i]);
}
return 0;
}

When you do scanf, it takes the input until the space character, which is a delimiter. You do not need to specify anything extra for that.
If you do not need to use the value of n again, you could use this code.
#include <stdio.h>
#include <stdlib.h>
int main (void) {
int n, x, i;
scanf ("%d%d", &n, &x);
int *a = (int *) malloc (n * sizeof(int)); //This will allocate 'n' integer sized memory for 'a'
for(i = 0; i < n; i++) {
scanf ("%d", &a[i]);
}
}

Related

Finding a number ( to be read from keyboard) in the list , where the size of list and the list is to be read from the keyboard

I am not able to figure out the error in the following code where I want to check a number in the list, the code prints yes, if it's present, and no if not. The output that I receive is random yes and no. Sometimes it's correct but other times, it's wrong.
{
int n, N, a[n], i, flag = 0;
printf("n , N\n");
scanf("%d%d", &n, &N);
printf("a\n");
for(i = 0; i < n; i++)
scanf("%d", &a[i]);
for (i = 0; i < n; i++)
{
if(a[i] == N)
{
flag = 1;
break;
}
}
if(flag == 0)
printf("No\n");
else
printf("Yes\n");
return 0;
}
I am trying to take an array with size n, which the user will input afterwards in the code and simultaneously while declaring the size I am entering the value of N, which is to be found in the list .. then using for loop I am comparing every number stored, but I think here the code fails.
The problem statement says you need to find out whether the value given as N exists among the n values given. It does not require you to store those n values.
So it's enough to check each of them as soon as it arrives and ...abandon it, memorizing just a positive result of test. No array needed.
Here is a simplified implementation:
int n, N, a, i, flag = 0;
puts("n , N");
scanf("%d%d", &n, &N);
puts("a");
for(i = 0; i < n; i++) {
scanf("%d", &a);
if(a == N)
flag = 1;
}
puts(flag ? "Yes" : "No");
At first, try to understand what 'some programmer dude' commented on your post. There is a bug in your code. You declared the array a[n], while the variable n is not initialized yet. So at first, you need to declare a pointer *a, then take the size of the array as an input from the user, and then finally allocate memory in pointer *a with the malloc() function. So here is the working code:
#include<stdio.h>
#include <stdlib.h>
int main()
{
int n, N, *a, i, flag = 0;
printf("n , N\n");
scanf("%d%d", &n, &N);
a = (int *) malloc(sizeof(int) * n);
printf("a\n");
for(i = 0; i < n; i++)
scanf("%d", &a[i]);
for (i = 0; i < n; i++)
{
if(a[i] == N)
{
flag = 1;
break;
}
}
free(a);
if(flag == 0)
printf("No\n");
else
printf("Yes\n");
return 0;
}

I want to make a program in C which takes an array as an input and tells which number are perfect squares

#include<stdio.h>
#include<math.h>
int perfectSquare(int arr[], int n);
int main()
{
int n , arr[n];
printf("number of elements to store in array");
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
printf("enter %d number", i+1);
scanf("%d", &arr[i]);
}
perfectSquare(arr, n);
return 0;
}
int perfectSquare(int arr[], int n)
{
int i;
int a;
for (i = 0; i <= n; i++) //i=4 arr[4]==9 //arr[1]=2 i=1
{
a=sqrt((double)arr[i]); //a=3 //a=1.454=1
if ( a*a==arr[i] ) //a==3*3==9==arr[4] //a*a=1!=arr[2]
printf("%d", arr[i]);
}
}
I am new to coding and I am currently learning c. I came up with this code but it doesn't work can someone tell me what is the problem with this code?
There are a couple of issues with this exercise, but generally you're on the right track. Here, a version of your example with some possible corrections:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void perfect_square(int arr[], int n);
int main(void)
{
int i, n, *arr;
printf("number of elements to store in array: ");
scanf("%d", &n);
if (n <= 0)
return -1;
arr = malloc(n*sizeof(int));
if (arr == NULL)
return -2;
for (i = 0; i < n; i++) {
printf("enter number %d: ", i+1);
scanf("%d", &arr[i]);
}
perfect_square(arr, n);
free(arr);
arr = NULL;
return 0;
}
void perfect_square(int arr[], int n)
{
int i, a;
for (i = 0; i < n; i++) {
a = (int)sqrt((double)arr[i]);
if (a*a == arr[i])
printf("%d ", arr[i]);
}
}
Some hints:
Arrays, that have an unknown size at compile time are usually allocated with malloc(), and must be deallocated again with free() (see also: alloca(), calloc(), realloc()). (In "more recent versions of C" there is also the possibility to use variable length arrays, but those can limit the portability of the code).
Always make sure to check the start value and end condition of for-loops, to prevent out of bound errors.
And try to consistently format the code, use good names and nice indentation to improve read-, maintain-, reusablilty.

How to read space-separated integers representing the array's elements and sum them up in C

How to read space-separated integers representing the array's elements and sum them up in C?
I used the below code but it reads all the elements in a new line:
#include <math.h>
#include <stdio.h>
int main() {
int i = 0, N, sum = 0, ar[i];
scanf("%d" , &N);
for (i = 0; i < N; i++) {
scanf("%d", &ar[i]);
}
for (i = 0; i < N; i++) {
sum = sum + ar[i];
}
printf("%d\n", sum);
return 0;
}
Your array ar is defined with a size of 0: the code invokes undefined behavior if the user enters a non zero number for the number of items.
Furthermore, you should check the return value of scanf(): if the user enters something not recognized as a number, your program will invoke undefined behavior instead of failing gracefully.
Here is a corrected version:
#include <stdio.h>
int main(void) {
int i, N, sum;
if (scanf("%d", &N) != 1 || N <= 0) {
fprintf(stderr, "invalid number\n");
return 1;
}
int ar[N];
for (i = 0; i < N; i++) {
if (scanf("%d", &ar[i]) != 1) {
fprintf(stderr, "invalid or missing number for entry %d\n", i);
return 1;
}
}
sum = 0;
for (i = 0; i < N; i++) {
sum += ar[i];
}
printf("%d\n", sum);
return 0;
}
Note that the program will still fail for a sufficiently large value of N as there is no standard way to check if you are allocating too much data with automatic storage. It will invoke undefined behavior (aka stack overflow).
You should allocate the array with malloc() to avoid this:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int i, N, sum;
int *ar;
if (scanf("%d", &N) != 1 || N <= 0) {
fprintf(stderr, "invalid number\n");
return 1;
}
ar = malloc(sizeof(*ar) * N);
if (ar == NULL) {
fprintf(stderr, "cannot allocate array for %d items\n", N);
return 1;
}
for (i = 0; i < N; i++) {
if (scanf("%d", &ar[i]) != 1) {
fprintf(stderr, "invalid or missing number for entry %d\n", i);
return 1;
}
}
sum = 0;
for (i = 0; i < N; i++) {
sum += ar[i];
}
printf("%d\n", sum);
free(ar);
return 0;
}
Finally, there is still a possibility for undefined behavior if the sum of the numbers exceeds the range of type int. Very few programmers care to detect such errors, but it can be done this way:
#include <limits.h>
...
sum = 0;
for (i = 0; i < N; i++) {
if ((sum >= 0 && arr[i] > INT_MAX - sum)
|| (sum < 0 && arr[i] < INT_MIN - sum)) {
fprintf(stderr, "integer overflow for entry %d\n", i);
return 1;
}
sum += ar[i];
}
#include <math.h>
#include <stdio.h>
int main()
{
int i=0,N,sum=0;
scanf("%d" ,&N);
int ar[N];
for(i=0; i<N; i++)
scanf("%d",&ar[i]);
for(i=0; i<N; i++)
sum=sum+ar[i];
printf("%d\n", sum);
return 0;
}
This should be the code.
You have initially declared the array of size 0 (because i=0).
Even though you declared the array of size 0, when I ran it on my machine, it actually executed successfully with the correct output.
This is generally due to undefined behavior which means that we can only guess the output when the code is correct. If the code has undefined behavior, then it can do whatever it wants (and in the worst case the code will execute successfully giving the impression that it's actually correct).
Declaring a Variable Size Array (VLA) is optional in C11 standard. Thus, it depends on the implementation of the compiler whether it will support VLA or not. As pointed out by #DavidBowling in comments, if the compiler does support, then declaring a VLA of size 0 can invoke undefined behavior (which you should avoid in all cases). If it doesn't support, then this will simply give a compilation error and you'll have to declare the array size as some integer constant (example, int arr[100];).
#include <math.h>
#include <stdio.h>
int main()
{
int i=0,N,sum=0;
scanf("%d" ,&N);
int ar[N];
for(i=0; i<N; i++)
{
scanf("%d",&ar[i]);
}
for(i=0; i<N; i++)
{
sum=sum+ar[i];
}
printf("%d\n", sum);
return 0;
}
You should declare the array after accepting the value of N.
#include <math.h>
#include <stdio.h>
int main()
{
int i=0,N,sum=0;
scanf("%d" ,&N);
int ar[N];
for(i=0; i<N; i++)
{
scanf("%d",&ar[i]);
sum=sum+ar[i];
}
printf("%d\n", sum);
return 0;
}
As this is a very simple question I'll expand it a bit to include some good programming practices.
1. Analyze the problem
We have to complete two tasks here:
Read and store the numbers to array.
Sum the array elements.
Of course you can both read and calculate the same time, but we ❤ the SoC design principle. This will help you later with bigger programs.
2. Create the program structure
In this state we have to consider what function to use, as we already solved the data structure problem (we use array).
Of course, we always can put the whole procedure in main function but this would break the SoC principle.
The main principle here is:
I create a function for a separate procedure.
So we'll have to build two functions. Let's consider the following example:
ReadArrayData will be used to read the data from the standard input (your keyboard in other words) to array. But what will declare as parameters? We surely have to pass the array and the array size. The return type of this function will be void (we don't have to return something).
Keep in mind that if you pass array to function you can manipulate it as you please and keep these changes in your main program. This is because the arrays are passed always by reference to a function.
In the end this will be your function prototype:
void ReadArrayData(int arraySize, int array[]);
CalculateArraySum will be used to calculate the sum of the array elements. The function prototype will be the same as for ReadArrayData with the difference that the returning type will be int (we return the sum).
int CalculateArraySum(int arraySize, int array[]);
3. Write your program
#include <stdio.h>
void ReadArrayData(int arraySize, int array[]);
int CalculateArraySum(int arraySize, int array[]);
int main(void) {
int N;
printf("Give the array size: ");
scanf("%d", &N);
int array[N];
ReadArrayData(N, array);
int sumOfArrayElements = CalculateArraySum(N, array);
printf("The sum of array elements is %d.\n", sumOfArrayElements);
return 0;
}
void ReadArrayData(int arraySize, int array[]) {
printf("Give %d elements: ", arraySize);
for (int i = 0; i < arraySize; ++i) {
scanf("%d", &array[i]);
}
}
int CalculateArraySum(int arraySize, int array[]) {
int sum = 0;
for (int i = 0; i < arraySize; ++i) {
sum += array[i];
}
return sum;
}
I know this was a large scaled answer, but I saw you are new to computer programing. I just wanted to present you the main functionality to solve all kinds of problems. This was just a small introduction. In the end, you have to remember what steps we take to solve a problem. With time and as you solve many problems you will learn many many other things.

I'm trying to use the malloc function to allocate memory for an array but the the values aren't scanning in properly. Can anyone explain?

So I was asked to write a program that tests whether a sequence of integers input by the user is a palindrome or not (reads same backwards as forwards). I can't figure out how to dynamically allocate memory so that the input can be of variable length. In the code you can see that the user enters the number of elements in their sequence, n. But during compilation, when n integers have been entered nothing happens. What is wrong with the code? Please explain in detail as much as possible, and if you know of any good references share them!! I'm struggling with pointers and arrays.
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i, n, x;
int* intarray;
printf("\nHow many integers are there?: \n");
scanf("d", &n);
intarray = (int*)malloc(n * sizeof(int));
printf("\nPlease enter the values:\n");
for (i = 0; i < n; i++)
{
scanf("%d", &intarray[i]);
}
n = n - 1;
x = n / 2;
for (i = 0; i <= x; i++)
{
if (intarray[i] != intarray[n - i])
{
printf("\nThis is not a palindrome\n");
return;
}
if (i = x)
{
printf("\nThis is a palindrome\n");
}
}
return;
}
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i, n, x;
int* intarray;
printf("\nHow many integers are there?: \n");
scanf("%d", &n); // and as mentioned by all above type specifier % is missing in %d (for integer type)
intarray = (int*)malloc(n * sizeof(int));
printf("\nPlease enter the values:\n");
for (i = 0; i < n; i++)
{
scanf("%d", &intarray[i]);
}
n = n - 1;
x = n / 2;
for (i = 0; i <= x; i++)
{
if (intarray[i] != intarray[n - i])
{
printf("\nThis is not a palindrome\n");
return;
}
if (i = x)
{
printf("\nThis is a palindrome\n");
}
}
return 0; // as your main()'s return type is int, you should should return an integer value
}
The problem is with the scanf("d", &n); statement that actually does not read anything into n as in order to read an integer you should use "%d" instead of "d".
2 changes:
1.
scanf("%d", &n);
%d is the format specifier for scanning integers.
2.
intarray = malloc(n * sizeof(int));
No need to cast malloc()

storing input into malloc array (1d and 2d) and printing

I am tryin to take input from the user and store it into an array and print it out: i have 2 functions:
/* Read a vector with n elements: allocate space, read elements,
return pointer */
double *read_vector(int n){
double *vec = malloc(n * sizeof(double));
int i;
for (i = 0; i < n; i++)
vec[i] = n;
return vec;
}
and the print function is:
void print_vector(int n, double *vec){
int i;
for (i = 0; i < n; i++) {
printf("%d\n", vec[i]);
}
}
the main function is:
#include <stdio.h>
#include <stdlib.h>
double *read_vector(int n);
void print_vector(int n, double *vec);
void free_vector(double *vec);
int main(){
int n;
double *vector;
/* Vector */
printf("Vector\n");
printf("Enter number of entries: ");
scanf("%d", &n);
printf("Enter %d reals: ", n);
vector = read_vector(n);
printf("Your Vector\n");
print_vector(n,vector);
free_vector(vector);
}
when i run this, it does not let me enter any numbers, it just skips it and prints out 0's. How do i fix this?
Try the code below. You're almost certainly either not compiling with warnings, or ignoring the warnings. All warnings mean something, and to a beginner they all matter. With gcc use the -Wall option, or even -pedantic.
As halfelf pointed out, you need a scanf in your read loop but it needs to be a pointer (&vec[i]). Always return something at the end of main. Also check the return value of malloc, it could fail and return a null pointer.
#include <stdio.h>
#include <stdlib.h>
double *read_vector(int n)
{
double *vec = malloc(n * sizeof(double));
int i;
for (i = 0; i < n; i++) {
printf("Enter number %i of %i: ", i + 1, n);
scanf("%lf", &vec[i]);
}
return vec;
}
void print_vector(int n, double *vec)
{
int i;
for (i = 0; i < n; i++) {
printf("%f\n", vec[i]);
}
}
void free_vector(double *vec)
{
free(vec);
}
int main()
{
int n;
double *vector;
printf("Vector\n");
printf("Enter number of entries: ");
scanf("%i", &n);
vector = read_vector(n);
printf("Your Vector\n");
print_vector(n, vector);
free_vector(vector);
return 0;
}
In the read_vector(int n) function's for loop:
for (i=0; i<n; i++)
vec[i] = n; // this should be scanf("%lf",vec+i) to read input from stdin
and notice your { and } there. If there's only one line in the loop, { and } is not necessary, OR you have to use a pair of them. The return clause must be out of the loop.
Btw, add return 0 at the end of your main function.
simple..you forgot to write scanf..!
double *read_vector(int n)
{
double *vec = malloc(n * sizeof(double));
int i;
for (i = 0; i < n; i++)
scanf("%d",&vec[i]);
return vec;
}

Resources