Array elements not allocating by positive or negative values in C - c

Basically I'm just trying to sort all user input numbers by positive or negative. So far I'm just trying to create an array of only positive integers, but can't seem to get it right.
Been stuck on this for a while and can't quite understand why my program is allocating negative integers to my array that's supposed to be for positive integers only, despite my if statements instructing otherwise. Any input would be greatly appreciated!
#include <stdio.h>
#include <stdlib.h>
int main() {
int num_of_elements = 0, i, j, x;
int elements[num_of_elements];
int positive_total = 0, negative_total = 0;
int negative_elements[20];
int positive_elements[20];
printf("How many elements in N? \n:");
scanf("%d", &num_of_elements);
for (i=0; i<num_of_elements; i++) {
printf("\nEnter element a%d. \n:", i+1);
scanf("%d", &elements[i]);
}
for (j=0; j<num_of_elements; j++)
{
if (elements[j] > 0)
{
positive_elements[positive_total] = elements[j];
positive_total++;
} else if (elements[j] < 0) {
negative_elements[negative_total] = elements[j];
negative_total++;
}
}
int num;
for (num=0; num<=positive_total;num++) {
printf("\npositive element %d is %d", num, positive_elements[num]);
}
int MAX_pos_element = 0;
for (x=0; x<=positive_total; x++) {
if (MAX_pos_element < positive_elements[x]) {
MAX_pos_element = positive_elements[x];
printf("\n%d is larger than %d", MAX_pos_element, positive_elements[x]);
printf("\nelement[%d] has the largest value: %d", x, MAX_pos_element);
}
}
return 0;
}

With:
int num_of_elements = 0, i, j, x;
int elements[num_of_elements];
you are allocating an array of zero length because num_of_elements is still zero.
Use the following:
printf("How many elements in N? \n:");
scanf("%d", &num_of_elements);
int elements[num_of_elements];
Now num_of_elements is initialized.
(Note: you should also check the return value of scanf to be sure a number was read.)

The program is initially invalid and has undefined behavior.
You may not declare a variable length array with zero number of elements as you are doing
int num_of_elements = 0, i, j, x;
int elements[num_of_elements];
You should declare the array after you entered a positive value of the variable num_of_elements.
For example
printf("How many elements in N? \n:");
scanf("%d", &num_of_elements);
int elements[num_of_elements];
Also in loops like this
for (num=0; num<=positive_total;num++) {
printf("\npositive element %d is %d", num, positive_elements[num]);
}
you have to use the condition num < positive_total instead of num <= positive_total.

Related

c program for finding the highest divisible number is not working

So I am new to C programming. The purpose of this program is to use a function to find the largest number divisible. Three numbers should be given and the answer should be the number that is higher than the first number and lower than the second number and should be the largest number between them that can be divided evenly by the third number.
#include <stdio.h>
#include <stdlib.h>
int my_function(int first, int second, int third) {
int i, answer;
for (i = second; i <= 0; i--) {
if (i < first || i > third) {
answer = 0;
break;
}
if (i % third == 0 && i != 0 && i > first)
answer = i;
}
return answer;
}
int main() {
printf("enter number one:\n");
int one, two, three, final;
scanf("%d", &one);
printf("enter number two\n");
scanf("%d", &two);
printf("enter number three\n");
scanf("%d", &three);
final = my_function(one, two, three);
printf("the number is %d", final );
return 0;
}
This program is not working. Can someone help me with my mistake?
Your function does not work for multiple reasons:
the loop test is always false if second is a positive number.
the test i > third will cause an early exit from the loop for no good reason.
when your find a divisible number, you should then exit the loop.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
int my_function(int first, int second, int third) {
int i;
for (i = second - 1; i > first; i--) {
if (i % third == 0)
return i;
}
return 0;
}
int main() {
int one = 0, two = 0, three = 0, final;
printf("enter number one:\n");
scanf("%d", &one);
printf("enter number two\n");
scanf("%d", &two);
printf("enter number three\n");
scanf("%d", &three);
final = my_function(one, two, three);
printf("the number is %d\n", final);
return 0;
}

Why does my loop terminate even with a condition?

I am trying to get user input and store them in an array Fib[i]. After that print the Fib[i] array. When the user enters -1 the loop will quit and the program will end. But my code is not printing or terminating.
#include <stdio.h>
double Fib[50];//globally declared
int fib(int n)
{
int i;
for(i=0; i<50; i++)
{
scanf("%d", &Fib[i]);
if(i==-1)
break;
//printf("numbers entered %d\n", Fib[i]); // <- doesn't terminate if printf is here
}
printf("numbers entered %d\n", Fib[i]); //doesn't print anything??
}
int main()
{
int i, n;
//calling the function
fib(n);
return 0;
}
user input:
4
5
-1
Expected output:
Numbers entered
4
5
First issue: you declare Fib as an array of double:
double Fib[50];
But you use %d to read the values, which is for reading an int:
scanf("%d", &Fib[i]);
Using the wrong format specifier invokes undefined behavior. You presumably want to store integers, so change the array to int:
int Fib[50];
Next is your array breakout condition:
if(i==-1)
i is your array index, which ranges from 0 to 49, so this will never be true. You want to stop when the user enters -1, and that value will be in Fib[i]:
if(Fib[i]==-1)
Finally, printing the array:
printf("numbers entered %d\n", Fib[i]);
This doesn't print the array. It just prints the element at the last index of i, and the value at that index will always be -1. You need a separate loop to print the values:
int j;
printf("numbers entered:\n");
for (j=0; j<i; j++) {
printf("%d\n", Fib[j]);
}
This code has many code writing standard issues but it seems you are new so I am making minimal changes just for your understanding
#include <stdio.h>
double Fib[50];//globally declared
int fib(int n)
{
int i,j;
for(i=0; i<50; i++)
{
scanf("%lf", &Fib[i]);
if(Fib[i]==-1)
break;
}
printf("numbers entered \n");
for(int j=0;j<i;j++)
{
printf("%lf\n",Fib[j]);
}
}
int main()
{
int i, n;
fib(n);
return 0;
}

Recursive function with array in C

The problem goes as follows:
Write a recursive function with three arguments: an array (a), the
number of elements of the array (n) and a number - k.
If k is positive and smaller than n it should print the first k positive
numbers of the array.
If k is negative and its absolute value is smaller than n the first k negative numbers should be printed.
If k is larger than n and positive all positive numbers should be printed.
If k is larger than n and negative all negative numbers should be
printed.
This is my attempt
#include <stdio.h>
#include <stdlib.h>
int function(int a[100], int n, int k)
{
int b[n], i;
if (k!=0 && n>1)
{
for (i=0; i<n; i++)
{
b[i]=a[i+1];
}
if (k<n || abs(k)<n)
{
if (k>0)
{
if (b[0]>0)
{
printf("%d", b[0]);
k=k-1;
}
}
if (k<0)
{
if (b[0]<0)
{
printf("%d", b[0]);
k=k+1;
}
}
return function(b, n-1, k);
}
}
else return 0;
}
int main()
{
int i, n, a[100], k;
printf("n = ");
scanf("%d", &n);
for (i=0; i<n; i++)
{
printf("a[%d] = ", i);
scanf("%d", &a[i]);
}
printf("k = ");
scanf("%d", &k);
printf("The new array is: \n");
function(a, n, k);
return 0;
}
But it only prints one number and I don't know how to fix it. Does anyone understand where I went wrong?
EDIT: If the array is {1, -1, 2, -2, 3, -3} and k=2, the expected result is {1, 2}. If k=-2 the expected result is {-1, -2}
EDIT 2: b is an array that contains all the elements of the a array other than a[0]
I found three issues with your code.
1) When I copied your code (converting to C# because that's what I work with), it threw an ArgumentOutOfRangeException for me here:
for (i=0; i<n; i++)
{
b[i]=a[i+1]; <------
}
When i is 99, it tries to copy a[100] into b[99], but there's no a[100]. You should change the for loop to this instead:
for (i=0; i<n-1; i++)
2) Your code is essentially treating a like a queue and popping the first number off (by copying all the others into a new array b), but instead of looking at that first number to determine whether or not to print it, you're skipping it and looking instead at the first item you just put into b:
if (k>0)
{
if (b[0]>0) <------
{
printf("%d", b[0]); <-----
k=k-1;
}
}
You should change your comparisons (and printf lines) to look at a[0] instead of b[0].
3) Whenever k is larger than n, then your entire logic block will get skipped (for example, I mistakenly set k to 34 instead of 3, and when I did, the if block reads if (34 < 6 || abs(34) < 6), which is always false.

Retaining input values in C?

I have asked for the user to enter in several values to calculate an average, however I'd like to also calculate a gradient which uses the inputted values. How do I name these values so I can use them again? Thank you.
Here is what I have thus far:
#include <stdio.h>
int main () {
int n, i;
float num[1000], total=0, mean;
printf("Enter the amount of x-values:");
scanf("%d", &n);
while (n <= 0 || n > 1000) {
printf("Print error. The number should in range of 0 to 1000.\n");
printf("Please try to enter the amount again: ");
scanf("%d", &n);
}
for (i = 0; i < n; ++i) {
printf("%d. Input x-value:", i+1);
scanf("%f", &num[i]);
total += num[i];
}
mean=total/n;
printf("The mean of all the x-values entered is %.2f to 2 decimal places", mean);
{
float num[1000], total=0, mean;
printf("Enter the amount of y-values:");
scanf("%d", &n);
while (n <= 0 || n > 1000) {
printf("Print error. The number should in range of 0 to 1000.\n");
printf("Please try to enter the amount again: ");
scanf("%d",&n);
}
for (i = 0; i < n; ++i) {
printf("%d. Input y-value:", i+1);
scanf("%f", &num[i]);
total += num[i];
}
mean = total / n;
printf("The mean of all the y-values entered is %.2f to 2 decimal places", mean);
return 0;
}
}
Naming the variable is really up to you, but `int gradient[NUM_ELEMENTS]; seems appropriate. It is an array, which also seems appropriate if it's purpose is to assist in finding the gradient from a series of numbers.
Steps could be:
1) use printf to ask user for values, specify spaces or commas between values. You can also specify a limit of values. Example printf("enter 5 numbers separated by commas\n:");
2) use scanf or similar to read values from standard input (the terminal) into the array: scanf("%d,%d,%d,%d,%d", &gradient[0], &gradient[1], &gradient[2], &gradient[3], &gradient[4]);
3) use the array an a function that will compute the gradient.
Simple example:
(where gradient computation, error checking, bounds checking etc. is all left to you)
int get_gradient(int a[5]);
int main(void) {
int gradient[5];
int iGradient=0;
printf("enter 5 numbers separated by commas");
scanf("%d,%d,%d,%d,%d", &gradient[0], &gradient[1], &gradient[2], &gradient[3], &gradient[4]);
iGradient = get_gradient(gradient);
return 0;
}
int get_gradient(int a[5])
{
return [do computation here using array a];
}
Edit:
The above example works only if you know the number of elements at compile time. It uses an int array that has been created on the stack. If you do not know how big of an array you will need until run-time, for example if user input determines the size, then the array size needs to be determined at run-time. One options is to create the variable needed on the heap. (read about stack and heap here) The following uses some techniques different from the simpler version above to get user input, including a function I called get_int(), which uses scanf() in conjunction with strtol(). Here's the example:
int main(void) {
char input[80]={0};
char **dummy={0};
long *gradient = {0};
int iGradient=0;
int arraysize;
int i;
char* fmt = "%[^\n]%*c";
printf("how many numbers will be entered?");
scanf(fmt, input);
arraysize = strtol(input, dummy, 10);
gradient = calloc(arraysize, sizeof(long));
if(gradient)
{
for(i=0;i<arraysize;i++)
{
gradient[i] = get_int();
}
iGradient = get_gradient(gradient, arraysize);
//free gradient when done getting result
free(gradient);
}
return 0;
}
int get_gradient(int *a, int num)
{
int grad = 0, i;
//do something here to compute gradient
return grad;
}
long get_int(void)
{
char input[80]={0};
char **dummy={0};
char* fmt = "%[^\n]%*c";
printf("Enter integer number and hit return:\n");
scanf(fmt, input);
return strtol(input, dummy, 10);
}

I can't store integers inside an array

This is an activity given by my instructor.
Create a program that accepts numeric input from the user. If the user enters an even number, store it to an array for even numbers. If the user enters an odd number, store it to another array for odd numbers. Input terminates if the user entered 10 numbers already. Display the size of each array and their elements.
Example:
Input: 5, 6, 12, 10, 0, 3, 4, 100, -1, 7
Even numbers (6): 6 12 10 0 4 100
Odd numbers (4): 5 3 -1 7
and this is the code I've come up with.
#include <stdio.h>
int sort(int);
int main(){
int input, count;
for(count=0;count!=10;count++){
printf("Enter 10 digits: ");
scanf("%d", &input);
sort(input);
}
printf("%d", input);
return 0;
}
int sort(int inp){
int odd[10];
int even[10];
if(inp%2==0){
odd[]=inp;
}
else
even[]=inp;
return 0;
}
Please help me on how to store the numbers into two separate arrays. Any tips will be greatly appreciated.
Check the below code. It's self-explaining.
#include <stdio.h>
#include <stdlib.h>
#define NUM 10
int main()
{
int input, i;
int oddcounter = 0, evencounter =0;
int oddarr[NUM];
int evenarr[NUM];
printf("Enter 10 integers\n");
for (i = 0; i < NUM; i++)
{
if ( scanf("%d", &input) == 1 )
{
if ((input % 2) == 0)
{
evenarr[evencounter++] = input;
}
else
{
oddarr[oddcounter++] = input;
}
}
}
printf("Number of elem in oddarray : %d, evenarray : %d\n\n", oddcounter, evencounter);
printf("Odd elements are :");
for (i = 0; i < oddcounter ; i++) printf("%d\t", oddarr[i]);
printf("\n");
printf("Even elements are :");
for (i = 0; i < evencounter; i++) printf("%d\t", evenarr[i]);
printf("\n");
return 0;
}
In addition to Sourav's comment which indicates that you shouldn't have the int[] arrays be local to sort, this syntax isn't correct for assigning to arrays in C:
odd[]=inp;
On my compiler, it generates the following error:
24:9: error: expected expression
odd[]=inp;
To store to odd, you need to indicate the index at which you'd like to store, for example:
odd[1]=inp;
which also means you'll need to keep track the latest index you wrote to for each array!
You need to tell the compiler which index of the array you are storing your data to. In sort:
if(inp%2==0){
odd[]=inp;
}
else
even[]=inp;
return 0;
}
Should look something like:
if(inp%2==0){
odd[endofoddindex]=inp;
}
else
even[endofevenindex]=inp;
return 0;
}
That said, you won't get much use out of the arrays being local variables, since they are deallocated on each call. Your best bet is to declare the arrays in main and pass them in.
Your even and odd arrays are both local. This means that they exist as long as the function exists. So you won't be retrieve the data you have stored(You also don't store it correctly).
So you need both the arrays in main and also two other variables for using as the index of both the array(i and j in the below program). The modified program is given below:
#include <stdio.h>
int sort(int);
int main(){
int input, count,i=0,j=0; //i and j to be used as array indices
int odd[10];
int even[10]; //arrays in main
for(count=0;count!=10;count++){
printf("Enter 10 digits: ");
scanf("%d", &input);
if(sort(input)) //if odd number was found
odd[i++]=input;
else //even number found
even[j++]=input;
}
printf("%d", input);
//print even and odd arrays here
return 0;
}
int sort(int inp){
if(inp%2==0)
return 0; //if number is even,return 0
return 1; //else return 1
}
You need to either have your arrays as globals or pass them into your sort function. Where they are they currently they get recreated every time the sort function is called and are inaccessible to the rest of your program.
You will also need to keep track of the max number of ints in each array and the current number.
Your test in sort would be something like this:
if( inp % 2 == 0)
{
//TODO check that currentEvenCount < maxEvenCount
even[ currentEvenCount ] = inp;
currentEvenCount++
}
else
{
//TODO check that currentOddCount < maxOddCount
odd[ currentOddCount ] = inp;
currentOddCount++;
}
To declare your arrays as globals just move the declaration outside of any function above anywhere they are referenced
int even[10];
int odd[10];
int main() ...
To pass them as parameters to sort function you could declare sort like this:
sort( int inp, int even[], int maxEvenCount, int* currentEvenCount, int odd[]. int maxOddCount, int* currentOddCount)
{
...
if( inp % 2 == 0)
{
//TODO check that currentEvenCount < maxEvenCount
even[ *currentEvenCount ] = inp;
(*currentEvenCount)++
}
}
The * in front of currentEventCount is dereferencing the pointer and getting/setting the actual value pointed to.
You would then call sort like so:
int main()
{
int evenArray[10];
int oddArray[10];
int currentEvenCount = 0;
int currentOddCount = 0;
...
sort( input, evenArray, 10, &currentEvenCount, oddArray, 10, &currentOddCount);
}
There is no any sense to define the arrays as local variables of function sort because each time the function is called the arrays are created anew.
The program could look the following way
#include <stdio.h>
#define N 10
enum Type { Even, Odd };
enum Type sort( int x )
{
return x % 2 == 0 ? Even : Odd;
}
int main( void )
{
int odd[N];
int even[N];
int odd_count = 0;
int even_count = 0;
int i;
printf( "Enter %d numbers: ", N );
for( i = 0; i < N; i++ )
{
int num;
scanf( "%d", &num );
switch ( sort( num ) )
{
case Even:
even[even_count++] = num;
break;
case Odd:
odd[odd_count++] = num;
break;
}
}
printf( "Even numbers (%d):", even_count );
for ( i = 0; i < even_count; i++ ) printf( " %d", even[i] );
printf( "\n" );
printf( "Odd numbers (%d):", odd_count );
for ( i = 0; i < odd_count; i++ ) printf( " %d", odd[i] );
printf( "\n" );
return 0;
}
If to enter
5 6 12 10 0 3 4 100 -1 7
then the output will be
Even numbers (6): 6 12 10 0 4 100
Odd numbers (4): 5 3 -1 7
Simply copy, paste and investigate the program.:)
Hope this program will solve you issue. Here is the working code.
#include <stdio.h>
int sort(int[]);
int main(){
int input[10], count;
printf("Enter 10 digits: ");
for(count=0;count<10;count++){
scanf("%d", &input[count]);
}
sort(input);
return 0;
}
int sort(int inp[]){
int odd[10];
int even[10];
int oddCount=0, evenCount=0;
int i;
for(i=0; i<10;i++)
{
if(inp[i]%2==0){
even[evenCount]=inp[i];
evenCount++;
}
else
{
odd[oddCount]=inp[i];
oddCount++;
}
}
printf("ODD COUNT is %d \n", oddCount);
for(i=0; i<oddCount;i++)
{
printf("ODD VALUE %d \n", odd[i]);
}
printf("EVEN COUNT is %d \n", evenCount);
for(i=0; i<evenCount;i++)
{
printf("EVEN VALUE %d \n", even[i]);
}
return 0;
}
Your variable input is just an int, it's not an array. You need two arrays:
int even[10], odd[10];
Then you need to keep track of the number of numbers you've read so far, and for each number check which array to store it in.
I don't see a need to do sorting, so not sure why you have a function called sort().
It should just be something like:
int even[10], odd[10];
int oddindex = 0, evenindex = 0;
while(scanf(" %d", &x) == 1)
{
if(x % 2 == 0)
even[evenindex++] = x;
else
odd[oddindex++] = x;
if((evenindex + oddindex) >= 10)
break;
}
/* Loop here to print numbers. */
An answer suitable for an assignment question:
int main()
{
int i,c,o[10],e[10];int oc=0;int ec=0;int*pc;for(c=0;c<10;c++){scanf("%d",&i);pc=(i&1)?&o[oc++]:&e[ec++];*pc=i;}
// Now print out the values as requested in oc, o, ec and e.
}

Resources