How to insert multiple elements in array in c program? - c

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.

Related

Similar function to the Java NextInt in 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.)

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

wrong print in coding c using pointer and array without no warning

int main()
{
int i, Quant, *Qsize1[4];
char *size1[4], size[5];
for(i=0; i<3; i++)
{
printf("Select Size : (S, M, L, XL) ");
scanf("%s",size);
size1[i]=size;
printf("How much quantity for this size? : ");
scanf("%d",Quant);
Qsize1[i]=Quant;
}
for(i=0; i<3; i++)
{
printf("\nSize %s : %d",size1[i], Qsize1[i]);
}
return 0;
}
example of print that i want is = Size L : 25
but when i print the it will print the last size i enter.
also the quantity of that size is wrong.
All the sizes are the same when you print them because you're reading all of them to the same character array named size. Each iteration overrides the previous size, and then you end up with size1[0], size1[1], size1[2] all point to the last size.
Quantity is wrong because you should pass scanf the address of the integer: scanf("%d", &Quant);
Also, as mentioned in the comments, you should fix how you read size itself. See this question about how to do it properly.

Can anybody resolve my mistake

I cant seem to find out where i'm going wrong in C. its on line 37 it says assignment to expression with array type any help or advice would be great thanks.
I was wondering also is it something to do with not adding in the brackets to show that they're arrays on line 37 but when i put them in it displays more errors
/*
This program uses pass by reference to calculate the values after two arrays are multiplied by each other
16/02/2015
Jake Young
*/
#include <stdio.h>
#define size 5
//Prototype
int multiply_function(int *[], int *[]);
main()
{
int array1[size];
int array2[size];
int i;
int answer[size];
//get users input for array1
printf("Please enter %d values into array1:\n", size);
for(i=0; i<size; i++)
{
scanf("%d", &array1[i]);
}//end for loop
//get users input for array2
printf("Please enter %d values into array2:\n", size);
for(i=0; i<size; i++)
{
scanf("%d", &array2[i]);
}//end for loop
//call function()
answer=multiply_function(&array1, &array2); // line 37
//Print out the results from array1 multiplied by array2
printf("Array1 multiplied by Array2 is the following:\n");
for(i=0; i<size; i++)
{
printf("%d multiplied by %d is %d\n", array1[i], array2[i], answer[i]);
}//end for loop
}//end main()
multiply_function(int *array1[], int *array2[])
{
int *answer[size];
int i;
for(i=0; i<size; i++)
{
//calculate multiplication
*answer[i]= *array1[i]* *array2[i];
}//end for loop
return(*answer);
}//end function()
int multiply_function(int *[], int *[]);
This doesn't make any sense. You intend to pass arrays of integers to the function, not arrays of pointers. You'll have to study how arrays should be passed to functions.
main()
This form is not standard. Unless you are programming a "bare metal" embedded system, you should use int main (void).
answer=multiply_function(&array1, &array2);
This doesn't make any sense. You declared the function to return an int. Again, study how arrays are passed to and from a function. Furthermore, you can't copy arrays with the assignment operator: you have to use memcpy() or similar functions.
multiply_function(int *array1[], int *array2[])
The function definition is different than the prototype: that is always bad practice. Apart from that, the function doesn't make any sense, as already mentioned.
int *answer[size];
This doesn't make any sense, you are declaring an array of pointers where you want an array of integers.
return(*answer);
Returning a pointer to a local variable in C is always a bug. And you can't return arrays like this. And there is no need for the parenthesis.
OK, you should really invest some more time to study arrays, pointers and fundamentals of functions in C.
Apart from grammatical problems in the code, the fundamental problem in this code is the answer[] array. it is defined both in main() and the multiply_function(). What you must do is to pass this array to the multiply_function() and have the function fill in the array.
I'm giving the solution below, with the hope that you'll compare it to your version and study the differences and continue to learn the basics of C:
#include <stdio.h>
#define size 5
//Prototype
int multiply_function(int *, int *, int *);
main()
{
int array1[size];
int array2[size];
int i;
int answer[size];
//get users input for array1
printf("Please enter %d values into array1:\n", size);
for(i=0; i<size; i++)
{
scanf("%d", &array1[i]);
}//end for loop
//get users input for array2
printf("Please enter %d values into array2:\n", size);
for(i=0; i<size; i++)
{
scanf("%d", &array2[i]);
}//end for loop
//call function()
multiply_function(array1, array2, answer);
//Print out the results from array1 multiplied by array2
printf("Array1 multiplied by Array2 is the following:\n");
for(i=0; i<size; i++)
{
printf("%d multiplied by %d is %d\n", array1[i], array2[i], answer[i]);
}//end for loop
}//end main()
multiply_function(int *array1, int *array2, int *answer)
{
int i;
for(i=0; i<size; i++)
{
//calculate multiplication
answer[i]= array1[i] * array2[i];
}//end for loop
return(*answer);
}//end function()

Unwanted Output in C Program

I have a class project to make an array, declare it's size (add 1) then fill it in numerical, nondecreasing order. After that, I need to declare x, a value to be added to the array in the appropriate spot, so the array is still nondecreasing.
The program builds without error (for once!) but I'm getting some really weird outputs.
#include <stdio.h>
int main (void) {
//Local Declarations
int size;
int ary[100];
int x;
int i;
int j;
//Statements
printf("Enter the size of the array: ");
scanf("%d", &size);
printf("\nEnter digits to fill the array, in numerical order: ");
for (i = 0; i < size; i++) scanf("%d", &ary[i]);
size++;
printf("\nInput x, the value to add to the array: ");
scanf("%d", &x);
while(i <= x && x > ary[i]){
i++;
j = size - 1;
while(j >= i) {
ary[j++] = ary[j];
j--;
}
}
for(i = 1; i < size; i++) {
printf("%d", &ary[i]);
}
return 0;
} //main
When it runs I get:
Enter the size of the array: 3
Enter digits to fill the array, in numerical order: 1
2
3
Input x, the value to add to the array: 4
268634426863482686352
Process returned 0 (0x0) execution time : 7.124 s
Press any key to continue.
I would examine your print function . It looks like you're printing the memory address of that particular array index rather than the value at that spot in the array.
Don't increase the size variable before you iterate through. Then walk backwards through the array, and populate as needed.
for (i = size; i >0; --i)
{
if (ary[i-1] > x)
{
ary[i] = ary[i-1];
}
else
{
ary[i] = x;
break;
}
}
if (i == 0)
ary[i] = x;
Afterwards, you can increase size as you print the output.
I've reproduced your desired output using this array walk.
There are other ways that I would solve this problem in real life, but this works well enough within your existing code.
First things first: what do you EXPECT to see as the output?
Second things first: you aren't clearing out the memory for the array before use. You have garbage values in any slots you aren't using.
Third things first: using GCC I'm seeing at least two warnings without even trying.
test.c:32:15: warning: format specifies type 'int' but the argument has type 'int *' [-Wformat]
printf("%d", &ary[i]);
test.c:27:14: warning: unsequenced modification and access to 'j' [-Wunsequenced]
ary[j++] = ary[j];
In your printing loop your are not printing the value but your are printing the address of that element. Change the last loop to
for(i = 1; i < size; i++) {
printf("%d", ary[i]);
}
I am not sure why your are printing the array from index 1. But if you want to print whole array you should initialize i to zero in above loop.

Resources