Reading a series of integers to an array? - c

I'm new to arrays , i want to know if it is possible to fill the array using a for-loop with the scanf function , i made a first attempt but the program isn't working ( it is supposed to fill the array then print all the elements of it )
#include<stdio.h>
void main(){
int n,i;
int table[10];
for(i=1;i<=10;i++){
scanf("%d",table[i]);
}
for(i=1;i<=n;i++){
printf("\n%d",table[i]);
}
getchar();
getchar();
return ;
}

When you declare an array of size N, the elements are indexed from 0 to N - 1. From there, you need to pass the address of your variable to scanf, not the variable itself. Since you are using an array, this becomes very simple.
for (int i = 0; i < 10; ++i)
scanf("%d", table + i);

You should use
scanf("%d", &table[i]);
Additionally the loop should start with 0, because indexes in C start from 0..N-1.
for(i = 0; i < 10; i++)
scanf("%d", &table[i]);

In C, array indexing starts from 0.
Change for loop to
for(i = 0; i < 10; i++) {...}
and
scanf("%d",table[i]);
to
scanf("%d", &table[i]);
^& operator before the variable table[i]

Related

C Programming How to get results of an mathematical operation stored in a different array?

I am trying to subtract a given number from an array and then store the results in a completely different array. Is it possible to write the code without using pointers?
I am trying to write the code with using for loop and or do/while loop.
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(){
int num[100];
int i ;
int size;
int sub;
int diff[100];
printf("Enter the size of the array: ");
scanf("%d", &size);
for(i=0;i<size; i++){
printf("Enter the element %d :", i+1);
scanf("%d", &num[i]);
}
printf(" Enter the number to substract: \n");
scanf("%d", &sub);
for (i=0;i<size; i++)
{
y = num[i]- sub;
scanf("%d", &diff[y]);
}
for (y=0; y<size; y++)
{
printf("%d", diff[y]);
}
}
After I scan the results, I tried different ways to initialize and store the values in the second array but haven't been successful. What mistake am I making here?
y = num[i] - sub;
This is fine, as it's the result of subtraction for a given source array element.
scanf("%d", &diff[y]);
This doesn't make sense, as it's attempting to read input from the user. Not only that, it's using the result of the subtraction as the index of the destination array.
Just assign the result of the subtraction to the corresponding destination array member:
diff[i] = num[i] - sub;
In your question, you try to scan the value to another array, but the correct form is to assign the value in the new array position.
For example, in your first for loop use the i variable as the position and assign num[i] - sub on diff[i]:
for (i = 0; i < size; i++)
{
diff[i] = num[i] - sub;
}
instead of:
for (i=0;i<size; i++)
{
y = num[i]- sub;
scanf("%d", &diff[y]);
}

Find the mistake in the code — we have to print the sum of elements of the array of any size

The elements of the array have to be taken as input from the user. Here I am using an array of size 10. I am getting the sum as 0 if I initialized it with sum = 0; while declaring, and if I didn't, I am getting a garbage value.
Here is the code:
#include <stdio.h>
int main(void)
{
int barray[10], i=0, sum=0;
for(i=0;i<10;i++ ){
printf("Enter the value for barray[%d] element of the array : ",i);
scanf("%d", &barray[i]);
}
while(i >=0 && i<10)
{
sum += barray[i];
i++;
}
printf("The sum of the elements of the array is %d", sum);
}
The problem with your code is that i is not a variable declared in the scope of the for loop but in the scope of main, so when the for loop is done i=10 and then the contents of the while loop are skipped as the condition for i to be greater than 0 and less than 10 are never met.
To fix this you should set i to zero after the for loop
scanf("%d", &barray[i]);
}
i = 0; // add this
while(i >=0 && i<10)
{
or change the while loop to a for loop like the first one. Though I would recommend as good practice and for cleaner code to declare the iterator variable inside the context of the for loop unless you need to access it outside of it, like so.
int main(void)
{
int barray[10], sum=0;
for (int i = 0; i < 10; i++) {
printf("Enter the value for barray[%d] element of the array : ", i);
scanf("%d", &barray[i]);
}
for (int i = 0; i < 10; i++) {
sum += barray[i];
}
printf("The sum of the elements of the array is %d", sum);
}

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

struct and values entered in C

I have a program that does not work. The problem for example is:
You input 2 for students, then enter mark 5 for the first student and then 10 for second student.
The output sum in the fun() function should return 15 . But instead, it returns 20.
This is my code so far:
struct mark{
int x;
};
int main(){
int n;
printf("Enter the number of student: ");
scanf("%d",&n);
struct mark *marks= malloc(n * sizeof(struct mark)); ;
for (int i = 0; i < n; i++ ){
printf("Enter mark: ");
scanf("%d",&(*marks).x);
}
fun(marks,n);
free(marks);
return 0;
}
void fun(struct mark *marks, int n){
int sum =0,i;
for (i = 0; i < n; i++ ){
sum= sum+(*marks).x;
}
printf("Sum: %d \n",sum);
}
scanf("%d",&(*marks).x);
Means you are reading into the first mark in marks.
You already have a for loop and a counter variable for reading into it, so use it. change
sum= sum+(*marks).x;
to
sum= sum+marks[i].x;
which is also equivalent to
sum = sum+(*marks+i).x;
Do the same for
scanf("%d",&(*marks).x);
change it to
scanf("%d",&marks[i].x);
again,
marks[i].x is equivalent to (*marks+i).x
The point is that you want to access the second mark in marks in your second iteration of your for loop. Also, don't forget to free() your marks when your program is done.
change :
scanf("%d",&marks[i].x);
and:
sum= sum+marks[i].x;
Inside main in this piece of code:
for (int i = 0; i < n; i++ ){
printf("Enter mark: ");
scanf("%d",&(*marks).x);
}
You are always assigning mark to 1st array element.
Inside fun in this piece of code:
for (i = 0; i < n; i++ ){
sum= sum+(*marks).x;
}
you are not iterating over the marks array, but instead always reading 1st array value.

My program crashes, I don't understand why it does not even reach the first printf

My program is supposed to order a list of numbers inputed by the user, but it crashes even before reaching the first printf. My compiler makes 2 warnings, but I don't see the issue. I haven't studied pointers yet, so I didn't want to use them. Here are the messages:
In function `selection_sort':
[Warning] passing arg 2 of `selection_sort' makes pointer from integer without a cast
In function `main':
[Warning] passing arg 2 of `selection_sort' makes pointer from integer without a cast
.
#include<stdio.h>
int selection_sort(int n, int v[n])
{
int high = v[0];
int i;
for(i = 0; i < n; i++)
high = high < v[i]? v[i] : high;
if(n - 1 == 0)
return;
v[n - 1] = high;
n -= 1;
selection_sort(n, v[n]);
}
int main(void)
{
int n, i;
int v[n];
printf("Enter how many numbers are to be sorted: ");
scanf("%d", &n);
printf("Enter numbers to be sorted: ");
for(i = 0; i < n; i++)
scanf("%d", &v[i]);
selection_sort(n, v[n]);
printf("In crescent order: ");
for(i = 0; i < n; i++)
printf("%d ", v[i]);
getch();
return 0;
}
Your program is using a variable length array, a feature that was added in C99.
However, you declare its size based on an uninitialized variable. What did you believe would happen there?
In C, variables declared inside functions are NOT set to 0. They are not set to anything. They pick up whatever value was left on the stack or in the register that they are assigned.
I believe that your program is crashing because n in int v[n] is a ridiculously big number and v is trying to use too much memory.
You can probably fix this by moving your array declaration below the scanf that reads in n.
You need to pass v, not v[n] to the function selection_sort. v is the array, v[n] is actually an out of bounds element of v.
the line should be selection_sort(n, v);

Resources