In: Computer Science
Can someone convert this to C++ Please!
import java.util.*; // for Random
import java.util.Scanner; // for Scanner
class game{
public static void main(String args[])
{
// generating a random number
Random rand = new Random();
int code = rand.nextInt(99999) + 1,
chances = 1, help, turn, i,match, sum;
// for input
Scanner sc = new
Scanner(System.in);
// running for 10 times
while(chances < 11)
{
System.out.print("\nYour chance number "+chances+" : ");
// taking user
input
turn =
sc.nextInt();
// if the code
matches, comes out of loop
if(turn ==
code)
break;
// code didn't
match
else
{
help = code;
match = 0;
sum = 0;
// looping 5 times to check each digit
for(i=0;i<5;i++)
{
// Checking from last digit
to first digit. So dividing by 10 each time.
// if digit is matched,
adding it to sum and incrementing match variable by 1
if(help%10 == turn%10)
{
match++;
sum+=help%10;
}
help = help/10;
turn = turn/10;
}
// printing sum and match to guide player
System.out.printf("\nNumber of digits matched:
%d\nSum of them : %d\n", match, sum);
}
chances++;
}
// printing relavant message
if(chances == 11)
{
System.out.println("\nYou lost! Code is "+code);
}
else
System.out.println("\nCongratulations, you won!");
}
}
#include <iostream> #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { // generating a random number srand(time(NULL)); int code = rand() % 99999 + 1, chances = 1, help, turn, i, match, sum; // running for 10 times while (chances < 11) { cout << "\nYour chance number " << chances << " : "; // taking user input cin >> turn; // if the code matches, comes out of loop if (turn == code) break; // code didn't match else { help = code; match = 0; sum = 0; // looping 5 times to check each digit for (i = 0; i < 5; i++) { // Checking from last digit to first digit. So dividing by 10 each time. // if digit is matched, adding it to sum and incrementing match variable by 1 if (help % 10 == turn % 10) { match++; sum += help % 10; } help = help / 10; turn = turn / 10; } // printing sum and match to guide player cout << "\nNumber of digits matched: " << match << "\nSum of them : " << sum << "\n"; } chances++; } // printing relavant message if (chances == 11) { cout << "\nYou lost! Code is " << code << endl; } else cout << "\nCongratulations, you won!" << endl; }