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.
Related
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;
}
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).
So I have made a program that inputs a number and then reverses it. E.g. input: 987 should return 789 but currently it keeps returning 32767.
I'm not sure why, I don't want to change my function but howcome it keeps returning the wrong value. The code inside my function reverseDigit() works, but when I try to use it as a function it doesn't work. Any ideas.
#include <iostream>
int reverseDigit(int number) {
int reverse = 0;
for( ; number!= 0 ; )
{
reverse = reverse * 10;
reverse = reverse + number%10;
number = number/10;
}
}
using namespace std;
int main() {
int numberInput;
cout<<"Input a Number\n";
cin>> numberInput; // Taking Input Number in variable number
cout << numberInput << " reversed is: " << reverseDigit(numberInput) << endl;
}
You aren't returning anything from your function.
This should have generated a compiler warning. If not you may want to increase the warning level.
Add return reverse; to the end of it.
With no return it's anybody's guess what you'll get when you print it.
It seems like I always come here to ask silly questions, but here it goes. As of right now I am in my first compsci course and we are learning c++. I've had an extremely basic introduction to c before, so I had thought I'd go above and beyond my current assignment. Now I was doing this just to showboat, I felt like if I didn't practice my previous concepts they would eventually fade. Anyways, on to the problem! I was supposed to write some code that allowed the user to input their initials, and a series of exams. Now this was supposed to accomplish three things: average the exams, print out the entered exams, and print out their initials. Well, what was a simple assignment, got turned into a huge mess by yours truly.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
string uInitials;
float avgExam = 0, tExam = 0;
int aExams[10] = {'0'};
int i, nExam = 0, cExam;
cout << "Enter your three initials!";
cin >> uInitials;
do
{
cout << "Enter your exam(s) to be averaged. Enter 0 when complete!\n";
cin >> cExam;
aExams[nExam] = cExam; //I used this before nExam was incremented, in order to get nExam while it was '0' That way the first exam score would be properly saved in the first space
nExam++;
tExam += cExam; //This is just to add all the exams up to later calculate the average
}
while(cExam != 0);
avgExam = tExam/(nExam - 1); //subtracted '1' from nExams to remove the sentinel value from calculations.
cout << "The average for initials: " << uInitials << " is: " << avgExam << endl;
cout << "This average was obtained using the following scores that were entered: \n";
for(i = 0; i < (nExam+1); i++)
{
cout << aExams[i] << endl; //Used a for loop to prevent redundancy
}
return 0;
}
The previous is my code, and the problem is that I'm getting output errors where it adds two '0's when I print out the list of entered exams. Also I feel like I made the whole do{}while() loop one huge clunky mess, so I'd like to refine that as well. If anyone could assist this poor, ignorant, beginner I would greatly appreciate it. Thank you for your time!
Some advice that i can give is for example in the 5th line there is no need
to put the 0 between ' ' and not even need to use the assign = operator.
You can initialize the array like this:
int aExams[10]{0};
Which will initialize all elements to 0,but can't be used for other value.
For example you won't have all the elements with value 1 if you write
int aExams[10]{1};
If your intention to initialize all elements in an array is with value other than 0 you can use fill_n(); function.
fill_n(aExams, 10, 1);
The first argument is the name of the array, the second is up-to which element you want to be initialized with the third argument, and the third is the value you want all elements to have.
Do not leave uninitialized variables like in line 6 with cExam and i variables. Initialize it like cExam=0; (copy-assign initialization) or cExam(0); (direct initialization). The latter calls the constructor for int built-in type.
A negative i see in your do-while loop is that you do not make sure that the user will enter under 10 exams,bad things will happen if the user tries to input 15 exams in an array that can hold only 10.
Just change the while to something more like this:
while( cExam != 0 && (nExam<10) );
You can also write the first two lines of the do-while loop outside the loop.
It is needed only once to tell the user that to stop the loop he/she needs to enter 0. There is no need to tell them this on every iteration plus that you will have a good performance benefit if you put those two lines outside the loop.
Look here how i would write the code and ask if you have any questions.
http://pastebin.com/3BFzrk5C
The problem where it prints out two 0's at the end of your code is a result of the way you wrote your for loop.
Instead of:
for(i = 0; i < (nExam+1); i++)
{
cout << aExams[i] << endl; //Used a for loop to prevent redundancy
}
Use:
for (i = 1; i < (nExam); i++)
{
cout << aExams[i - 1] << endl; //Used a for loop to prevent redundancy
}
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <fstream>
using namespace std;
void make_array(ifstream &num, int (&array)[50]);
int main(){
ifstream file; // variable controlling the file
char filename[100]; /// to handle calling the file name;
int array[50];
cout << "Please enter the name of the file you wish to process:";
cin >> filename;
cout << "\n";
file.open(filename);
if(file.fail()){
cout << "The file failed to open.\n";
exit(1);
}
else{
cout << "File Opened Successfully.\n";
}
make_array(file, array);
file.close();
return(0);
}
void make_array(ifstream &num, int (&array)[50]){
int i = 0; // counter variable
while(!num.eof() && i < 50){
num >> array[i];
i = i + 1;
}
for(i; i>=0; i--){
cout << array[i] << "\n";
}
}
Alright, so this it my code so far. When I output the contents of the array, I get two really large negative numbers before the expected output. For example, if the file had 1 2 3 4 in it, my program is outputting -6438230 -293948 1 2 3 4.
Can somebody please tell me why I am getting these ridiculous values?
Your code outputs the array backwards, and also it increments i twice after it has finished reading all the values. This is why you see two garbage values at the start. I suspect you are misreporting your output and you actually saw -6438230 -293948 4 3 2 1.
You end up with the extra increments because your use of eof() is wrong. This is an amazingly common error for some reason. See here for further info. Write your loop like this instead:
while ( i < 50 && num >> array[i] )
++i;
Now i holds the number of valid items in the list. Assuming you do actually want to output them backwards:
while ( i-- > 0 )
cout << array[i] << "\n";
To output them forwards you'll need two variables (one to store the total number of items in the array, and one to do the iteration)
The check !num.eof() only tells you that the last thing you read was not eof. So, if your file was 1 2 3 4, the check will only kick in after the 5th num>>array[i] call. However, for that i, array[i] will be populated with a meaningless value. The only correct way to deal with eofs is to check for validity on every call to operator>>. In other words, the right condition is simply num>>array[i]. This works by exploiting this conversion to bool since C++11 and to void* pre-C++11.