So, I've just started to learn C. I decided to make a basic number guessing game, where it tells you if you were too high or too low, and gives you up to 5 tries. I've got it working, but I can't figure out how to do the 5 tries. Any tips or help would be appreciated.
#include <stdio.h> /* printf, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
int main()
{
srand(time(NULL));
int r = ( rand() % 10 ) + 1; /* generates "random" number */
int number;
int c = 0;
printf( "Guess a number from one to ten!\n" );
do {
scanf( "%d", &number);
if (number == r) {
printf( "Correct! You win!!!\n" );
c = 1; /* ends loop if correct */
}
else if (number > r) {
printf( "Too high! Try again!\n" );
}
else {
printf( "Too low! Try again!\n" );
}
}
while ( c == 0 );
return 0;
}
Add a counter to your loop condition:
int counter = 0;
do {
....
counter++;
}
while ( c == 0 && counter < 5 );
Change c == 0 to c != 5. Everytime they guess incorrect increment c by 1. Also if they guess correctly either do c = 5 or use the keyword break to break out of the do-while loop. You are quite close though.
you can add a loop outside the origin loop in your program.
for (i=0;i<5;i++)
{ ...
if (number=r)
{ printf("you win.");
return 0;
}
else if ...
Preferably, do like this, for best readability:
const int MAX = 5;
bool found = false;
for(int tries=0; !found && tries<MAX; tries++)
{
scanf( "%d", &number);
if (number < r)
{
// ...
}
else if(number > r)
{
// ...
}
else // number == r
{
found = true;
}
}
if(found)
{
// ...
}
else
{
// ...
}
As a rule of thumb, always use a for loop when the number of iterations are known in advance.
Mainteining your do while loop you can do
#include <stdio.h> /* printf, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#define MAX_TRY 5
int main()
{
srand(time(NULL));
int r = ( rand() % 10 ) + 1; /* generates "random" number */
int number;
int c = 0;
printf( "Guess a number from one to ten!\n" );
do
{
scanf( "%d", &number);
// Count the new inserted value
c++;
if (number > r)
{
printf( "Too high! Try again!\n" );
}
else if (number < r)
{
printf( "Too low! Try again!\n" );
}
else
{
printf( "Correct! You win!!!\n" );
c = MAX_TRY; /* ends loop if correct */
}
}
while ( c < MAX_TRY );
return 0;
}
As you can see
I changed the while condition to check that max tries are as stated.
I inverted your if-else sequence to make the loop able to exit
immediately after the correct value is inserted.
try this. I defined another variable int n=0 and used it just before your conditional sentence starts and in loop I used and operator.
#include <stdio.h> /* printf, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
int main()
{
srand(time(NULL));
int r = ( rand() % 10 ) + 1; /* generates "random" number */
int number;
int c = 0,n=0; /* new int variable defined */
printf( "Guess a number from one to ten!\n" );
do {
n+=1;
scanf( "%d", &number);
if (number == r) {
printf( "Correct! You win!!!\n" );
c = 1; /* ends loop if correct */
}
else if (number > r) {
printf( "Too high! Try again!\n" );
}
else {
printf( "Too low! Try again!\n" );
}
}
while ( c == 0 && n != 5);
return 0;
}
i hope it helps.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
srand(time(NULL));
int r = ( rand() % 10 ) + 1; /* generates "random" number */
int number;
int c = 0; /* new int variable defined */
printf( "Guess a number from one to ten!\n" );
do {
c+=1;
scanf( "%d", &number);
if (number == r) {
printf( "Correct! You win!!!\n" );
break;
}
else if (number > r) {
printf( "Too high! Try again!\n" );
}
else {
printf( "Too low! Try again!\n" );
}
} while ( c<5);
if(c==5)
printf("You lose\n");
return 0;
}
Related
I am trying to make a code in C that takes a number as an input, counts how many times 0-9 appears in the given number.
The code as nooby as it might is:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num,dig,dat[9],mod;
printf("Give a number: ");
scanf("%d",&num);
mod = num % 10;
while(mod != 0)
{
if(mod > 1)
{
dig = mod / 10;
while(dig >= 0 )
{
++dat[dig];
}
}
else if(mod =1)
{
dig = mod/1;
while(dig >= 0 )
{
++dat[dig];
}
}
--mod;
}
printf("%d appears %d\n",dig,dat[dig]);
return 0;
}
Thanks in advance
Nothing really works, i dont even get any response from printf.
#include <stdio.h>
int main(void) {
int n = 12334268;
int digits[10] = {0};
while(n)
{
++digits[n%10];
n/=10;
}
for(int i=0; i<10; ++i)
{
if (digits[i])
{
printf("Digit %d appears %d times\n", i, digits[i]);
}
}
return 0;
}
Output
Success #stdin #stdout 0s 5512KB
Digit 1 appears 1 times
Digit 2 appears 2 times
Digit 3 appears 2 times
Digit 4 appears 1 times
Digit 6 appears 1 times
Digit 8 appears 1 times
For starters the array dat shall have 10 elements because there are 10 digits 0-9.
dat[10],
And moreover you are using the uninitialized array
++dat[dig];
If the entered number is divisible by 10 then the while loop is skipped
mod = num % 10;
while(mod != 0)
{
//...
So the code does not make sense.
Pay attention to that you should deal with unsigned integers. Otherwise the program shall take into account the sign of the entered number.
Also the user can enter 0 that is a valid number containing one digit 0.
The program can look the following way.
#include <stdio.h>
int main( void )
{
enum { N = 10 };
unsigned int digits[N] = { 0 };
unsigned int num;
printf( "Give a number: " );
if ( scanf( "%u",&num ) == 1 )
{
const unsigned int Base = 10;
do
{
++digits[num % Base];
} while ( num /= Base );
puts( "The number contains the following digits:" );
for ( unsigned int i = 0, j = 0; i < N; i++ )
{
if ( digits[i] != 0 )
{
if ( j != 0 ) printf( ", " );
printf( "%u: %u", i, digits[i] );
j = 1;
}
}
}
}
how to count consecutive two heads and tails in this program please help me, I am really stuck, I tried hard but failed please, write the code for consecutive please, I am very hopeful that StackOverflow can help me
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int flip();
int main()
{
int loop;
int headCount = 0;
int tailCount = 0;
srand( time( NULL ) );
for ( loop = 1; loop <= 100; loop++ ) {
if ( flip() == 0 )
{
tailCount++;
}
else
{
headCount++;
}
if ( loop % 10 == 0 )
{
printf( "\n" );
}
}
printf( "\nThe total number of consecutive Heads was %d\n", headCount );
printf( "The total number ofconsecutive Tails was %d\n", tailCount );
return 0;
}
int flip() {
int HorT = rand() %2;
if ( HorT == 0) {
printf( "Tails " );
}
else
{
printf( "Heads " ); }
return HorT;
}
I don't know how you want to count 4 consecutive runs of a tail (is that 3, or 4 or 2?), and I'm not going to worry too much about it. Mostly posting this to point out some stylistic issues with your code. You can greatly simplify what you're doing with something like:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int flip(void);
int
main(int argc, char **argv)
{
int loop;
int max = argc > 1 ? strtol(argv[1], NULL, 10) : 100;
int count[2] = {0, 0};
int prev = -1;
srand(time(NULL));
for( loop = 0; loop < max; loop++ ) {
int t = flip();
if( t == prev ) {
count[t] += 1;
}
if( loop % 10 == 9 || loop == max - 1 ) {
putchar('\n');
}
prev = t;
}
printf( "\nThe total number of consecutive Heads was %d\n", count[0]);
printf( "The total number of consecutive Tails was %d\n", count[1]);
return EXIT_SUCCESS;
}
int
flip(void)
{
int HorT = rand() % 2;
fputs(HorT ? "Heads " : "Tails ", stdout);
return HorT;
}
I had an interview last week. They asked me to write a code to print like this
input :5
0
101
21012
3210123
432101234
54321012345
i wrote the below code but he said i could optimize this more . i cant figure it out.
,
int main(){
int n,i,j,k,lim,num;
scanf("%d",&n);//getting input starting number of last row
lim=n;
int collen=n+2;//it denotes end of row
for(i=0;i<n+1;i++)
{
num=i;
k=0;
for(j=0;j<collen-1;j++){
if(j<lim)
printf(" ");
else if(num<0){
printf("%d",++k);
}
else{
printf("%d",num--);
}
}//j for
printf("\n");
collen++;
lim--;
}//i for
}// main end
I have different code at first attempt, I used flag to detect when num reaches for incrementing and decrementing, it was complex there was about 4 if inside second loop, so I optimized that code to the above one. He said can you optimize more? I have no idea to optimize it .
My question: can it be optimized? If it can be - please post the code
There are more for-loops than those comparing by <. for(i=0;i<n+1;i++) is much clearer written as for (i = 0; i <= n; i++).
If you initialize a value, in example int collen=n+2;, and later use it like collen-1, save the subtraction and initialize it adjusted.
Separate this complex inner loop with ifs into their own loops.
Use less variables.
Use more and consistent whitespace.
And now my solution, but as yours it can only handle inputs from 0 to 9:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n;
printf("input :");
if (scanf("%d", &n) != 1 || n < 0 || n > 9) {
printf("input not recognized or invalid\n");
return EXIT_FAILURE;
}
for (int i = 0; i <= n; ++i) {
printf("%*d", n - i + 1, i);
for (int j = i - 1; j >= 0; --j) {
printf("%d", j);
}
for (int j = 1; j <= i; ++j) {
printf("%d", j);
}
printf("\n");
}
return EXIT_SUCCESS;
}
This looks optimized to the brims:
int main( int argc, char **argv )
{
puts( "input :5");
puts( " 0");
puts( " 101");
puts( " 21012");
puts( " 3210123");
puts( " 432101234");
puts( "54321012345");
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* Print a pyramid */
int
main(int argc, char **argv)
{
int size = argc > 1 ? strtol(argv[1],NULL,10) : 5;
if( size > 9 || size < 0) {
fprintf(stderr, "Invalid size\n");
return EXIT_FAILURE;
}
for(int line = 0; line <= size; line++) {
char template[]="9876543210123456789";
char *s = template + 9 - size;
template[10 + line] = '\0';
memset(s, ' ', size - line);
if(puts(s) == EOF) {
perror("puts");
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
I am having trouble refining some code. My code takes a number "n" and calculates that many prime numbers. I need to display 10 primes per line of output data. Any tips would be appreciated.
#include <stdio.h>
int main()
{
int n, i = 3, count, c;
printf("How many primes would you like?");
scanf("%d",&n);
if ( n >= 1 )
{
printf("2");
}
for ( count = 2 ; count <= n ; )
{
for ( c = 2 ; c <= i - 1 ; c++ )
{
if ( i%c == 0 )
break;
}
if ( c == i )
{
printf(" %d",i);
count++;
}
i++;
}
return 0;
}
Just try
printf(" %5d", i);
/* ^ to help align the numbers
and
if ((count + 1) % 10 == 0)
fputc(stdout, '\n');
fix for the first time when you already print 2.
bool is_prime(int anyNum) //takes an integer array returns, is_prime
{
bool is_prime = true;
for (int c = 2; c <= anyNum - 1; c++)
{
if (anyNum % c == 0)
{
//printf("%d is not prime\r\n" , anyNum);
is_prime = false;
}
}
return is_prime;
}
int main()
{
int num_primes;
printf("How many primes would you like: ");
std::cin >> num_primes;
printf("\r\nScanned Primes Are---\r\n");
int foundPrimes = 0;
int x = 0;
for (; x <= num_primes; x++)
{
bool gotLuckyFindingPrime = is_prime( x );
if (gotLuckyFindingPrime)
{
if (foundPrimes % 10 == 0)
{
printf("\r\n");
}
printf(" %d", x);
foundPrimes = (foundPrimes + 1) % 10;
}
}
}
Does handle ten digit showing on cmd too, you can experiment with formatting
I have been trying to get this to work for days now and I still cannot figure out the error. When I output the code, it prints, but it will not find the amicable pairs (divisor of first == second, and vice versa).
#include <stdio.h>
#include <stdlib.h>
#define _USE_MATH_DEFINES
#include <math.h>
int sumDivisors( int num );
int sumDivisors( int num )
{
int counter, total;
for( counter = 1; counter < num; counter++ )
{
if( num % counter == 0 )
{
total += counter;
}
}
return ( total );
}
int main( void )
{
int higher, lower, lowx, lowy, x, y, numOfPairs = 0;
printf( "This program finds all amicable numbers within a range. \n" );
printf( "Please enter a lower limit: \n" );
scanf( "%d", &lower );
printf( "Please enter a higher limit: \n" );
scanf( "%d", &higher );
for( lowx = lower; lowx <= higher; lowx++ )
{
for( lowy = lower; lowy <= higher; lowy++ )
{
if( sumDivisors( lowx ) == sumDivisors( lowy ) )
{
numOfPairs++;
printf( "Pair #%d: (%d, %d)\n", numOfPairs, lowx, lowy );
}
}
}
printf( "There are %d amicable pairs from %d to %d\n", numOfPairs, lower, higher );
system("pause");
return ( 0 );
}
You are not assigning any value to total in your code:
int sumDivisors( int num )
{
int counter, total;
for( counter = 1; counter < num; counter++ )
{
if( num % counter == 0 )
{
total += counter;
}
}
return ( total );
}
so it contains garbage not predictable value!
it should be like: int counter, total = 0;