Sorting inputted integers into odd and even arrays - c

I'm a beginner to C, and am trying to sort user inputted numbers into odd and even arrays. I don't understand why my code isn't working.
Cheers.
This is my code, I don't understand my mistake.
int x[]= {};
int i=0;
int d=0;
int j=0;
int even[12]={};
int odd[12]={};
printf("Enter amount of numbers: "); // asking user for amount of numbers
scanf("%d", &d);
for (j=0; j<d; j++){
printf("Enter number %d: ", i+1); // scanning input into 'x' array
scanf("%d", x[i]);
}
printf("Even numbers: ");
for (i=0; i<d; i++) {
if (x[i] % 2 == 0) { // sorting into even array
even[i]=x[i];
printf("%d \n", even[i]);
}
}
printf("\n Odd numbers: ");
for (i=0; i<d;i++){
if (x[i] % 2 != 0) { // sorting into odd array
odd[i]=x[i];
printf("%d \n", odd[i]);
}
}
This error message keeps coming up:
$ ./main
Enter amount of numbers: 4
Enter number 1: 6
Segmentation fault (core dumped)

int x[]= {}; doesn't work because it would hold no elements. But initializing it with {} doesn't work in C anyway, do this instead:
int x[24] = {0}; // first element explicitely set to 0, the rest default-initialized to 0
You also need to put {0} for even and odd. If it's compiling for you with {} then it's possible that you're compiling it as a C++ program, or perhaps your compiler just tolerates it anyway (but it won't work on every C compiler).
scanf needs the address of the int, so instead of scanf("%d", x[i]); you need scanf("%d", &x[i]);. But i is the wrong iterator for this for (j = 0; j < d; j++) loop. Instead do this:
for (j = 0; j < d; j++) {
printf("Enter number %d: ", j + 1); // scanning input into 'x' array
scanf("%d", &x[j]);
}
Also note that the way you're doing this, half the array will be left at 0. So for instance if I imputted the values 1 through 6, then odd contains the values 1 0 3 0 5 0.

Related

Understanding the arrays in C

I'm new to C and need some help to understand how this piece of code works. I know that it reads the values that the user writes, puts them into an array, and then prints them out.
But I don't understand why I need two "counters" (i and j) to do this. Can someone help me to figure it out?
#include<stdio.h>
int main ()
{
int A[5];
int i=0;
int j=0;
while (i < 5)
i++;
printf("Enter your %d number\n", i);
scanf("%d", &A[i]);
}
while (j < 5)
{
j++;
printf ("\n%d\n", A[j]);
}
}
Technically, what you have aren't two counters, but two loops. If you wanted, to, you could just reuse i for the second loop as well, by doing something like this:
while (i < 5)
i++;
printf("Enter your %d number\n", i);
scanf("%d", &A[i]);
}
i = 0;
while (i < 5)
{
i++;
printf ("\n%d\n", A[i]);
}
As for why you have two loops, the reason is simple. The first loop (using i in your code), reads the 5 integers into the array A. After the first loop concludes, your array A holds the 5 int values, which you could've used however you wanted. In your case, you want to print those values. So what you do is use a loop for looping over the array elements and printing the values to the screen, one by one.
You don't need it, you can simply reset the first and reuse it. However you must increment your index only after having using it otherwise you will overflow the limit of the array :
#include<stdio.h>
int main ()
{
int A[5];
int i=0;
while (i < 5) {
printf("Enter your %d number\n", i);
scanf("%d", &A[i]); // the last must be 4 not 5
i++; //<== increment here
}
i=0;
while (i < 5)
{
printf ("\n%d\n", A[i]); //idem
i++;
}
}

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

Printing out dynamically allocated memory in C

I'm a total beginner in programming and got an assignment about dynamically allocated memory. One of the expected outputs was a printf statement where all the entered inputs(integers) are printed in a single line, in a row. I have managed to printf in a for-loop, but thats not enought. How do I printf them in a single code-line? Here's the code:
int main()
{
int how_many_integers, count, entered_integers, i, *pSize;
printf("\nHow many integers are you going to type?\n");
scanf("%i", &how_many_integers);
getchar();
// Allocates memory for the integers.
pSize = malloc (how_many_integers * sizeof(int));
// Checks if the integer is 0, and/or reads in all the integers.
if (how_many_integers == 0)
{
printf("No numbers were given.\n");
exit(0);
}
printf("Please enter your integers.\n");
for (int i = 0; i < how_many_integers; i++)
{
scanf("%i", &entered_integers);
count++;
pSize[i] = entered_integers;
}
for (int i = 0; i < how_many_integers; i++)
{
printf("Number: %i\n", *(pSize+i));
}
free(pSize);
printf("Count: %i", count);
return 0;
}
Try this:
printf("Numbers:");
for (int i = 0; i < how_many_integers; i++)
{
printf(" %i", *(pSize+i)); // No \n
}
printf("\n"); // if you want a new line at the end
This should result in an output like
Numbers: 1 2 3 4 5
And as others mentioned, your count variable is never initialized. Initialize it to 0.

How to add 'nothing' into int array in C

I have a task to sort an integer array into an even number array and odd number array. Then i have to show what digits has been placed in which. However, in my code not all places of the array are occupied, so in the end i receive random numbers when I want to show what the arrays odds and evens contain. Instead of random numbers I would like to have literally nothing added in their place.
I did the following:
int main()
{
int evens[10], whole[10], odds[10], i;
printf("Enter 10 integer(/whole) numbers\n");
for (i = 0; i < 10; i++)
{
scanf("%d", &whole[i]);
if (whole[i] % 2 == 0)
{
evens[i] = whole[i];
else odds[i] = whole[i];
}
}
printf("Your even numbers are the following:\n");
for (i = 0; i < 10; i++)
{
printf("%d\n", evens[i]);
}
printf("Your odd numbers are the following:\n");
for (i = 0; i < 10; i++)
{
printf("%d\n", odds[i]);
}
return 0;
}
and then I get this output for having entered digits from 1 to 10:
Your even numbers are the following:
-1832565259
2
1985901418
4
4200864
6
4200958
8
74
10
Your odd numbers are the following:
1
4200864
3
6356652
5
1986281400
7
1985964450
9
1985901427
So how do i get an odds/even array without these random digits like 1985964450 in between? Is there a command to add literally nothing instead?
You should have a counter of odds and a counter of evens.
int oddcount = 0;
int evencount = 0;
When you decide that a number is even, you use this counter to know where in the array it should go. For example:
if (whole[i] % 2 == 0) {
evens[evencount] = whole[i];
evencount++;
}
Notice that evencount not only gives you the number of even numbers, but since arrays indices begin at zero, it also tells you what is the position of the next even number.
Then you modify your for loops at the end to use the actual number of even and odd numbers that were typed. You can even check for zero and print a specific message such as No even numbers supplied.
Also, unless you have been specifically asked to keep the input numbers in an array, you don't need whole. You can do just like so:
int input;
for (i=0; i<10; i++)
{
scanf("%d", &input);
if (input %2 == 0)
/* ... */
else
/* ... */
}
As a final remark, you should indent your code. Indentation is simply augmenting the number of spaces before the code (like I did inside the ifs above). It is very important to indent your code because it makes the structure of your code clear. For a more comprehensive discussion on this, read here: Importance of code indentation.
It is better to have two variables that represents indexes, one you use to add odd numbers, other to add even numbers. Then you will have two arrays without redundant data :)
int evensIndex = 0;
int oddsIndex = 0;
for (i=0; i<10; i++)
{
scanf("%d", &whole[i]);
if (whole[i] %2 == 0)
{
evens[evensIndex] = whole[i];
evensIndex++;
}
else
{
odds[oddsIndex] = whole[i];
oddsIndex++;
}
}
int main()
{
int evens[10], temp, odds[10], i;
int oddIndex = 0, evenIndex = 0;
printf("Enter 10 integer(/whole) numbers\n");
for (i=0; i<10; i++)
{
scanf("%d", &temp);
if(temp%2)
odd[oddIndex++]=temp;
else
even[evenIdex++]=temp;
}
printf("Your even numbers are the following:\n");
for (i=0; i<10; i++)
printf("%d\n", evens[i]);
printf("Your odd numbers are the following:\n");
for (i=0; i<10; i++)
printf("%d\n", odds[i]);
return 0;
}

Segmentation fault in my program

My sorting program results in a "segmentation fault 11":
#include <stdio.h>
int main()
{
// Asking user for number of inputs in an array
int n;
do {
printf ("enter the number of intigers you want to sort\n");
scanf("%d",&n);
}while (n<=1);
int sort [n];
printf ("please enter %d numbers\n",n);
for (int i=0; i<n; i++) {
scanf("%d",&sort[i]);
}
printf("you entered\n ");
for (int i=0; i<n; i++) {
printf(" %d ",sort[i]);
}
printf("\n");
int k,c,i,x;
for (i=0;i<n;i++) {
if (sort[i]<sort[i-1]){
k=i-2;
while (sort[k]>sort[i]){
k--;
}
k++;
x =sort[i];
c=i;
for (c=i;c>k;c++){
sort[c-1]=sort[c];
}
sort[k]=x;
}
}
printf ("Sorted numbers :-\n");
for (int i=0; i<n; i++) {
printf ("%d ",sort[i]);
}
printf ("\n");
return 0;
}
Now I have looked up the internet and found that it is caused because a variable has value that exceeds the system's memory limit. But cannot understand that concept.
for (i=0;i<n;i++)
{
if (sort[i]<sort[i-1])
You are accessing array out of its bounds.Maybe you want to start your loop from 1.Also
k=i-2;
while (sort[k]>sort[i])
will access index beyond 0 for example if i is 0 or 1 or 2
k = i - 2; looks unstable for low values of i.
sort[i - 1] is undefined when i is zero.
The thing causes the behaviour of sort[k] to be undefined.
Moral of the story: check all the array indexes before attempting to retrieve an array element. Your debugger will help you here.
In addition to all said before:
c=i;
for (c=i;c>k;c++){
sort[c-1]=sort[c];
}
sort[k]=x;
i can be 0 -> c can be 0 -> sort[c-1] would also result in accessing array out of bounds.
There is no need to initialize c=i twice. It is enough to do it in the loop-declaration

Resources