PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, May 9, 2022

[FIXED] How do i write a program that calculates the product of a number's digits that are different from another number i input?

 May 09, 2022     c++, digits, product     No comments   

Issue

I have to input 2 numbers, n and k, and find the product of n's digits which are different from k. Example: n = 1234, k=2, and the product should be 1 * 3 * 4;

    #include <iostream>

using namespace std;

int main()
{
    int n, k, p=1, digit;
    cin >> n >> k;

    while(true){
            digit= n % 10;

        if(digit != k){
            p = p * digit;
        }
        n = n/10;
    }
    cout << "Product of digits different from K is: " << p;
    return 0;
}

When i run it, after i input n and k, the program doesnt do anything else and just keeps the console open without an output.


Solution

The problem is the while(true). In this way the program stay in the loop for eternal. A possible solution can be this:

int main()
{
    int n, k, p=1, digit;
    cin >> n >> k;

    while( n > 0 ){
            digit= n % 10;

        if(digit != k){
            p = p * digit;
        }
        n = n/10;
    }
    cout << "Product of digits different from K is: " << p;
    return 0;
}


Answered By - Zig Razor
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing