So I'm working on this assignment. I tried running this code, and it ceases to work after reading in the second number. Here is a synopsis of it:
Write a C program that prompts the user to enter two positive integers. Your program should then display the number of carry operations that result from adding the two numbers and print the result of the addition. The input continues until the user enters 0 for the first number.
For instance, if the input is 123 and 456, there are 0 carry operations. If the input is 666 and 777, there are 3 carry operations.
Here's my code (nothing happens once it gets to the while loop):
#include <stdio.h>
#include <string.h>
// ------------------------
char dummy;
char response = 'y';
int userNum1, userNum2, sum;
int carry = 0;
int factor = 1;
int digit1 = 1;
int digit2 = 1;
int main(void)
{
while (response == 'y' || response == 'Y')
{
printf ("Enter the first number: ");
scanf ("%d", &userNum1);
printf ("Enter the second number: ");
scanf ("%c", &dummy);
scanf ("%d", &userNum2);
sum = userNum1 + userNum2;
while (userNum1 > 0 && userNum2 > 0)
{
while (digit1 > 0 && digit2 > 0)
{
digit1 = getNum (userNum1);
digit2 = getNum (userNum2);
factor = factor * 10;
carryTheOne (digit1, digit2);
}
}
printf ("The sum is %d and there were %d carry operations", sum, carry);
printf("\n");
printf ("Do you want to do another one?");
scanf ("%c", &dummy);
scanf ("%c", &response);
scanf ("%c", &dummy);
}
return 0;
}
int getNum(int num)
{
num = ((num % (factor * 10)) / factor);
return num;
}
int carryTheOne (int num1, int num2)
{
if ((digit1 + digit2) > 9)
carry++;
return carry;
}
Can someone help me here and let me know what I'm doing wrong? It just prints a blank line after reading the second number and never does anything else (doesn't terminate, just doesn't do anything).
EDIT: I changed the while loop to this:
while (userNum1 > 0 && userNum2 > 0)
{
while (digit1 > 0 && digit2 > 0)
{
digit1 = getNum (userNum1);
digit2 = getNum (userNum2);
factor = factor * 10;
carryTheOne (digit1, digit2);
userNum1 = (userNum1 - digit1) / 10;
userNum2 = (userNum2 - digit2) / 10;
}
}
It worked for 123 and 456, but didn't work for 666 and 777. Any reason why?
Remove that factor variable. I have made for edits:
1.Comment out
int factor = 1;
2.comment out
factor = factor * 10;
3.change
userNum1 = (userNum1 - digit1) / 10;
userNum2 = (userNum2 - digit2) / 10;
to
userNum1 = userNum1 / 10;
userNum2 = userNum2 / 10;
4.change:
int getNum(int num)
{
num = ((num % (factor * 10)) / factor);
return num;
}
to
int getNum(int num)
{
num = num % 10;
return num;
}
Related
//Determine the prime factors of a number
for(i = 2; i <= num; i++) { //Loop to check the factors.
while(num % i == 0) { //While the input is divisible to "i" which is initially 2.
printf("%d ", i); //Print the factor.
num = num / i; //Divide the num by "i" which is initially 2 to change the value of num.
}
}
I know that this is the way of finding the prime factors of a number using for loop. But I don't know how to express the output integer as a product of its prime factors.
For example, INPUT IS: 10 ||
OUTPUT IS: 2 x 5 = 10. How do we do this? TIA.
You should:
Save the original value.
Print the operator x between each prime factors.
Print the original value at the end.
#include <stdio.h>
int main(void) {
int num;
int i;
int start_num;
int is_first = 1;
if(scanf("%d", &num) != 1) return 1;
start_num = num; //Save the original value.
//Determine the prime factors of a number
for(i = 2; i <= num; i++) { //Loop to check the factors.
while(num % i == 0) { //While the input is divisible to "i" which is initially 2.
if(!is_first) printf("x "); //Print the operator before second and later operands.
printf("%d ", i); //Print the factor.
num = num / i; //Divide the num by "i" which is initially 2 to change the value of num.
is_first = 0; //Mark that there is already one or more operand.
}
}
printf("= %d\n", start_num); //Print the original value.
return 0;
}
You can output the factors with the appropriate punctuation:
// Output the prime factors of a number
void factorize(int num) {
int n = num; // save the initial value of num
const char *sep = ""; // initial separator is an empty string
for (int i = 2; i <= num / i; i++) { // stop when num is reduced to a prime
while (num % i == 0) { // while the input is divisible to "i"
num = num / i; // divide the num by "i" (remove the factor)
printf("%s%d", sep, i); // print the separator and the factor.
sep = " x "; // change the separator for any further factors
}
}
if (num > 1 || n <= 1) {
printf("%s%d", sep, num); // print the last or single factor.
}
printf(" = %d\n", n); // print the rest of the equation
}
I've revised the code to give something that's a bit more robust than what I posted previously, as well as being slightly more efficient. Again I assume you want (unsigned) 32-bit input via stdin in the range: [1, 2^32 - 1]
As far as the algorithm is concerned, it should be apparent that searching for factors need only test candidates up to floor(sqrt(num)). There are also factors with multiplicity, e.g., (24) => {2, 2, 2, 3}.
Furthermore, after factoring out (2), only odd factors need to be tested.
For a 32-bit (unsigned) type, there will be fewer than (32) prime factors. This gives a simple upper-bound for a fixed-size array for storing the successive prime factors. The prime factors in the array are in ascending order, by virtue of the algorithm used.
/******************************************************************************/
#include <stdio.h>
int main (void)
{
/* print a value in [1, 2^32 - 1] as a product of primes: */
unsigned long int n, u, prime[32];
int np = 0;
if (scanf("%lu", & n) != 1 ||
((n == 0) || ((n & 0xffffffffUL) != n)))
{
fprintf(stderr, "factor < u32 = 1 .. 2^32 - 1 >\n");
return (1);
}
if (n == 1) /* trivial case: */
{
fprintf(stdout, "1 = 1\n");
return (0);
}
u = n; /* (u) = working value for (n) */
for (; (u & 0x1) == 0; u >>= 1) /* while (u) even: */
prime[np++] = (2);
while (u > 1)
{
unsigned long q, d = 3, c = 0; /* (c)omposite */
if (np != 0) /* start at previous odd (prime) factor: */
d = (prime[np - 1] == 2) ? (3) : prime[np - 1];
for (; (c == 0) && (q = u / d) >= d; )
{
if ((c = (q * d == u)) == 0) /* not a factor: */
d += 2;
}
prime[np++] = (d = (c == 0) ? u : d);
u /= d; /* if (u) is prime, ((u /= d) == 1) (done) */
}
for (int i = 0; i < np; i++)
{
const char *fmt = (i < np - 1) ? ("%lu x ") : ("%lu = ");
fprintf(stdout, fmt, prime[i]);
}
fprintf(stdout, "%lu\n", n);
return (0);
}
/******************************************************************************/
I'm trying to make a program that accepts 4 numbers, regardless if it is a whole or non-whole number. It will determine the largest non-whole number found in the inputs. If there are no non-whole numbers present, then it will print a message that there are none.
Here is my code:
#include <stdio.h>
int main()
{
float num1, num2, num3, num4;
//Enter Numbers
printf("Enter 4 Numbers : ");
scanf("%f %f %f %f", &num1, &num2, &num3, &num4);
//Numbers are Integer
if ((num1 - (int) num1) == 0
&& (num2 - (int) num2) == 0
&& (num3 - (int) num3) == 0
&& (num4 - (int) num4) == 0) {
printf("Output : No Non-Whole Numbers found\n");
} else {
//Numbers are Float
if (num1 > num2 && num1 > num3 && num1 > num4) {
printf("Output : %.1f\n", num1);
} else if (num2 > num1 && num2 > num3 && num2 > num4) {
printf("Output : %.1f\n", num2);
} else if (num3 > num1 && num3 > num2 && num3 > num4) {
printf("Output : %.1f\n", num3);
} else {
printf("Output : %.1f\n", num4);
}
}
}
But I have some problems with it, for example when a user inputs:
Enter 4 Numbers : 12.5 15 2 1
Output: 15
Instead it should be 12.5
Enter 4 Numbers : 10.5 10.5 7 8
Output: 8.0
Instead it should be 10.5
As Nils Martel pointed out this should be coded as a loop over an array.
The only difference from his implementation is that I think mine is easier to understand, because it's closer to the original code
#include <stdio.h>
#include <stdlib.h>
#define FALSE (0 != 0)
#define TRUE (!FALSE)
#define ABS(x) ((x >= 0) ? (x) : (-x))
#define NUMS 4
int is_whole(float num)
{
return (ABS(num) - (int)ABS(num)) == 0;
}
int main()
{
float nums[NUMS];
int contains_float = FALSE;
int largest = 0; // Initialized with the first element
//Enter Numbers
printf("Enter 4 Numbers : ");
scanf("%f %f %f %f", &nums[0], &nums[1], &nums[2], &nums[3]);
//Numbers are Integer
for (int i = 0; i < NUMS; ++i) {
if (is_whole(nums[i]) == FALSE) {
contains_float = TRUE;
// The additional condition here accounts for the case when
// nums[0] is the largest element in the array
if (nums[i] > nums[largest] || is_whole(nums[largest]))
largest = i;
}
}
if (contains_float)
printf("Output : %.1f\n", nums[largest]);
else
printf("Output : No Non-Whole Numbers found\n");
}
You can run it here https://onlinegdb.com/rkVwPZaZu
I think the best check for determining, if a number is non while would be
floor(n) != n
Now, In your code you repeat yourself quite often and your logic gets quite complex and hard to understand by just looking at it.
You might find this exercise a great moment, to learn more about arrays and loops!
I've tried to rewrite your code using the floor(n) != n check, and by using arrays and loops. Mind, my C is a little rusty, but I hope you can reason with my code:
#include <stdio.h>
#include <math.h>
void print_largest_non_while(float *numbers, int length) {
int is_set = 0;
float greatest;
for (int i = 0; i < length; i++) {
float n = numbers[i];
if (floor(n) != n) {
// n is a non while number
if (!is_set) {
is_set = 1;
greatest = n;
continue;
}
if (greatest < n) greatest = n;
}
}
if (is_set) printf("%f\n", greatest);
}
int main() {
float num[4];
// Enter Numbers
printf("Enter 4 Numbers : ");
scanf("%f %f %f %f", num, num + 1, num + 2, num + 3);
print_largest_non_while(num, 4);
}
Your test consider that all your numbers are not integers, or that they are all integers. Also consider that the test num1 - (int)num1) == 0 could give false results. Better: compare the abs of the difference to a threshold.
#define N 4
#include <stdio.h>
#include <math.h>
int main(){
float num[N];
//Enter Numbers
printf("Enter %d Numbers : ", N);
for (int i = 0; i < N; ++i) {
int t = scanf ("%f", &num[i]);
if (t != 1) return 1;
}
float eps = 1.0e-5;
int found = 0;
float vmax;
for (int i = 0; i < N; ++i) {
int check = fabs(num[i] - rint(num[i])) > eps;
found += check;
if (check) {
if (found == 1) {
vmax = num[i];
} else {
if (num[i] > vmax) {
vmax = num[i];
}
}
}
}
//Numbers are all Integer if found == 0
if(found == 0) {
printf("Output : No Non-Whole Numbers found\n");
} else {
printf("Output : %.1f\n", vmax);
}
return 0;
}
This code when run in the CS50 Web IDE has expected results of running Luhn's Algorithm then correctly printing out the type of credit card used.
#include <stdio.h>
#include <string.h>
int main(void){
long ccNumber;
do{
printf("Insert CC Number: \n");
scanf("%ld", &ccNumber);
} while (ccNumber <= 0);
long ccCopy = ccNumber;
int sum;
int count = 0;
long divisor = 10;
char result[16];
while(ccCopy > 0){
int lastDigit = ccCopy % 10;
sum = sum + lastDigit;
ccCopy = ccCopy / 100;
printf("%i\n", sum);
}
ccCopy = ccNumber / 10;
while(ccCopy > 0){
int lastDigit = ccCopy % 10;
int timesTwo = lastDigit * 2;
sum = sum + (timesTwo % 10) + (timesTwo / 10);
ccCopy = ccCopy / 100;
}
ccCopy = ccNumber;
while(ccCopy != 0){
ccCopy = ccCopy / 10;
count++;
}
for(int i = 0; i < count - 2; i++){
divisor = divisor * 10;
}
int firstDigit = ccNumber / divisor;
int firstTwo = ccNumber / (divisor / 10);
if(sum % 10 == 0){
if(firstDigit == 4 && (count == 13 || count == 16)){
strcpy(result, "VISA");
} else if((firstTwo == 34 || firstTwo == 37) && count == 15){
strcpy(result, "AMEX");
} else if((firstTwo > 50 || firstTwo < 56) && count == 16){
strcpy(result, "MASTERCARD");
} else {
strcpy(result, "INVALID");
}
}
else {
strcpy(result, "INVALID lol");
}
printf("%i\n", sum);
printf("%s\n", result);
}
The issue is, when copy and pasted into VSCode the Sum is not calculated the same
These are the results from CS50 IDE:
Insert CC Number:
4012888888881881,
1,
9,
17,
25,
33,
41,
43,
43,
90,
VISA
And these are the results from VSCode with the exact same code copy and pasted:
Insert CC Number:
4012888888881881,
15774464,
15774472,
15774480,
15774488,
15774496,
15774504,
15774506,
15774506,
15774553,
INVALID lol
The original code did not have the printf showing sum in the first while loop I added it to debug the results.
This has left me very confused, considering the code is copy and pasted.
sum is not initialized to 0, so you are having undefined behaviour. Then you get different results depending on compiler, platform, weather....
You need to initialize all variables. int sum can be anything.
Initialize sum to 0.
int sum = 0;
I tried to printf all the narcissistic numbers of the number of digits entered by the user.
For example for input 3 the program should print: 153, 370, 371, 407. Now for some reason instead of printing the numbers it prints nothing and the program is stuck.
#include <stdio.h>
#include <math.h>
int main() {
int digit, a, c = 0;
unsigned long long int count, b, sum;
printf("Enter digits to check narcisistic: ");
scanf("%d", &digit);
count = pow(10, digit - 1);
if (digit > 2) {
while (count < pow(10, digit)) {
b = count;
sum = 0;
while (count >= 1) {
a = b % 10;
b /= 10;
sum += pow(a, digit);
}
if (sum == count) {
printf("\n Narcissistic found:\t%llu", count);
c++;
}
count++;
}
if (c == 0)
printf("No Narcissistic number for this digit.");
}
return 0;
}
What is the problem of this code?
while(count>=1){
a=b%10;
b/=10;
sum+=pow(a,digit);
}
count never changes in this loop, so it will loop forever.
As per #dcp's answer.
The inner while loop will never exit. What you are supposed to be looping over is the number of digits. For instance (after declaring digNum as an int earlier):
for(digNum = digit; digNum > 0; digNum--)
{
a = b%10;
b /= 10;
sum+=pow(a,digit);
}
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int funkcija(int num, int num2)
{
int doesContain;
if (doesContain == 1)
return 1;
else
return 0;
}
int main(void)
{
int num, num2;
scanf("%d", num);
scanf("%d", num2);
printf("%d", funkcija(num, num2));
return 0;
}
So basically, I need to make a function which takes number 1 and number 2, checks if number2 is in number1, then returns 0 or 1.
So for example, if number 1 is let's say '2452325678', and number 2 is '7', number 1 DOES contain number 2 and the statement is true. But if num1 is '2134' and num2 is '5', the statement is false.
It needs to be done PRIMITIVELY, without arrays and whatnot.
I need any help I can get with the algorithm.
int numsub(int haystack, int needle)
{
for (; haystack; haystack /= 10)
if (haystack % 10 == needle)
return 1;
return 0;
}
fairly simple, works by keeping dividing the number by 10 and each time
checking if currentNumber % 10 == the digit checked.
that's all.
example:
int i;
int num;
int flag;
int digit;
flag = 1;
num = 1234;
digit = 2;
while(num != 0 && flag)
{
if(num % 10 == digit)
{
flag = 0;
}
else
{
num = num / 10;
}
}
if(flag == 1)
{
//flag stays set,which means that digit is not inside num
}
else
{
//flag is not set, which means that digit is indeed a part of num.
}