Simple calculator C++ loop [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
The community reviewed whether to reopen this question 4 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I am a student in my first year.
Could someone help me with an assignment?
Simple calc C++
In the first line the number of tests n. In the next n lines operations Each operation contains the operation type (+ *) the number of k numbers to be processed, and k numbers
Output
Result
Example
Input
3
+ 3 3.1 5.2 -8.3
* 2 1 3.3
+ 1 3
Output
0
3.3
3
My code
int n, k;
char x;
cin >> n;
int tab[100];
for (int i = 0; i < n; i++)
{
cin >> x >> k;
for (int j = 0; j < k; j++)
{
cin >> tab[j];
if (x == '+')
{
tab[j] += tab[j + 1];
}
if (x == '*')
{
tab[j] *= tab[j + 1];
}
cout << tab[j];
}
}
return 0;
}

There are a few problems.
your tab is of type int so it can only store integers e.g.: 1,2,3,4,5 not floating point numbers like 1.3 2.5 3.3, you should consider changing tab to be of type float.
your loop logic and indexing is totally wrong, and you are accessing the wrong elements, you should have some sort of accumulator variable that will accumulate the results instead of storing them in an array. e.g.:
float accumulator = 0;
cin >> input_number;
accumulator += input_number;`
the best advice i can give you is to learn to use the debugger, the debugger is your friend, you should use it to walk through your code, line by line and understand what each lines does to each variable, and read the contents of each variable, i cannot recommend a certain source for learning to use a debugger as it depends on your IDE, but you should maybe check a video on using debugger with IDE X, it can be a good start for learning to use an IDE GUI.

The issues are many. Just some:
The purpose of tab is unclear. You do not need to store the operands, you can accumulate a result in a single value.
In any event tab[j + 1]; is not initialised at point of use.
If you want to output the results after all the input as indicated in the question then you do need somewhere to store the results for later output.
You do need to output the results.
The input and output types do need to be a floating-point type.
Greater clarity of thought might arise if you were to use clear variable names that reflected their purpose and perhaps some comments. If you have to explain what the code does (even to yourself) often you spot the errors. A good technique is to write the comments first, to explain what you need to code rather than explaining the code you have written and assume erroneously to be correct. Also you need to get out of that "all variables at the top" habit.
Example:
#include <iostream>
int main()
{
// Get number of calculations
int ncalc = 0 ;
std::cin >> ncalc ;
// Create array for results
double* result = new double[ncalc] ;
// For each calculation
for( int calc = 0; calc < ncalc; calc++ )
{
// Get the operator
char op = 0 ;
std::cin >> op ;
// Get the number of operands
int noperands = 0 ;
std::cin >> noperands ;
// Get initial operand in accumulator
double accumulator = 0 ;
std::cin >> accumulator ;
// For each remaining operand...
for( int i = 1; i < noperands; i++)
{
// Get the operand
double operand = 0 ;
std::cin >> operand ;
// Perform the operation
switch( op )
{
// For +, accumulate sum
case '+' : accumulator += operand ; break ;
// For * accumulate product
case '*' : accumulator *= operand ; break ;
}
}
// Store accumulated result
result[calc] = accumulator ;
}
// Output results
for( int calc = 0; calc < ncalc; calc++ )
{
std::cout << result[calc] << '\n' ;
}
delete[] result ;
return 0;
}

Related

Convert number in binary and print out as matrix (C++)

Before you read ahead or try to help, this question is regarding my homework so the requirements to this question will be very specific.
I am writing a code that takes a user input between 0 and 511 and converts it into a binary number. Then the program will replace all the 1's in the binary number with T and all the 0's in the number as H. Afterwards it will print out the results (the binary number with the H and T replacement) as a 3*3 matrix.
This is the desired output (not what I have but what I want):
Enter a number between 0 and 511: 299
The binary number is: 100101011
The matrix is:
THH
THT
HTT
The problem with my code is that I am unsure of how to replace an array that consists of all integers to have certain parts of the index to be either characters or strings. For sure the part with the binary number conversion works but the replacement of the 0's and 1's of the array is where the trouble is at. I am also unsure of how to print out the matrix result. I assume it goes either of 2 ways: 1. The program creates a new array for the previous array's elements stored and prints out the matrix array instead. 2. There is a way to only print the array 3 lines at a time. The only way I can think of is to somehow cut the for loop short and add a line break after every 3 values. I am aware that there are a few pointable errors in my code but I do not know how to fix them.
Although this is in the C++ language, what I have learned is the C style syntax (no std:: kinds of code or stuff like that because I haven't learned it yet and I will not understand it) So far I have learned basic arrays, loops, and functions.
#include <iostream>
using namespace std;
int main(){
int arr[10];
int input, i;
cout<<"Enter a number between 0 and 511: ";
cin>> input;
for(i = 0; input > 0; i++){
arr[i] = (input % 2);
input = input / 2;
}
cout<<"The binary number is: ";
for(i = i - 1; i >= 0; i--){
cout<<arr[i];
}
string newArr[10] = arr[10]; //the error here states that the array initializer must be an initializer list
for(int i = 0; i < sizeof(arr)/sizeof(arr[10]); i++){
if(arr[i] == 1){
arr[i] = "T"; //the error here mentions that a string/ character cannot be assigned with a integer array
}
else{
arr[i] = "H";
}
}
for(int i = 0; i < sizeof(arr)/sizeof(arr[10]); i++){
cout<<arr[i]<< " ";
}
}
This would be sufficient:
#include <iostream>
using namespace std;
int main()
{
// you never actually checked if the input is valid
// so you may or may not want this loop:
int input;
do
{
cout << "Enter a number between 0 and 511: ";
cin >> input;
} while ((input < 0) || (input > 511));
// space for matrix, new lines and null
// to construct a null terminated string
char buffer[3 * (3 + 1) + 1];
int i = 0;
// since the bits are read from left to right
// I will use a mask instead of bit shifting the input
int bit = 1 << 9;// 2^9 == 512
for (int r = 0; r < 3; r++)// rows
{
for (int c = 0; c < 3; c++)// columns
{
// this could come after the check
// and then bit would start at 256
bit >>= 1;
// perform the check and add the corresponding letter
buffer[i++] = (bit & input) ? 'T' : 'H';
}
// add new lines
buffer[i++] = '\n';
}
// if you don't want the last '\n'
// this could be { buffer[--i] = '\0'; }
buffer[i++] = '\0';
cout << buffer;
}

Input and Output in program [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I have a problem with Input and Output in my program.
I can’t make sure that the BFS response for each horse is separated and at the end the BFS response of all horses of a given number of examples is summarized.
Everything works well for this example:
1- number of examples
1 - the number of chess knights
5 5 - the starting point
5 6 - the final point
answer: 3
but not this example:
1- number of examples
2 - the number of chess knights
0 0 - the starting point of the first knight
1 0 - the starting point of the second knight
0 1 - the final point of the first knight
1 1 - the final point of the second knight
I need the answer(BFS) for the first horse and for the second horse to be summed up (for first = 2, for second = 2, for all horses = 4). But if you check this example using my code (below) then the answer is 3, the program considers only the first horse.
Here is my code:
int main()
{
int number_of_examples;
cin >> number_of_examples; //number of examples
for (int i = 1; i <= number_of_examples; i++) {
int number_of_horse;
cin >> number_of_horse; //number of horse
vector<Node> src;
vector<Node> dest;
int x, y;
for (int i = 1; i <= number_of_horse; i++)
cin >> x >> y;
src.push_back(Node(x, y));
for (int i = 1; i <= number_of_horse; i++)
cin >> x >> y;
dest.push_back(Node(x, y));
for (int i = 0; i < src.size(); i++)
{
for (int j = 0; j < dest.size(); j++)
{
cout << BFS(src[i], dest[j]);
}
}
}
return 0;
}
the program considers only the first horse
As you told it to do...
for (int i = 1; i <= number_of_horse; i++)
cin >> x >> y;
src.push_back(Node(x, y));
Only the first line following the for is repeated. If you want (I wager you do) repeat multiple statement, you need to enclose them in a block:
for (int i = 1; i <= number_of_horse; i++) {
cin >> x >> y;
src.push_back(Node(x, y));
}
You might want to read a bit more about the for syntax.

C++ program doesn't fully execute iteration [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
The program I've written is supposed to take in two user inputs (one being the number we're meant to check whether it's k-hyperperfect or not, the other being a maximum k-value.) if the input integer is k-hyperperfect in the range of 1 to the inputted maximum k-value, then the output should be that k-value. For example, if the input integer is 21 and the maximum k-value is 100 then the output should be 2.
My program gives the correct output for (the first number is the input integer, the second number is the k-max value, the third number is output value) ...
21 (input integer) 100 (k-max) --> 180
301 100 --> 6
12211188308281 100 --> 0
-301 100 --> 0
21 -5 --> 0
However, it doesn't correctly execute for 12211188308281 and 200 (it gives me 0 when it should give me 180). I've run my code through a step by step visualizer and it seems to just abruptly stop execution when i = 496 in the for loop within the else statement. But I don't understand why since it executes correctly for 5 other test runs.
#include <iostream>
using std::cout; using std::cin; using std::endl; using std::fixed;
int main () {
int number;
int kmax;
int sum = 0 ;
int hyper = 0;
std::cin >> number;
std::cin >> kmax;
if (number <= 6 or kmax < 1) {
std::cout << "0" << "\n";
}
else {
for (int i=1;i<=number;i++) {
if (number%i==0 and i != 1 and i != number){
sum+= i;
}
}
}
for (int k=1; k <= kmax; k++) {
hyper = ((sum)*k) + 1;
if (hyper == number) {
std::cout << k << endl;
break;
}
}
}
You need to check that numbers read through std::istreams (like std::cin) are read successfully. As the value that you enter for number is too large to store in an integer your read will fail. For example you could change your code to:
int main()
{
int number;
std::cin >> number;
if ( !std::cin )
{
std::cout << "invalid value: " << number << "\n";
return 1;
}
else
{
std::cout << "valid value: " << number << "\n";
}
// calculate answer
return 0;
}
You would then see your program printing "invalid value: 2147483647" if you have a c++11 compliant compiler or an undefined number if you have an older compiler.
Now that you have implemented reading values correctly the fix to your issue is to use a larger integer type like int64_t which is able to hold your number.
As already noted, the int type in your machine isn't big enough to store the value 12,211,188,308,281.
The C++ standard only mandates it to be capable of storing a value up to 32,767 and even in the (now common) case of a 32-bit int or long int), the limit would be 2,147,483,647. So you need a long long int or an int64_t (if it's present in your implementation).
A simple check like
if (std::cin >> number >> kmax ) { // perform calculations...
Would have shown the error sooner.
That beeing said, there are also some simple changes that could be done to the posted code in order to make it more efficient. The first loop can be optimized considering the "symmetry" of the divisors of a given number: meaning, if n is divisible by a, so that b = n/a is a whole number, b too is a divisor of n. This will limit the number of iterations to the square root of n, instead of n.
long long int number,
kmax,
sum = 0;
// ...
long long int temp = number,
i = 2;
for (; i * i < number; i++) {
if (number % i == 0) {
temp = number / i;
sum += i + temp;
}
}
if (i * i == number) {
sum += i;
}
There probably are better algorithms, but I'm unfamiliar with those.
The second loop, in my opinion, is unnecessary. The value k can be calculated directly:
if ( (number - 1) % sum == 0) {
std::cout << (number - 1) / sum << '\n';
}
You are assigning a too long value 12211188308281 to integer "number", which can't contain it fully and it is getting truncated to 596285753. You can add a print statement to print it.
std::cout<<number;
which will print 596285753.
As suggested you should use long long int. Again its dependent on the software platform running on your system.

C++ Matrix values of

I want to create a matrix of 5 lines and 5 columns which contains values from 1 to 9. The following programs displays numbers from 1 to 25 instead, when I input 5 to the program..
#include <iostream>
using namespace std;
int a[20][20], n, x = 0;
int main()
{
cout << "n=";
cin >> n;
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
{
a[i][j] = x+1;
x = x+1;
}
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
cout << a[i][j] << " ";
cout << endl;
}
}
I'm a c++ beginner, so maybe it's simple to do but i don't know how to make it show values from 1 to 9. This is the matrix I except:
1 2 3 4 5
6 7 8 9 1
2 3 4 5 6
7 8 9 1 2
3 4 5 6 7
There are some issues in your code.
C arrays or STL containers?
First off, a your matrix may only hold matrices as big as 20x20. Your program will silently fail if you enter n bigger than 20, because you will access memory out of bounds; which causes an undefined behavior (see other common UB cases here).
You may want to use a dynamic size array - A good way to achieve this is to use std::vector. Unfortunately, this isn't as comfortable to use as a C-style array with two dimensions - you can achieve the same access syntax using a std::vector<std::vector<int>>, but this is not very efficient (see this answer if you are interested why) nor quite comfortable.
The Boost C++ library provides a multidimensional array library. Once you get experienced enough, you may find an use in it.
<= or <? 0-index or 1-indexed?
Many programming languages today uses 0-indexing for arrays. This means the first element of the array is located at index 0, not 1. Some languages, such as Lua, doesn't do this.
This means you should iterate i and j from 0 to n. This also means n is excluded, so you should use <, not <=.
Filling the matrix with numbers from 1 to 9
Your code doesn't do anything so you get numbers from 1 to 9 - it only fills the matrix with numbers from 1 to n * n. You could change this using an if clause to set x every time it goes above 9:
if (x > 9) { x = 0; } // x = 0 because it will be 1 on the next iteration
That being said, there is more convenient, as #PMar's answer says. The modulo operator % will do the task as well.
a[i][j] = (x % 9) + 1;
x = (x % 9) + 1;
This way, you will get every number from 1 to 9.
Now, you can also do another cleanup: Why are you calculating x's next value, and only then setting it? You could assign the new x value before the assignment to your matrix's cell. This allows having clearer code, with less copy pasting, which implies better maintainability.
x = (x % 9) + 1;
a[i][j] = x;
Another code quality consideration
I cannot say if your original code source was indented like your question (before it was edited), but you should really indent your code, for the future you and other people that will have to read your code. It allows for much better readability.
Same goes for different parts of your code : Add some space! It only can get more readable if you make a clear distinction between even just expressions.
You need to use the modulus operator (%). If you want the values in the matrix to be as you have computed them, but only need to change the display, you would output the matrix values as follows:
cout << (a[i][j] % 10) << " ";
If you want the one-digit values to be in the matrix itself, you would instead change the increment on 'x' to the following:
x = (x+1) % 10;}
#include <iostream>
int main()
{
int a[5][5];
int x = 1;
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 5; j++)
{
if(x > 9)
x = 1;
a[i][j] = x;
x++;
}
}
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 5; j++)
{
if(a[i][j] < 10)
std::cout << " ";
std::cout << a[i][j] << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
return 0;
}

Split Binary number into Digits [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
In case of normal integer, we use %10 for the remainder, and /10 to reduce the digit by one digit.
For a Binary Digit, I could use %2 to get the remainder, but how do I remove digits from the Binary number?
If there's a number 0000, when I perform /10, I need 000 and not 0.
while (bin > 0) {
int rem = bin % 2;
// action_block;
// How do I divide ?
}
Clearing the confusion, this is for a problem of a competitive coding site. The stdin will be an integer, which has a binary data. Example: 1100001. I want its bits in an array. arr[0] = 1, arr[1] = 1, arr[2] = 0, arr[3]=0 and so on..
Quite logically, use /2. It's the same with any base.
Right shift (>>) operator is used to shift the bits to right by position specified in the expression.
For example :
unsigned int num1 = 12; // 12 = 1100
int num2 = 0;
num2 = num1 >> 1; // 6 = 0110
int num3 = 0;
num3 = num1 >> 2; // 3 = 0011
Now, try achieving your goal using this.
Edit :
As problem described by OP in comment section of this answer.
std::string inp;
std:: cin >> inp.
for (int i = 0; i < inp.length(); i++) {
std::stoi(inp[i]); // This will be 0,1.
}
If you want to use an array then this is what you are looking for :
#include <iostream>
#include <string>
using namespace std;
int main()
{
string input="0101011010";
int arr[10];
for(int i=0; i<10; i++)
{
arr[i]=input[i]-'0';
}
for(int i=0; i<10; i++)
{
cout << arr[i] << endl;
}
}