Integer and Loop Help

Im a new programming student and this question has got me dumbfouded:

"Write a program which will calculate, for every integer that is being input, a code in the following way:

first digit multiplied by 3
plus
second digit multiplied with the third digit
minus
fourth digit

You assume that the given integers will all consist of four digits
eg 3124 would equal 7 : 3*3+1*2-4"

How do you do this calulation without entering each digit seperately?
Given that you know all integers are 4 digits you can use integer division and subtraction to calcualte the 4 digits.

So Number / 1000 = Thousands
(Number-Thousdands) / 100 = hundreds
etc.

Hi Faldrax
I tried coding it. Can you maybe code it so that I can see.
Hi Faldrax
Never mind, I got it right eventually. C++ want you to think in chronological manner and visualise what you want to do as well as a lot of practice.
Thanx Man
Here is the answer:

#include <iostream>
using namespace std;

int main ( )
{
int number,dig1,dig2,dig3,dig4,second,third,fourth;
cout << "Enter a 4 digit number " ;
cin >> number;
// Obtain FIRST Digit
dig1 = number / 1000;
// Obtain SECOND digit
second = (number-dig1) / 100;
dig2 = second % 10;
// Obtain THIRD Digit
third = number / 10;
dig3 = third % 10;
// Obtain FOURTH Digit
fourth = number / 1;
dig4 = fourth % 10;

// The answer for the equation: (first digit multiplied by 3), plus (second digit multiplied by third didit) minus fourth digit
cout << (dig1 * 3) + (dig2 * dig3) - dig4 << endl;
return 0;
}
In the problem, it does say that it has to be a 4 digits number. I guess that is the pain in the ass.
I tried the following codes. It works but I am not sure it is good or not.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 
#include <iostream>
using namespace std;


int main()
{
	int i=0;
	char digits[4];
	
	cout << "please input the number:";
	     while(i<4){
	                 cin >> digits[i];
	                 i++;
	                }
	
    cout << (digits[0]-48)*3+(digits[1]-48)*(digits[2]-48)-(digits[3]-48);
	return 0;
}



Last edited on
You can save yourself a bit of work:
1
2
3
4
5
6
7
8
cout << "please input the number:";
while (i < 4)
  {
    cin >> digits[i];
    digits[i] -= 48;
    i++;
  }
cout << digits[0] * 3 + digits[1] * digits[2] - digits[3];


Edit: You could even use a for loop instead of the while loop (and eliminate your need to have 'i' declared outside of the loop) -
1
2
3
4
5
for (int i = 0; i < 4; i++)
  {
    cin >> digits[i];
    digits[i] -= 48;
  }
Last edited on
Topic archived. No new replies allowed.