srand() in dice game [duplicate] - c

This question already has answers here:
srand() — why call it only once?
(7 answers)
Closed 8 years ago.
I've been searching the site for possible answers to this problem, and although they're all similar they don't seem to be the exact same problem that I have, which is why I've been forced to open this question. SO I need to make a dice game that is supposed to roll 2 dice ranged from 1-6 and the user is supposed to guess what the number will be. The program then outputs the values of the die and reroll's if the guessed value isn't the real value of the 2 die. If it is then the program stops rolling the die and tells you how many rolls it took for the die to reach your guessed value.
For some reason my program keeps rolling the die over and over without stopping and I'm not exactly sure why. I tried testing it in a seperate program and have gotten even more confused as to why I still can't get different values even with srand() being called only once at the beginning of main.(I realized that, among a few other problems were what was wrong with the functions throwCalc1 and the unnecessary throwCalc2) If I try to place rand() outside a variable, I get different values, but if I put it within a variable the values stay the same. I've tried making the variable a function and it still doesn't work as the compiler gives me an error saying "initialization makes pointer from integer without a cast"
test function:
int main(void)
{
srand(time(NULL));
int i;
int *throwCalc = rand() % 6 + 1;
for(i = 0; i < 6; i++) {
printf("value is: %d\n", *throwCalc);
}
return 0;
}
original program:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define _CRT_SECURE_NO_WARNINGS
#define MIN 2
#define MAX 12
int getInt(int min, int max) {
int retry = 1;
int value;
char after;
int cc;
do {
printf("Enter total sought \n"
"Range must be within [%d - %d]", min, max);
cc = scanf("%d%c", &value, &after);
if(cc == 0) {
printf("bad char or 0 input, please re-enter input");
clear();
} else if (after != '\n') {
printf("Error:Trailing characters, please re-ente input");
clear();
} else if (value < min || value > max) {
printf("Error: value outside of range, please re-enter input");
clear();
} else {
retry = 0;
}
} while(retry == 1);
return value;
}
void clear() {
while (getchar() != '\n') {
; //intentional empty statement
}
}
int throwCalc1() {
int a = 1, b = 6, n;
srand(time(NULL));
n = a + rand() % (b + 1 - a);
return n;
}
int throwCalc2() {
int a = 1, b = 6, n;
srand(time(NULL));
n = a + rand() % (b + 1 - a);
return n;
}
int throwResult(int input, int getcalc1, int getcalc2) {
int i = 0;
do {
throwCalc1();
throwCalc2();
printf("Result of throw %d : %d + %d", i, getcalc1, getcalc2);
i++;
} while(input != getcalc1 + getcalc2);
printf("You got your total in %d throws!\n", i);
return 0;
}
int main(void)
{
int input = getInt(MIN, MAX);
int getCalc1 = throwCalc1();
int getCalc2 = throwCalc2();
printf("Game of Dice\n");
printf("============\n");
printf("hi number is: %d", input);
throwResult(input, getCalc1, getCalc2);
return 0;
}

You do this once at the top of main:
int getCalc1 = throwCalc1();
int getCalc2 = throwCalc2();
And then expect the values to update just by calling throwCalc1() & 2 again.
Besides fixing srand(), have throwCalc1 & 2 return values into local variables instead of passing something in.

Right now you are calling throwCalc1() and throwCalc2() within your loop, but throwing away the results. You need to save those results in a pair of variables:
do {
getcalc1 = throwCalc1();
getcalc2 = throwCalc2();
printf("Result of throw %d : %d + %d", i, getcalc1, getcalc2);
i++;
} while(input != getcalc1 + getcalc2);
After you've done this, you might notice that getcalc and getcalc2 don't need to be parameters to that function - they can just be local variables within throwResult().
In addition, your throwCalc1() and throwCalc2() functions are identical, so you can remove one them and just call the remaining one twice.
Your test function should look like:
int main(void)
{
srand(time(NULL));
int i;
int throwCalc;
for(i = 0; i < 6; i++) {
throwCalc = rand() % 6 + 1;
printf("value is: %d\n", throwCalc);
}
return 0;
}

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

Some problems in coding a "guessing random number in C" under some conditions such as using input(), output()

I tried going beyond just guessing random numbers. The conditions were these:
use input() numbers used from 1 to100 and if inserted numbers that are out of this range, to show a line to re-enter a number
use output() to show the output(but show the last line```You got it right on your Nth try!" on the main())
make the inserted number keep showing on the next line.
Basically, the program should be made to show like this :
insert a number : 70
bigger than 0 smaller than 70.
insert a number : 35
bigger than 35 smaller than 70.
insert a number : 55
bigger than 55 smaller than 70.
insert a number : 60
bigger than 55 smaller than 60.
insert a number : 57
You got it right on your 5th try!
I've been working on this already for 6 hours now...(since I'm a beginner)... and thankfully I've been able to manage to get the basic structure so that the program would at least be able to show whether the number is bigger than the inserted number of smaller than the inserted number.
The problem is, I am unable to get the numbers to be keep showing on the line. For example, I can't the inserted number 70 keep showing on smaller than 70.
Also, I am unable to find out how to get the number of how many tries have been made. I first tried to put it in the input() as count = 0 ... count++; but failed in the output. Then I tried to put in in the output(), but the output wouldn't return the count so I failed again.
I hope to get advice on this problem.
The following is the code that I wrote that has no errors, but problems in that it doesn't match the conditions of the final outcome.
(By the way, I'm currently using Visual Studio 2017 which is why there is a line of #pragma warning (disable : 4996), and myflush instead of fflush.)
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#pragma warning (disable : 4996)
int input();
int random(int);
void myflush();
void output(int, int);
int main()
{
int num;
int i;
int ran;
srand((unsigned int)time(NULL));
i = 0;
while (i < 1) {
ran = 1 + random(101);
++i;
}
num = input();
output(ran, num);
printf("You got it right on your th try!");a
return 0;
}
int input()
{
int num;
printf("insert a number : ");
scanf("%d", &num);
while (num < 1 || num > 100 || getchar() != '\n') {
myflush();
printf("insert a number : ");
scanf("%d", &num);
}
return num;
}
int random(int n)
{
int res;
res = rand() % n;
return res;
}
void myflush()
{
while (getchar() != '\n') {
;
}
return;
}
void output(int ran, int num) {
while (1) {
if (num != ran){
if (num < ran) {
printf("bigger than %d \n", num); //
}
else if (num > ran) {
printf("smaller than %d.\n", num);
}
printf("insert a number : ");
scanf("%d", &num);
}
else {
break;
}
}
return;
}
There are many problem and possible simplifications in this code.
use fgets to read a line then scanf the line content. This avoids the need of myflush which doesn’t work properly.
the function random is not needed since picking a random number is a simple expression.
if the range of the random number is [1,100], you should use 1+rand()%100.
there is no real need for the function output since it’s the core of the main program. The input function is however good to keep to encapsulate input.
you should test the return value of scanf because the input may not always contain a number.
Here is a simplified code that provides the desired output.
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#pragma warning (disable : 4996)
int input() {
char line[100];
int num, nVal;
printf("insert a number : ");
fgets(line, sizeof line, stdin);
nVal = sscanf(line, "%d", &num);
while (nVal != 1 || num < 1 || num > 100) {
printf("insert a number : ");
fgets(line, sizeof line, stdin);
nVal = sscanf(line, "%d", &num);
}
return num;
}
int main()
{
int cnt = 0, lowerLimit = 0, upperLimit = 101;
srand((unsigned int)time(NULL));
// pick a random number in the range [1,100]
int ran = 1 + rand()%100;
while(1) {
cnt++;
int num = input();
if (num == ran)
break;
if (num > lowerLimit && num < upperLimit) {
if (num < ran)
lowerLimit = num;
else
upperLimit = num;
}
printf("bigger than %d and smaller than %d\n", lowerLimit, upperLimit);
}
printf("You got it right on your %dth try!\n", cnt);
return 0;
}
I am unable to find out how to get the number of how many tries have been made.
Change the output function from void to int so it can return a value for count, and note comments for other changes:
int output(int ran, int num) {//changed from void to int
int count = 0;//create a variable to track tries
while (1) {
if (num != ran){
count++;//increment tries here and...
if (num < ran) {
printf("bigger than %d \n", num); //
}
else if (num > ran) {
printf("smaller than %d.\n", num);
}
printf("insert a number : ");
scanf("%d", &num);
}
else {
count++;//... here
break;
}
}
return count;//return value for accumulated tries
}
Then in main:
//declare count
int count = 0;
...
count = output(ran, num);
printf("You got it right on your %dth try!", count);
With these modifications, your code ran as you described above.
(However, th doesn't work so well though for the 1st, 2nd or 3rd tries)
If you want the program to always display the highest entered number that is lower than the random number ("bigger than") and the lowest entered number that is higher then the random number ("smaller than"), then your program must remember these two numbers so it can update and print them as necessary.
In the function main, you could declare the following two ints:
int bigger_than, smaller_than;
These variables must go into the function main, because these numbers must be remembered for the entire duration of the program. The function main is the only function which runs for the entire program, all other functions only run for a short time. An alternative would be to declare these two variables as global. However, that is considered bad programming style.
These variables will of course have to be updated when the user enters a new number.
These two ints would have to be passed to the function output every time it is called, increasing the number of parameters of this function from 2 to 4.
If you want a counter to count the number of numbers entered, you will also have to remember this value in the function main (or as a global variable) and pass it to the function output. This will increase the number of parameters for the function to 5.
If you don't want to pass so many parameters to output, you could merge the contents of the functions output and input into the function main.
However, either way, you will have to move most of the "smaller than" and "bigger than" logic from the function output into the function main, because that logic is required for changing the new "bigger_than" and "smaller_than" int variables which belong to the function main. The function output should only contain the actual printing logic.
Although it is technically possible to change these two variables that belong to the function main from inside the function output, I don't recommend it, because that would get messy. It would require you to pass several pointers to the function output, which would allow that function to change the variables that belong to the function main.
I have now written my own solution and I found that it is much easier to write by merging the function output into main. I also merged all the other functions into main, but that wasn't as important as merging the function output.
Here is my code:
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#pragma warning (disable : 4996)
int main()
{
const char *ordinals[4] = { "st", "nd", "rd", "th" };
int num_tries = 0;
int bigger_than = 0, smaller_than = 101;
int input_num;
int random_num;
srand( (unsigned int)time( NULL ) );
random_num = 1 + rand() % 101;
for (;;) //infinite loop, equivalent to while(1)
{
printf( "Bigger than: %d, Smaller than: %d\n", bigger_than, smaller_than );
printf( "enter a number: " );
scanf( "%d", &input_num );
printf( "You entered: %d\n", input_num );
num_tries++;
if ( input_num == random_num ) break;
if ( input_num < random_num )
{
if ( bigger_than < input_num )
{
bigger_than = input_num;
}
}
else
{
if ( smaller_than > input_num )
{
smaller_than = input_num;
}
}
}
printf( "You got it right on your %d%s try!", num_tries, ordinals[num_tries<3?num_tries:3] );
return 0;
}
Also, I made sure that the program would print "1st", "2nd" and "3rd", whereas all the other solutions simply print "1th", "2th", "3th". I used the c++ conditional operator for this.

i have a problem with my code and i'm not sure if i even wrote it correctly

so i'm practicing c and i built a program that says if its prime number or not and i tried to execute it but it wont work it doesnt shows me the output oh and im still new to this i started learning c one week ago.
i dont know how to fix this.
#include <stdio.h>
void Num();
int main()
{
void Num();
return 0;
}
void Num()
{
int n, i, flag = 0;
printf("Enter a num: ");
scanf("%d", &n);
for(i = 1; i <= 10; i++)
{
for(n = 1; n <= 10; n++)
{
flag = 1;
}
}
if( flag == 1)
{
printf("its not the prime num ");
} else{
printf("its the prime num" );
}
}
it wont even show the printf output
You need to go back to the basics (this means: reading a good C book before diving in). You are confusing declaration and calling of functions.
int main()
{
void Num();
return 0;
}
main contains two statements:
A local (re)declaration of Num as a function without return value.
A return statement.
Since you want to call Num rather than redeclaring it, you need to use the function call syntax:
int main()
{
Num();
return 0;
}
This is just the first step, however. Your Num function does not perform the correct actions to determine primality.

How do I go through a certain number and extract digits smaller than 5 using a recursive function?

it's me again. I deleted my previous question because it was very poorly asked and I didn't even include any code (i'm new at this site, and new at C). So I need to write a program that prints out the digits smaller than 5 out of a given number, and the number of the digits.
For example: 5427891 should be 421 - 3
The assignment also states that i need to print the numbers smaller than 5 in a recursive function, using void.
This is what I've written so far
#include<stdio.h>
void countNum(int n){
//no idea how to start here
}
int main()
{
int num, count = 0;
scanf("%d", &num);
while(num != 0){
num /= 10;
++count;
}
printf(" - %d\n", count);
}
I've written the main function that counts the number of digits, the idea is that i'll assign (not sure i'm using the right word here) the num integer to CountNum to count the number of digits in the result. However, this is where I got stuck. I don't know how to extract and print the digits <5 in my void function. Any tips?
Edit:
I've tried a different method (without using void and starting all over again), but now i get the digits I need, except in reverse. For example, instead of printing out 1324 i get 4231.
Here is the code
#include <stdio.h>
int rec(int num){
if (num==0) {
return 0;
}
int dg=0;
if(num%10<5){
printf("%d", num%10);
dg++;
}
return rec(num/10);
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++)
{
scanf("%d", &a);
rec(a);
printf(" \n");
}
return 0;
}
Why is this happening and how should I fix it?
There is nothing in your question that specifies the digits being input are part of an actual int. Rather, its just a sequence of chars that happen to (hopefully) be somewhere in { 0..9 } and in so being, represent some non-bounded number.
That said, you can send as many digit-chars as you like to the following, be it one or a million, makes no difference. As soon as a non-digit or EOF from stdin is encountered, the algorithm will unwind and accumulate the total you seek.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int countDigitsLessThanFive()
{
int c = fgetc(stdin);
if (c == EOF || !isdigit((unsigned char)c))
return 0;
if (c < '5')
{
fputc(c, stdout);
return 1 + countDigitsLessThanFive();
}
return countDigitsLessThanFive();
}
int main()
{
printf(" - %d\n", countDigitsLessThanFive());
return EXIT_SUCCESS;
}
Sample Input/Output
1239872462934800192830823978492387428012983
1232423400123023423420123 - 25
12398724629348001928308239784923874280129831239872462934800192830823978492387428012983
12324234001230234234201231232423400123023423420123 - 50
I somewhat suspect this is not what you're looking for, but I'll leave it here long enough to have you take a peek before dropping it. This algorithm is fairly pointless for a useful demonstration of recursion, to be honest, but at least demonstrates recursion none-the-less.
Modified to print values from most significant to least.
Use the remainder operator %.
"The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined" C11dr §6.5.5
On each recursion, find the least significant digit and test it. then divide the number by 10 and recurse if needed. Print this value, if any, after the recursive call.
static int PrintSmallDigit_r(int num) {
int count = 0;
int digit = abs(num % 10);
num /= 10;
if (num) {
count = PrintSmallDigit_r(num);
}
if (digit < 5) {
count++;
putc(digit + '0', stdout);
}
return count;
}
void PrintSmallDigits(int num) {
printf(" - %d\n", PrintSmallDigit_r(num));
}
int main(void) {
PrintSmallDigits(5427891);
PrintSmallDigits(-5427891);
PrintSmallDigits(0);
return 0;
}
Output
421 - 3
421 - 3
0 - 1
Notes:
This approach works for 0 and negative numbers.
First of all, what you wrote is not a recursion. The idea is that the function will call itself with the less number of digits every time until it'll check them all.
Here is a snippet which might help you to understand the idea:
int countNum(int val)
{
if(!val) return 0;
return countNum(val/10) + ((val % 10) < 5);
}
void countNum(int n, int *c){
if(n != 0){
int num = n % 10;
countNum(n / 10, c);
if(num < 5){
printf("%d", num);
++*c;
}
}
}
int main(){
int num, count = 0;
scanf("%d", &num);
countNum(num, &count);
printf(" - %d\n", count);
return 0;
}
for UPDATE
int rec(int num){
if (num==0) {
return 0;
}
int dg;
dg = rec(num/10);//The order in which you call.
if(num%10<5){
printf("%d", num%10);
dg++;
}
return dg;
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++){
scanf("%d", &a);
printf(" - %d\n", rec(a));
}
return 0;
}

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