Table in reverse order - c++

I was doing basic programming to print the n's table in reverse order where n is a positive integer.
Here is my approach:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int n;
cin >> n;
int multiplier = 10;
while (multiplier--)
{
n = n*multiplier;
cout << n << endl;
}
}
But its output is not what I expected. May I know where is the problem lying in this code? Also, please do provide me some advice as after 2 months I am having MS intern interview.
My input was
2
Output came out to be
18
144
1008
6048
30240
120960
362880
725760
725760
0

I guess you probably don't want to change n every iteration, so I suggest you assign the calculation to another (scoped) variable:
int main()
{
int n;
cin >> n;
int multiplier = 10;
while (multiplier--)
{
int nn = n*multiplier;
cout << nn << endl;
}
}
Another thing: you might want to actually see the 10*n printed first (and not the "0" at the end), so you could also multiply n by multiplier+1 (or do a do-while loop instead).

Related

The "sticks" variable cannot be re-assigned to 0 in C++14

I am writing a program to resolve the request:
Count the number of match sticks used to create numbers in each test case
Although it is a simple problem, the thing that makes me quite confusing is that the program has no error but the output is not as expected.
Source Code:
#include <bits/stdc++.h>
using namespace std;
int main() {
map<char,int> digits={
{'0',6},{'1',2},{'2',5},{'3',5},{'4',4},{'5',5},{'6',6},{'7',3},{'8',7},{'9',6}
};
map<char,int> peterMap;
int t; cin >> t;
string peterNum[t];
for(string &a:peterNum) cin >> a;
for(string b:peterNum){
int sticks = 0;
string tomNum, n;
for(char c:b) ++peterMap[c];
for(auto d:peterMap) sticks += d.second*digits[d.first];
cout << sticks << ' ';
}
return 0;
}
Input:
5 (Number of test cases)
1 0 5 10 15
Output:
2 8 13 21 28
Expected Output:
2 6 5 8 7
There are 3 problems with your code
don't use <bits/stdc++.h>, it is non-standard and promotes bad practice.
variable-length arrays are not standard C++, use std::vector instead. But this is actually not necessary in this case, because...
peterMap is completely unnecessary and needs to be removed, it is screwing up your result.
Try this instead:
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<char,int> digits = {
{'0',6},{'1',2},{'2',5},{'3',5},{'4',4},{'5',5},{'6',6},{'7',3},{'8',7},{'9',6}
};
int t; cin >> t;
for (int i = 0; i < t; ++i) {
string a; cin >> a;
int sticks = 0;
for(char ch : a) sticks += digits[ch];
cout << sticks << ' ';
}
return 0;
}
Online Demo
Problem is here:
for(char c:b) ++peterMap[c]; // <<--here
for(auto d:peterMap) sticks += d.second*digits[d.first];
You are increasing number in map and use it in next statement without reseting for next input entry.
But there are several problems with your code:
Don't use #include <bits/stdc++.h>. I hate hackerrank for using this in their solution template.
Using string peterNum[t]; is not standard as mentioned in comments.
From my point of view, you don't need to use std::map for peterMap at least. Just iterate over characters of each string.

Im trying to create a a code that count numbers divisible by 9 by putting numbers into an array and count the numbers in it [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 last year.
Improve this question
Im trying to create a a code that count numbers divisible by 9 by putting numbers into an array and count the numbers in it but it only prints 1 instead of the number of numbers divisible by 9 please help me i want to use array to count those numbers
#include <iostream>
using namespace std;
int main(){
int a,b,i;
int numbers[]={i};
cin >>a>>b;
for (i=a; i<=b; i++)
if (i%9==0){
cout << sizeof(numbers)/sizeof(numbers[0]);
}
}
Nowhere in your code are you adding numbers to the array. Anyhow, it is not possible to add elements to arrays, because they are of fixed size. Your array has a single element.
Moreover, int numbers[]={i}; is undefined, because i has not been initialized.
Further, it is not clear what is the purpose of sizeof(numbers)/sizeof(numbers[0]) in your code. sizeof(numbers) is the size of a single int because the array has a single element. sizeof(numbers[0]) is the size of a single int as well. Hence the result is 1 always. (Its a compile time constant btw.)
If you want to count how many numbers fullfil some condition you best use a counter and print its value after the loop:
#include <iostream>
int main(){
int a,b;
cin >> a >> b;
unsigned counter = 0;
for (int i=a; i<=b; i++) {
if (i%9==0){
++counter;
}
}
std::cout << counter;
}
i want to use array for my learning porpuses please help me
You chose the wrong example to train working with arrays, because as already mentioned, arrays have fixed size. It is an opportunity to learn about std::vector. You can add elements to a std::vector at runtime and query its size:
#include <iostream>
#include <vector>
int main(){
int a,b;
std::vector<int> by9divisables;
std::cin >> a >> b;
for (int i=a; i<=b; i++) {
if (i%9==0) {
by9divisables.push_back(i);
}
}
std::cout << by9divisables.size();
}
However, other than to see how std::vector is working, the vector has no place in this code. As you can see above, the result can be obtained without it.
This declaration
int numbers[]={i};
declares an array with only one element and initializes it with an indeterminate value stored in the variable i because the variable i was not initialized.
The body of this if statement
if (i%9==0){
cout << sizeof(numbers)/sizeof(numbers[0]);
}
does not make a sense because it always outputs the number of elements in the array numbers that has only one element. But according to the description of the assignment you have to place numbers divisible by 9 into the array.
As the user can enter arbitrary values for the variables a and b then it means that you need a variable length array. However variable length arrays is not a standard C++ feature. Instead you should use the standard container std::vector.
The program can look the following way
#include <iostream>
#include <vector>
#include <utility>
int main()
{
int a = 0, b = 0;
std::vector<int> numbers;
const int divisor = 9;
std::cout << "Enter two integer numbers: ";
std::cin >> a >> b;
if ( b < a ) std::swap( a, b );
for ( int i = a; not ( b < i ); ++i )
{
if ( i % divisor == 0 ) numbers.push_back( i );
}
std::cout << "There are " << numbers.size()
<< " numbers divisible by " << divisor
<< " in the range [" << a << ", " << b << "]\n";
if ( numbers.size() != 0 )
{
std::cout << "They are ";
for ( const auto &n : numbers )
{
std::cout << n << ' ';
}
std::cout << '\n';
}
}
Your code is printing one's for each element found because your array only has one element in it!
Print i instead like so:
#include <iostream>
using namespace std;
int main(){
int a,b,i;
//int numbers[]={i};
cin >>a>>b;
for (i=a; i<=b; i++)
{
if (i%9==0)
{
cout << "i: " << i << endl;
}
}
}

How to find the greatest number among the numbers given input?

I'm a beginner in programming and as you can see, I created a program where the user is asked to input three numbers. It will display the greatest among the numbers given. But after I finished the code, a question came into my mind, what if the user was asked to input a hundreds of numbers and should display the greatest among the numbers given. So the question is, is it possible to do that? what are the things I need to learn to produce that result? is there any hints you can give me?
#include <iostream>
#include <string>
using std::cout, std::cin, std::endl, std::string;
int main() {
string result = " is the greatest among the numbers given";
double x, y, z;
cout<<"Enter three numbers to decide which is the largest: "<<endl;
cin >>x;
cin >>y;
cin >>z;
system("clear");
if(x>y && x>z){
cout<< x << result;
} else if (y>z && y>x){
cout << y << result;
} else
cout<< z << result;
return 0;
}
With the program below, you can get as many numbers as you want from the user and find the largest of them.
#include <iostream>
int main()
{
int size=0, largestValue=0, value=0;
std::cout << "Enter total numbers you want to add :" << "\n";
std::cin >> size;
for (int i{ 0 }; i < size; ++i)
{
std::cout << "Enter value to add : ";
std::cin >> value;
if (i == 0 || value > largestValue)
{
largestValue = value;
}
}
std::cout << "Largest value = " << largestValue << "\n";
return 0;
}
One solution would be to store your inputs in a list and sort them afterwards. Just google "sorting alorithms". Also there are nice youtube visualizations.
Another one would be to not save the inputs into dedicated variables - in your case x, y, z - but to always save the largest given input:
int largestInput = std::numeric_limits<int>::min();
int input;
for (int i = 0; i < 10000; i++)
{
std::cin >> input;
largestInput = input > largestInput ? input : largestInput;
}
If you know the inputs are large, you can use vectors.
#include <bits/stdc++.h>
using namespace std;
int main(){
int total_num=0;
cout << "Enter total numbers:" << "\n";
cin>>total_num;
int max_number = INT_MIN;
vector<int> v;
for(int i=0;i<total_num;i++){
int x;
cin>>x;
v.push_back(x);
max_number = max(max_number,x);
}
cout<<"Maximum number present: "<< max_number<<endl;
return 0;
}
Although there is no need to store numbers. But it's your choice if you need it later you can use it in that program.
> what are the things I need to learn
what if the user was asked to input a hundreds of numbers
For this, you'll need to learn about arrays. I suggest you first learn about C-style arrays (int x[3]{};), and then std::array (std::array<int, 3> x{};). You also need to learn about loops.
and should display the greatest among the numbers given
Having to find the largest number in an array is very common. If you want to learn how to do so manually, the other answers here should answer your question. Otherwise, look towards the standard library algorithms std::ranges::max() (C++20) and std::max_element.
Examples
Example 1
Here's a program that uses a C-style array and a simple algorithm to get the largest number:
#include <iostream>
int main(){
// Amount of numbers user should input
constexpr int count{ 3 };
std::cout << "Enter " << count
<< " numbers to decide which is the largest:\n";
// The numbers entered by the user
double numbers[count]{}; // Declare and zero-initialize a C-style array of 3 ints
// Get each number from the user and put it in the array
for (int i{ 0 }; i < count; ++i) {
std::cin >> numbers[i];
}
// The biggest number found so far
int max{ numbers[0] }; // Initialize it with the first number
for (int i{ 1 }; i < count; ++i) { // Start at the second element (element 1)
if (numbers[i] > max) { // If the current number is larger than max...
max = numbers[i]; // ...assign it to max
}
}
std::cout << max << " is the greatest among the numbers given\n";
return 0;
}
Note:
int numbers[count]{};
This creates a C-style array called numbers which has count (3) elements. The first element's "index" is 0 and the last element's is 2. The {} initializes the values of all of the numbers to 0 (good practice).
for (int i{ 0 }; i < count; ++i)
std::cin >> numbers[i];
This loops until i isn't less than count (3) and increments i (++i) each time. It starts at 0, so it loops 3 (0 1 2) times. On each iteration, it gets a number from the console and stores it in numbers[i].
Example 2
Here's a shorter program that uses the standard library:
#include <algorithm> // ranges::max()
#include <array> // array<>
#include <iostream> // cin, cout
int main() {
// Amount of numbers user should input
constexpr int count{ 3 };
std::cout << "Enter "
<< count
<< " numbers to decide which is the largest:\n";
std::array<double, count> numbers{}; // Declare an array of 3 ints
for (int i{ 0 }; i < count; ++i) {
std::cin >> numbers[i];
}
// Return the largest number in array "numbers"
std::cout << std::ranges::max(numbers)
<< " is the greatest among the numbers given\n";
return 0;
}
Note:
std::array<int, count> numbers{};
Declares an array of count (3) ints and zero-initializes it.
std::ranges::max(numbers)
This neat function finds the largest number in numbers. It was added in C++20 -- if you're using an older compiler, you should use *std::max_element(numbers.begin(), numbers.end()). If you want to learn how the latter works, you need to learn about iterators and pointers.
Here are some good practices that your tutorial hasn't taught you yet (if it ever will):
DON'T use using namespace std. It's unsafe because it brings everything in the standard library into global scope. The standard library contains a lot of commonly used identifiers like count and list. Bringing these into global scope is dangerous because it can cause naming conflicts.
Don't use copy initialization (int x = 3). Use uniform/brace/list initialization instead (int x{ 3 }). The former sometimes makes an unnecessary copy, whereas the latter doesn't. The latter also refuses to do narrowing conversions (e.g. initializing a short with a long).
Always initialize variables (do: int x{}, don't: int x), even when it seems redundant. If you don't, then the value stored is undefined - it could be anything. Undefined behaviour is hard to debug but luckily easy to avoid.
Use \n instead of std::endl. Both do the same, except std::endl does an extra buffer flush which is slow and unnecessary. \n is shorter anyways.
DRY -- Don't Repeat Yourself. You have the string " is the greatest among the numbers given" three times in your code. You could have stored it in a std::string instead -- then it wouldn't have repeated.
Repeating code is bad, because:
It's harder to read
It's harder to maintain (you would have to modify it everywhere it's repeated)
Maintenance is more error-prone
If I were you, I'd immediately find a different tutorial/book. See this thread.
#include <stdio.h>
int main()
{
int num1, num2, num3, num4;
printf("Enter num1\n");
scanf("%d",&num1);
printf("Enter num2\n");
scanf("%d",&num2);
printf("Enter num3\n");
scanf("%d",&num3);
printf("Enter num4\n");
scanf("%d",&num4);
if(num1>num2 && num1>num3 && num1>num4){
printf("greatest number is %d",num1);
}
if(num2>num3 && num2>num1 && num2>num4){
printf("greatest number is %d",num2);
}
if(num3>num1 && num3>num2 && num3>num4){
printf("greatest number is %d",num3);
}
if(num4>num1 && num4>num2 && num4>num3){
printf("greatest number is %d",num4);
}
return 0;
}

The input is a three-digit number. Print the arithmetic mean of its digits

I have a homework assignment. The input is a three-digit number. Print the arithmetic mean of its digits. I am new to C++ and cannot write the code so that it takes 1 number as input to a string. I succeed, only in a column.
#include <iostream>
int main()
{
int a,b,c;
std::cin >> a >> b >> c;
std::cout << (a+b+c)/3. << std::endl;
return 0;
}
If you write it in Python it looks like this. But I don't know how to write the same thing in C ++ :(
number = int(input())
digital3 = number % 10
digital2 = (number//10)%10
digital1 = number//100
summ = (digital1+digital2+digital3)/3
print(summ)
The most direct translation from Python differs mostly in punctuation and the addition of types:
#include <iostream>
int main()
{
int number;
std::cin >> number;
int digital3 = number % 10;
int digital2 = (number/10)%10;
int digital1 = number/100;
int summ = (digital1+digital2+digital3)/3;
std::cout << summ << std::endl;
}
In your code, you use three different numbers and take the mean of their sum (not the sum of three-digits number). The right way is:
#include <iostream>
int main()
{
int a;
std::cin >> a;
std::cout << ((a/100) + ((a/10)%10) + (a%10))/3.<< std::endl;
return 0;
}
EDIT: This answer is incorrect. I thought the goal was to average three numbers. Not three DIGITS. Bad reading on my part
*Old answer *
I'm not sure I'm interpreting the question correctly. I ran your code
and confirmed it does what I expected it to...
Are you receiving three digit chars (0-9) and finding the average of
them? If so, I'd trying using a
for loop using getChar()
Here is a range of functions that may be of use to you.
Regex strip
Convert string to int: int myInt = stoi(myStr.c_str())
Convert int to string: std::string myStr = myInt.to_string()
If you need to improve your printing format
Using printf
If using cout, you can kindve hack your way through it!
The input is a three-digit number.
If it means, you'll be given a number that will always have 3 digits, then you can try the following approach.
Separate each digit
Find all digits sum
Divide the sum by 3
If you're given the number as a string, all you've to do is convert that string into int. Rest of the approach is the same as abve.
Sample code:
int main()
{
int a;
std::cin >> a;
int sum = (a % 10); // adding 3rd digit
a /= 10;
sum += (a % 10); // adding 2nd digit
a /= 10;
sum += (a % 10); // adding 1st digit
std::cout << (double)sum / 3.0 << std::endl;
return 0;
}
Here's a possible solution using std::string:
EDIT added digits check
#include <iostream>
#include <string>
#include <cctype>
int main()
{
std::string s;
std::cin >> s;
if(s.length() == 3 && isdigit(s[0]) && isdigit(s[1]) && isdigit(s[2]))
{
std::cout<<double(s[0] + s[1] + s[2])/3 - '0'<<std::endl;
}
else
{
std::cout<<"Wrong input"<<std::endl;
}
return 0;
}

Not getting correct output Function not working

I'm trying to write a code that will take a number that the user inputted and create an inverted triangle like:
8 6 4 2 0 on the first line,
6 4 2 0 on the second line,
4 2 0 on the third line,
2 0 on the fourth line,
0 on the last line.
My nested for loops worked in a previous code that was in the main not in a function, but I decided I wanted to create a function that when called would run through the loops. However, something in my code isn't right since now I don't get an inverted triangle. I just get 0 and I think that's because my return is 0. I'm not sure if I'm writing my function incorrectly or if it's something else.
Please help. Thank you
#include <iostream>
using namespace std;
int row(int num)
{
int number;
int decreasedNumber;
for(int i = number; i >= 0; i -= 2)
{
decreasedNumber = i;
for(int j = decreasedNumber; decreasedNumber >= 0; decreasedNumber -=2)
{
cout << decreasedNumber << " ";
}
cout << endl;
}
return 0;
}
int main()
{
int number;
//Prompting the user to enter a number and collect that input
cout << "Enter a number: " << endl;
cin >> number;
cout << row(number);
return 0;
}
You are accepting num as a parameter to row, but never using it. Also, you are using number, but never initializing it. Instead, it seems you want number to be the parameter to the function, instead of a local variable.
Here's a demo.
Also, the variable j is never used in the loop, so you should just remove it.
Also, please don't use using namespace std;, it's a bad habit that you should avoid.
You are using number as the initial value of i.
number is uninitialized and its value is indeterminate.
Instead of number, you should use the argument num as the initial value of i.