C program error - outputting 0 - c

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;

Related

write a program that computes and displays the factorial of a positive integer n entered by the user

Been working on this question for class. Not sure what I'm doing wrong.
Seems like I just don't have the correct format. My professor wants the output to look like "5!=1 * 2* 3* 4* 5=120"
Can someone help me with this? Below is what I have so far:
#include <iostream>
#include <stdio.h>
int main() {
int n, i, fact;
printf("Enter a positive integer: \n");
scanf("%d", &n);
if (n < 0)
printf("Error! Factorial of a negative number doesn't exist.");
else {
for( i = 1; i <= n; ++i) {
fact *= i;
n= n * (n-1);
}
printf("Factorial of %d = ", &n, &fact) ;
}
return 0;
}
remove #include <iostream> if it is the C code
Use functions.
Initialize local variables (you do not and it is undefined behaviour)
Compile C program using C compilers
unsigned long long fact(unsigned val, char *buff)
{
unsigned result = 1;
*buff++ = '1';
*buff = 0;
for(unsigned c = 2; c <= val; c++)
{
buff += sprintf(buff, "x%u", c);
result *= c;
}
return result;
}
int main(void)
{
unsigned x;
char y[1000];
unsigned long long res;
if(scanf("%u", &x) == 1){res = fact(x, y); printf("factoral(%u) = %s = %llu\n", x, y, res);}
else printf("Invalid number!!!\n");
}
or without printing steps
unsigned long long fact(unsigned val)
{
unsigned result;
switch(val)
{
case 0:
case 1:
result = 1;
break;
case 2:
result = 2;
break;
default:
result = 2;
while(val > 2) result *= val--;
break;
}
return result;
}
int main(void)
{
unsigned x;
if(scanf("%u", &x) == 1) printf("factioral(%u) = %llu\n", x, fact(x));
else printf("Invalid number!!!\n");
}
https://godbolt.org/z/Tf5431zco
For starters it does not make a sense to declare the variable n as having a signed integer type. It is better to declare it as having unsigned integer type. For example
unsigned int n, i, fact;
Secondly the variable fact was not initialized. You should initialize it by the value equal to 1.
So the above declaration could look like
unsigned int n, i;
unsigned long long fact = 1;
In this for loop
for( i = 1; i <= n; ++i) {
fact *= i;
n= n * (n-1);
}
the statement
n= n * (n-1);
does not make a sense and shall be removed.
In the printf call you have to use values of variables instead of pointers to the variables like
printf("Factorial of %u = %llu\n", n, fact) ;
Pay attention to that neither declaration from the header <iostream> is used in your program So whether it is a C program or a C++ program nevertheless remove this header.
Here is a demonstration C program.
#include <stdio.h>
int main( void )
{
unsigned int n = 0;
unsigned long long int fact = 1;
printf( "Enter a positive integer: " );
scanf( "%u", &n );
printf( "%u! = ", n );
for ( unsigned int i = 1; i <= n; i++ )
{
fact *= i;
if ( i != 1 ) printf( " * " );
printf( "%u", i );
}
printf( " = %llu\n", fact );
}
The program output might look like
Enter a positive integer: 5
5! = 1 * 2 * 3 * 4 * 5 = 120
If you are allowed to use only variables of the type int as you wrote in a comment to the answer then the program can look like
#include <stdio.h>
int main( void )
{
int n = 0;
int fact = 1;
printf( "Enter a positive integer: " );
scanf( "%d", &n );
if ( n < 0 )
{
puts( "Error! Factorial of a negative number doesn't exist.");
}
else
{
printf( "%d! = ", n );
for ( int i = 1; i <= n; i++ )
{
fact *= i;
if ( i != 1 ) printf( " * " );
printf( "%d", i );
}
printf( " = %d\n", fact );
}
}
To output multipliers in the reverse order like
5! = 5 * 4 * 3 * 2 * 1 = 120
rewrite the for loop the following way
for ( int i = n; i != 0; i-- )
{
fact *= i;
if ( i != n ) printf( " * " );
printf( "%d", i );
}

counting consecutive value and printing in c programming

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

How to read only numbers from file until EOF in C

I have this function to find the max and min value of numbers in file with uknown text("ADS 50 d 15"). It works fine with only digits in the file, but when there is a characters it just stops.
{
int n;
int min = INT_MAX, max = INT_MIN;
int flag = 0;
rewind(f);
while (fscanf(f, "%d", &n) != EOF)
{
if (ferror(f))
{
perror("Error:");
}
if (flag == 0)
{
min = n;
max = n;
flag = 1;
}
if (min>n)
min = n;
if (max<n)
max = n;
}
printf("\nMax value: %d\nMin value: %d\n", max, min);
}
fscanf will return EOF after reaching the end of the file. It will return 1 on successful scanning an integer. If the input is not an integer, it will return 0 and the problem input has to be removed.
{
int n;
int min = INT_MAX, max = INT_MIN;
int result = 0;
char skip = 0;
rewind ( f);
while ( ( result = fscanf ( f, "%d", &n)) != EOF)
{
if (result == 0)
{
fscanf ( f, "%c", &skip);//remove a character and try again
}
else
{
if (min>n)
min = n;
if (max<n)
max = n;
}
}
printf("\nMax value: %d\nMin value: %d\n", max, min);
Try the following approach as it is shown in this demonstrative program. You have to use the fscanf instead of scanf used in this program.
#include <stdio.h>
#include <ctype.h>
int main( void )
{
int min, max;
size_t n = 0;
while ( 1 )
{
char c;
int x = 0;
int success = scanf( "%d%c", &x, &c );
if ( success == EOF ) break;
if (success != 2 || !isspace( ( unsigned char )c ) )
{
scanf("%*[^ \t\n]");
clearerr(stdin);
}
else if ( n++ == 0 )
{
min = max = x;
}
else if ( max < x )
{
max = x;
}
else if ( x < min )
{
min = x;
}
}
if ( n )
{
printf( "\nThere were enetered %zu values\nmax value: %d\nMin value: %d\n",
n, max, min );
}
return 0;
}
If the input looks like
1 2 3 4 5a a6 7 b 8
then the output will be
There were enetered 6 values
max value: 8
Min value: 1

How to create try counter in C?

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

Simple C Program is not getting printed

I am trying to run this simple code:
#include <stdio.h>
int main()
{
int n = 3;
printf("Enter your number: ");
scanf("%d",&n);
int faculty(int n){
int i = 1;
int res = 1;
for (i = 2;i<= n;i++){
res = res * i;
}
printf("the value is %d\n",res);
return(0);
}
}
But somehow there is no result showing up. Could you please explain me how it should be implemented properly?
Thanks in advance!
Please try this:
#include
int faculty( int n )
{
int i = 1;
int res = 1;
for ( i = 2; i <= n; i++ )
{
res = res * i;
}
printf( "the value is %d\n", res );
getchar( );
return ( 0 );
}
int main( )
{
int n = 3;
printf( "Enter your number: " );
scanf( " %d", &n );
faculty( n );
}

Resources