Similar function to the Java NextInt in C - c

In Java, you can use Scanner.nextInt to get the next input value. I have tried doing this is C:
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("How long is your array?");
int len;
scanf("%d",&len);
printf("Enter %d numbers:",len);
int array[len];
for (int i=0; i<len; i++){
scanf("%d", &array[i]);
}
for (int i=0; i<len; i++){
printf(array[i]);}
return 0;
}
But it will stop before printing the array, which makes me think that this is a false methode.

[Note: The question was edited after this answer was written.]
printf(array); will not work. You must print the array elements individually, using a loop similar to the one you used to read the values. C has very limited facilities for automatically working with aggregates.
Additionally, scanf("%d", array[i]); must be scanf("%d", &array[i]);. You need to tell scanf where to put the value it reads. Passing array[i] would tell scanf what the current value is. &array[i] is the address of where array[i] is. (When using printf, you will pass array[i], because printf only needs the value to print. It does not need to know where it is.)

Related

How to insert multiple elements in array in c program?

I can insert an element in an array but I want to know that is this possible to insert multiple(two or three..) element in an array by using c program. I tried a little, there is no problem or eror but it doesn't work.
Here is my code which I had tried to make a program which can insert multiple element in array:
#include<stdio.h>
int main(){
int size,i;
printf("Enter array length - ");
scanf("%d",&size);
int array[size];
printf("Enter array elements : \n");
for(i=0; i<size; i++){
scanf("%d",&array[i]);
}
int el_no; //el_no means elemnet no which user should input
printf("How many element you want to insert - ");
scanf("%d",&el_no);
int element[el_no];
printf("Element value - ");
for(i=0; i<el_no;i++){
scanf("%d",&element[i]);
}
int index[el_no];
printf("Index no - ");
for(i=0; i<el_no;i++){
scanf("%d",&index);
}
for(i=0; i<el_no;i++){
for(i=index[i]; i< size+el_no;i++){
array[i+1]=array[i];
}
}
for(i=0; i<el_no; i++){
array[index[i]]=element[i];
}
for(i=0; i<size+el_no; i++){
printf("%d\t",array[i]);
}
return 0;
}
You can't do what you want (at least, not directly). Once you say
int array[size];
that array can only hold size number of elements, no more.
Your program first stores values into array[0], array[1], ..., up to array[size-1]. That's perfectly fine.
But then when you say
for(i=0; i<el_no;i++){
for(i=index[i]; i< size+el_no;i++){
array[i+1]=array[i];
}
}
you are trying to move some of the array's elements over (to make room for new ones), but you're moving them outside the array, which is never going to work.
One fix (not quite what you want) would be to declare the array bigger than it needs to be. For example, you could say
int array[size+5];
and then later double-check that it will be big enough:
printf("How many element you want to insert - ");
scanf("%d",&el_no);
if(el_no > 5) {
printf("sorry, I can't insert that many\n");
exit(1);
}
The "better" way, although it gets into pointers and dynamic memory allocation perhaps sooner than you're ready to, would be to use a pointer simulating an array, using malloc to allocate space for it to point to:
int *array = malloc(size * sizeof(int));
Than, later, you can resize it:
array = realloc(array, (size + el_no) * sizeof(int));
This is just an example -- in reality, you'd need to check the return values of malloc and realloc to make sure they're not NULL, indicating that something has gone wrong.
Also there are some other problems with your code. The way you're using the auxiliary index array looks wrong, and probably isn't necessary at all.
As I tried to show in my comment, you're not specifying an index for the index array. In that loop, you're scanfing to &index, which is the wrong argument for scanf. Your compiler should be giving you a warning:
warning: format '%d' expects argument of type 'int *', but argument 2 has type 'int (*)[el_no]' [-Wformat=]
32 | scanf("%d",&index);
| ~^ ~~~~~~
| | |
| | int (*)[el_no]
| int *
Despite the warning, what's most likely happening is each value you enter in the loop is getting stored at index[0]. You need to change that loop from
for(i=0; i<el_no;i++){
scanf("%d",&index);
}
to
for(i=0; i<el_no;i++){
scanf("%d",&index[i]); // <-- note the [i] addition
}
You've done this correctly in the previous loop
for(i=0; i<size; i++){
scanf("%d",&array[i]);
}
This may not be the only problem, but it's a problem, and too long for a comment.
I've edited the code and stated where to correct the faults
#include<stdio.h>
int main(){
Initialize j here
int size,i,j;
printf("Enter array length - ");
scanf("%d",&size);
int array[size];
printf("Enter array elements : \n");
for(i=0; i<size; i++){
scanf("%d",&array[i]);
}
int el_no; //el_no means elemnet no which user should input
printf("How many element you want to insert - ");
scanf("%d",&el_no);
int element[el_no];
printf("Element value - ");
for(i=0; i<el_no;i++){
scanf("%d",&element[i]);
}
int index[el_no];
printf("Index no - ");
here is a mistake you can correct
for(i=0; i<el_no;i++){
scanf("%d",&index[i]);//Add[i] here
}
Also do not use same variable in more than one for loop in a nested loop
for(i=0; i<el_no;i++){
for(j=index[i]; j< size+el_no;j++){//Use any other variable than 'i' in this for loop
depending on what you want to do you can correct this line below
array[i+1]=array[i];
}
}
for(i=0; i<el_no; i++){
array[index[i]]=element[i];
}
for(i=0; i<size+el_no; i++){
printf("%d\t",array[i]);
}
return 0;
}
All is good.
Hope you find it useful.

C program displays garbage value while taking user input using scanf

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: ");

Trouble with horizontal frequency histogram

Am having many problems with coding C. Apologies for any bad mistakes. Im trying to do simple horizontal histogram for frequency of integers in array. No matter what it prints out incorrect and makes infinite loop. I believe the problem lies in printHistogram function. Any tips?
Here is code:
#include <stdio.h>
//Prints histogram to screen using horizontal bar chart
void printHistogram ( int *hist, int n );
int main ( void )
{
int i, n;
printf ("How many values for array? ");
scanf ("%d", &n);
int list[n];
for (i=0; i < n; i++) {
printf ("Enter value: ");
scanf ("%d", &list[i]);
}
// Process data to compute histogram
int hist[10];
// Print histogram
printHistogram ( hist, 10);
return 0;
}
void printHistogram ( int *list, int n )
{
int i, j;
for (i=0; i < n; i++) {
printf ("[%d] ", i);
for (j = 0; j < list[i]; j++)
printf ("*");
printf ("\n");
}
}
The problem is in
for (j = 0; j < list[i]; j++)
when, you're trying to use list[i], but based on the argument passed, the value is indeterminate. So, in this case, this invokes undefined behavior and the loop goes haywire.
To elaborate, you have defined int hist[10]; as a local variable and did not initialize it, so all the members contain indeterminate value. You then, go ahead and pass the array to printHistogram(), inside which, you receive it via list and then, dereference that and expect to get some valid value magically, which is not possible.
OTOH, you are scanning values in list inside the main() and not using it. You need to make some corrections so as to make use of the scanned value later, which seems to be the actual target.

array used uninitialized in this function

My task is to allocate memory for an array of integers (n elements), to give random values to each one of them and to print them sorted and unsorted. When I compile the code, I get this warning "'v' is used uninitialized in this function", and when I try to run it, I get "Segmentation fault".
I was wondering why am I supposed to initialize the array if I want to fill it up with random values? Is there a problem in the way I allocate memory for the array?(I'm not sure about the cast i did)
This is the source code:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main() {
int i, j, max, n, *v, aux;
scanf("%d%d", &n, &max);
*v=(int*)malloc(n*sizeof(int));
for(i=0; i<n; i++){
srand(time(NULL));
v[i]=rand()%max;
}
for(i=0; i<n; i++){
printf("%d ", v[i]);
}
printf("\n");
for(i=0; i<n-1; i++){
for(j=0; j<n-i-1; j++){
if(v[j]>v[j+1]){
aux=v[j];
v[j]=v[j+1];
v[j+1]=aux;
}
}
}
for(i=0; i<n; i++){
printf("%d ", v[i]);
}
printf("\n");
return 0;
}
I would be grateful if someone could make me understand what I do wrong, and eventually modify part of the source.
You made a typo (I presume) when creating the array.
*v=(int*)malloc(n*sizeof(int));
should be
v=(int*)malloc(n*sizeof(int));
The warning
'v' is used uninitialized in this function
is because of the deferencing *v in the line above.
Here's your problem:
*v=(int*)malloc(n*sizeof(int));
You assign the address of your allocated memory to the dereference of v - that is, you dereference your uninitialized pointer, and write to "wild memory".
In addition, using unitialized values is still a rotten way to get randomness. Look up rand() in your manual.

scanf infinite loop

This program takes the first number in a file and indicates how many numbers are going to be after it, then does various other things with the numbers that follow.
It seems like scanf is causing an infinite loop when trying to read from the file. WHen I run the program not even the check at 1 works
Here is the code:
#include <stdio.h>
int main(void) {
int N, a, n;
int x=0;
int t=0;
printf("1"); //Check
scanf("%d", &N);
printf("2"); //Check
int nums[N];
int i;
printf("%d", &N); //Check
for (i=0; i<N; i++)
{
scanf("%d", &nums[i]);
t+=nums[i];
if (nums[i] > x) x=nums[i];
if (i=0 || nums[i] < n) n = nums[i];
}
a = t/N;
printf("Number Processed: \t%d\n", &N);
printf("Maximum: \t%d\n", &x);
printf("Minimum: \t%d\n", &n);
printf("Total: \t%d\n", &t);
printf("Average: \t%d\n", &a);
}
The way i run the program is
gcc -lab16
./a.out <in1
where in1 is text and has the numbers
7
6
-30
90
3903
-934
443
445
Thanks for your time.
if (i=0 || nums[i] < n) n = nums[i];
you are assigning i = 0, so the loop never realy advances! You probably wanted i == 0. This is causing the infinite loop.
Other issue: int nums[N]; - if you want an array of dynamic [determined in run-time] size, you will probably need to malloc() it.
Update: note that int nums[N] is valid in C99, so if your assigment is assuming C99 you should not worry about this issue. Otherwise - malloc() will be needed:
int* nums = (int*) malloc(sizeof(int) * N)
And don't forget to free(nums) before the program ends, or you will get memory leak.
if (i=0 || nums[i] < n) n = nums[i];
This is the culprit. You are making an assignment i=0 when you should do a comparison : i==0
Your loop goes to infinity because everytime you are i to 0.
Moreover, the code you gave us, gave me an error, because you were creating new variables during runtime.
#include <stdio.h>
#include "stdlib.h"
int main(void) {
int N, a, n;
int x=0;
int t=0;
int i;
int *nums;
printf("1"); //Check
scanf("%d", &N);
printf("2"); //Check
nums = malloc(N*sizeof(int));
....
There are numerous problems with this code.
You mistook assignment for comparison:
i=0
sets i to zero. You probably meant
i==0
which checks whether i is equal to zero.
You should check the value returned by scanf(). When data read by scanf() doesn't fit the format you specified it leaves the data in the buffer and the next call to scanf() sees the same data again.
The reason that the first printf() doesn't print anything is most likely that you are not printing any newline. Note that on some output devices like terminals output is line-buffered.
You are passing a pointer to a variable to printf(), but your format specifies %d. You probably meant the variable itself, not a pointer to it.
Also, if you need an array of length dependent on a value known only at runtime, you need to allocate it on the heap, e.g. using malloc().

Resources