I can't store integers inside an array - c

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.
}

Related

Why this function gives me first sums correct and then prints bad sums

Write a program that prints the sum of digits for the entered interval limits. To calculate the sum of
digits form the corresponding function.
#include <stdio.h>
void suma(int a ,int b ){
int s= 0,i;
for(i=a;i<=b;i++){
while(i != 0 ){
int br = i % 10;
s+=br ;
i = i/10;
}
printf("%d\n",s);
}
}
int main(void){
int a,b;
printf("enter the lower limit of the interval: "); scanf("%d",&a);
printf("enter the upper limit of the interval: "); scanf("%d",&b);
suma(a,b);
return 0;
}
when i set a to be 11 and b to be 13 program does first 3 sums but after that it doesent stop.why doesn't it stop. But if i set a to 3 digit number program gives me first sum but then gives me random sums
The reason why your code is not working is because in your while-loop, you are changing the value of i, but i is also used in the for-loop. This results in undefined behaviour. In order to fix this, I would suggest breaking the problem up in two functions. One for calculating the sum of a the digits of a number, and one function that adds these sums in a particular range.
int sumNumber(int number) {
int sum = 0;
while(number != 0) {
sum += number % 10;
number /= 10;
}
return sum;
}
int suma(int a ,int b){
int totalSum = 0;
for(int i=a;i<=b;i++){
int sum = sumNumber(i);
totalSum += sum;
}
return totalSum;
}
This way, you are not modifying i in the while-loop.
You are mixing up the two loop variables. As arguments are passed by value just a instead of introducing an unnecessary variable. Minimize scope of variables. Check the return value from scanf() otherwise you may be operating on uninitialized variables.
#include <stdio.h>
void suma(int a, int b) {
for(; a <= b; a++) {
int s = 0;
for(int i = a; i; i /= 10) {
s += i % 10;
}
printf("%d\n", s);
}
}
int main(void){
printf("enter the lower limit of the interval: ");
int a;
if(scanf("%d",&a) != 1) {
printf("scanf failed\n");
return 1;
}
printf("enter the upper limit of the interval: ");
int b;
if(scanf("%d",&b) != 1) {
printf("scanf failed\n");
return 1;
}
suma(a,b);
}
and example run:
enter the lower limit of the interval: 10
enter the upper limit of the interval: 13
1
2
3
4
I was unreasonably annoyed by how the code was formatted. Extra white space for no reason including at end of line, missing white space between some operations, variables lumped together on one line.
It's a really good idea to separate i/o from logic as in #mennoschipper's answer. My answer is as close to original code as possible.
i did function like this and it works now
void suma(int a ,int b ){
int s= 0,i;
int x ;
for(i=a;i<=b;i++){
x = i;
while(x != 0 ){
int br = x % 10;
s+=br ;
x = x/10;
}
printf("%d\n",s);
s = 0;
} }

How do I print ordinal indicators in a C program? Can't print numbers with 'st', 'nd', 'rd'. (Beginner)

#include <stdio.h>
main()
{
int i, num, sum=0; //declaration
printf("How many numbers do you want to calculate average of?\n");
scanf("%d", &num); //how many numbers are to be calculated
printf("Enter %d numbers\n", num);
int a[num]; //array to store data
for(i=1;i<=num;i++) //loop to take input
{
if(i==1) //for 1st
printf("1st value : ");
else if (i<=2) //2nd
printf("2nd value : ");
else if (i<=3) //3rd
printf("3rd value : ");
else //else print th ordinal
printf("%dth value : ", i);
scanf("%d", &a[i]);
}
for(i=1;i<=num;i++)
sum+=a[i];
float avg;
avg=sum/num;
printf("Average : %f", avg);
return 0;
}
A program to take out the average of n numbers.
Now, this code does what it should, but if the size of the array goes beyond 20, it prints 21th, 22th, 23th and so on, which is wrong. I can't think of how to fix this problem. Any help would be great. I am new to programming, so pardon my ignorance.
There isn't a standard function that does that. You can write one, or use mine:
ordinal.c
#include "ordinal.h"
#include <stdio.h>
static const char *const suffixes[4] = { "th", "st", "nd", "rd" };
enum { NUM_SUFFIXES = sizeof(suffixes) / sizeof(suffixes[0]) };
static unsigned suffix_index(unsigned n)
{
unsigned x;
x = n % 100;
if (x == 11 || x == 12 || x == 13)
x = 0;
else if ((x = x % 10) > 3)
x = 0;
return x;
}
char *fmt_ordinal(char *buffer, size_t buflen, unsigned n)
{
unsigned x = suffix_index(n);
int len = snprintf(buffer, buflen, "%u%s", n, suffixes[x]);
if (len <= 0 || (size_t)len >= buflen)
return 0;
return(buffer);
}
ordinal.h
/* returns buffer or 0 on failure (implausible unless buffer too small) */
extern char *fmt_ordinal(char *buffer, size_t buflen, unsigned n);
Some of that is overkill on its own, but the source file also contains scn_ordinal() which scans ordinal numbers with greater or lesser strictness, and the header declares it.
int main(void)
{
char buffer[15];
/* Test fmt_ordinal() */
for (unsigned i = 0; i < 35; i++)
printf("%2u => %4s\n", i, fmt_ordinal(buffer, sizeof(buffer), i));
return 0;
}
You can mod by 10 to get the last digit. Then based on that you can use "st", "nd", "rd", or "th". You'll also need special cases for 11, 12, and 13.
if ((i % 10 == 1) && (i % 100 != 11))
printf("%dst value : ", i);
else if ((i % 10 == 2) && (i % 100 != 12))
printf("%dnd value : ", i);
else if ((i % 10 == 3) && (i % 100 != 13))
printf("%drd value : ", i);
else
printf("%dth value : ", i);
I played with this a bit and this was my minimal 'lookup' except, sadly, for the expense of the modulo division. I wasn't fussed about values above 99.
if( i > 20 ) i %= 10; // Change 21-99 to 1-10.
if( i > 3 ) i = 0; // Every other one ends with "th"
// 0 1 2 3
suffix = &"th\0st\0nd\0rd"[ i * 3 ]; // Acknowledge 3byte regions.
You can use 'suffix' as a pointer to a normal null terminated string.
It is okay to be a beginner, no need to apologize. You can solve your problem using a combination of a SWITCH statement and the modulus operator (%). The modulus operator takes two numbers (n1 % n2) and returns the remainder when n1 is divided by n2.
You will want to construct an array of ordinals, like this:
char *ordinalList[] = { "st", "nd", "rd", "th" };
This will allow you to simply reference this array to append the correct ordinal to a number. The next step is to create an algorithm to determine which array index should be referenced. To do this, you can make a new function and call it in your "main".
char *determineOrdinal (char **ordinalList, int numValue)
{
if (3 < numValue && numValue < 21)
return ordinals[3];
switch (numValue % 10) {
case 1 : return ordinalList[0];
break;
case 2 : return ordinalList[1];
break;
case 3 : return ordinalList[2];
break;
default: return ordinalList[3];
break;
}
You can pass a number into this function as the numValue argument. Your "main" function might look something like this:
#include <stdio.h>
int main(void)
{
char *ordinalList[] = { "st", "nd", "rd", "th" };
char *currentdOrdinal;
int i, num, sum=0; //declaration
printf("How many numbers do you want to calculate average of?\n");
scanf("%d", &num); //how many numbers are to be calculated
printf("Enter %d numbers\n", num);
int a[num]; //array to store data
for(i=1;i<=num;i++) //loop to take input
{
currentdOrdinal = determineOrdinal (ordinalList, i)
printf("%d%s value : ", i, currentdOrdinal);
scanf("%d", &a[i]);
}
for(i=1;i<=num;i++)
sum+=a[i];
float avg;
avg=sum/num;
printf("Average : %f", avg);
return 0;
}
I think that code should work for you. I hope this helps.

Can I 'return' a result from the main variable?

So I have this exercise where I need to show the N first prime numbers, but I need to specifically create a function to know if the number is a prime number
#include <stdio.h>
#include <stdlib.h>
int prime(int num){
int cont,i,j=0,b;
b=num;
do{
j++;
i=0;
for(cont=1;cont<j;cont++){
if(j%cont == 0)
i++;
}
if(i == 1){
return(j);
c=j;
b--;
}
} while (b > 0);
}
int main(){
int *v,n,cont;
do{
printf("Input an integer: ");
scanf("%d",&n);
} while (n <= 0);
v = (int *)malloc(n * sizeof(int));
for(cont=0;cont<n;cont++){
v[cont] = prime(n);
}
for(cont=0;cont<n;cont++){
printf("%d ",v[cont]);
}
}
The problem with the way i've done this is that the variable J is aways being set to 0 when i call the function again, i've tried to set something like c=j so when the program return to the prime function it would have the 'previous' j value but it gets a weird random number. So I wanted to know if is there a way to 'return' the result in the main function to the prime function, i couldn't find anything that helped me, not that i could understand at least
Your function prime() is not working as intended and there are many other errors -
1) Since smallest prime is 2, variable cont should start from 2.
2) scanf need not be in a loop in this case
3) Enter values in v only when cont is confirmed a prime.
See this function prime2( not optimize though for clarity):
bool prime2(int n)
{
for(int i = 2 ; i<n-1;i++)
if( n% i == 0) return false;
return true;
}
int main(){
int *v,n,cont,cc=0;
printf("Input range: ");
scanf("%d",&n);
v = malloc(n * sizeof(int));
for(cont=2;cc<n;cont++){
if( prime2(cont) == true )
{
v[cc] = cont;
cc++;
}
}
for(cont=0;cont<n;cont++){
printf("%d ",v[cont]);
}
delete v;
}
Output:

Calculating Size of the Array

I'm trying to calculate the size of the file . The process I've followed is to read the file and store it in an array and calculate its size. However,I really don't know ... I tried n number of ways..I've to pass this size as an attribute to the frequency function.along with the name of the array.
#include <stdio.h>
#include<conio.h>
void frequency (int theArray [ ], int ??????, int x)
{
int count = 0;
int u;
for (u = 0; u < ??????; u++)
{
if ( theArray[u]==x)
{
count = count + 1 ;
/*printf("\n%d",theArray[u]);*/
}
else
{
count = count ;
}
}
printf ("\nThe frequency of %d in your array is %d ",x,count);
}
void main()
{
FILE*file = fopen("num.txt","r");
int integers[100];
int i=0;
int r = 0;
int num;
int theArray[100];
int there[100];
int n;
int g;
int x;
while(fscanf(file,"%d",&num)>0)
{
integers[i]=num;
printf("\n%d",(integers[i]));
there[r] = integers[i];
i++;
}
//printf("%d",there[r]);
//printf("\n%d",file);
//fclose(file);
printf ("\n OK, Thanks! Now What Number Do You Want To Search For Frequency In Your Array? ");
scanf("\n%d", &x);/*Stores Number To Search For Frequency*/
frequency(integers,????????,x);
getch();
fclose(file);
}
?????? is the size of the integer array from where i read the file and stored it.
I could not find a way to calculate the size of the array into which i copied my file. My idea is to calculate the frequency of a number in that file and calculate the probability of it's occurrence and thereby calculating entropy..Suggestions please!
I don't know why you are initializing so many variables and some of them with awkward names like ??????.
Your main problem is that the call to function should be
frequency(integers, i, x);
Your code with the awkward irrelevant parts removed will look like
#include <stdio.h>
#include<conio.h>
void frequency (int theArray [ ], int number, int x)
{
int count = 0;
int u;
for (u = 0; u < number; u++)
{
if ( theArray[u]==x)
count++;
}
printf ("\nThe frequency of %d in your array is %d ",x,count);
}
void main()
{
FILE*file = fopen("num.txt","r");
int integers[100];
int i=0;
int num;
int x;
while(fscanf(file,"%d",&num)>0)
{
integers[i]=num;
printf("\n%d",integers[i]);
i++;
}
printf ("\n OK, Thanks! Now What Number Do You Want To Search For Frequency In Your Array? ");
scanf(" %d", &x);/*Stores Number To Search For Frequency*/
frequency(integers,i,x);
getch();
fclose(file);
}
There are a lot of parts of this code that don't make sense, but I assume it is your debugging trying to figure out what is wrong. The answer to your specific question is:
For each value read from the file you set integers[i] to the value and then increment i. Thus i is the count of items in integers. You then pass integers to frequency(), so i should be passed to the second parameter as the count.
Note that if there are more than 100 values in the file, you will over index integers and cause unpredictable behavior.
To calculate length of array:
int len= sizeof(arr)/sizeof(arr[0]);
It will give length of array without looping.

How to print integers in typing order in C - increasing, decreasing or evenly

I have a problem with a c program I'm trying to write. The program must store integers in array (read from the keyboard). The numbers must be printed out in the order of entering, for example if you enter: 3 2 0 5 5 5 8 9, the ouput should be:
3 2 0 - decreasing
5 5 5 - evenly
8 9 - increasing
The problem for me is, that I can't write an algorithm which to be able to work in all cases.
I was trying to "flag" the elements with another array(using the same index, to save for each integer a value 1-for increasing, -1-for decreasing and 0 for evenly), but this works partly.
Have you any other ideas?
Thanks in advance :)
#include <stdio.h>
#include <stdlib.h>
main() {
int array[100];
int flag[100];
int num, i;
printf("Enter how many numbers you want to type: ");
scanf("%d",&num);
for(i=0;i<num;i++) {
scanf("%d",&array[i]);
}
for(i=0;i<num;i++){
if((array[i]<array[i+1])) {
flag[i]=flag[i+1]=1;
}
if(array[i]>array[i+1]) {
flag[i]=flag[i+1]=-1;
}
}
for(i=0;i<num;i++) {
if(array[i]==array[i+1]) {
flag[i]=flag[i+1]=0;
}
}
for(i=0;i<num;i++){
printf("%d ",flag[i]);
}
printf("\n");
for(i=0;i<num;i++) {
if(flag[i]==1) {
do{
if(flag[i]==1){
printf("%d ",array[i]);
i++;
}
}while(flag[i]==1);
printf(" - increasing\n");
}
if(flag[i]==0) {
do{
if(flag[i]==0){
printf("%d ",array[i]);
i++;
}
}while(flag[i]==0);
printf(" - evenly\n");
}
if(flag[i]==-1) {
do{
if(flag[i]==-1) {
printf("%d ",array[i]);
i++;
}
}while(flag[i]==-1);
printf(" - decreasing\n");
}
}
system("pause");
return 0;
}
Thoughts:
You only know if the 'first' number belongs to a descending, even, or ascending sequence after you see the 'second' number.
The 'third' number either belongs to the same sequence as the first two or is the 'first' number of another sequence.
So: check two numbers and assign a sequence type.
Keep checking numbers in the same sequence.
When you cannot assign the same sequence go back to checking two numbers and assigning a sequence.
Something like
int *n1, *n2, *n3;
n1 = <first element>;
n2 = n1 + 1;
n3 = n2 + 1;
/* some kind of loop */
if ((n3 - n2) HAS_SOME_SIGN_AS (n2 - n1)) /* n3 belongs to the sequence */;
n1++;
n2++;
n3++;
/* end loop */
#include <stdio.h>
int status(a, b){
if(a < b) return 1;
if(a > b) return -1;
return 0;
}
int main() {
int array[100]={0};
int old_status, new_status;
int old_pos;
int num, i, j;
const char* status_message[] = {"decreasing","evenly","increasing", "i don't know"};
printf("Enter how many numbers you want to type: ");
scanf("%d",&num);
for(i=0;i<num;i++)
scanf("%d",&array[i]);
//{num | 1 < num <= 100}
old_status =status(array[0], array[1]);
old_pos = 0;
for(i=1;i<num;++i){
new_status = status(array[i-1], array[i]);
if(old_status != new_status){
for(j=old_pos;j<i;++j)
printf("%d ", array[j]);
printf("- %s\n", status_message[1 + old_status]);
old_status = (i<num-1)? status(array[i], array[i+1]):2;
old_pos = i;
}
}
if(old_pos < num){ //not output section output
for(j=old_pos;j<i;++j)
printf("%d ", array[j]);
printf("- %s\n", status_message[1 + old_status]);
}
return 0;
}

Resources