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;
}
Related
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;
}
}
}
The idea of my program was to print individual digits of n.
But instead it prints all the digits at once in the first line and a bunch of zeroes or garbage values in subsequent lines.
I want to access each individual number as we can do with arrays.
Suppose the input is 1234, why doesn't it print 1\n2\n3\n4?
#include <iostream>
#include <cmath>
#include <stdlib.h>
using namespace std;
int main()
{
int* n=(int*)malloc(1000*sizeof(int));
cin>>*n;
int len;
len = log10(*n) + 1;
for(int i=0;i<len;i++)
{
cout<<n[i]<<endl;
}
}
n is declared as a pointer to a memory location which can store 1000 integer entities. When you use cin>>*n;, an integer value is read as input and store at the first memory block among the 1000 blocks. The individual digits of the integer are not stored in separate blocks, hence you can't print them separately.
For example, if the input is 123,
n[0] stores 123, n[1],n[2],...n[999] stores junk values.
To store a value in n[1], you will have to use cin again.
For some reason you think that
int* n=(int*)malloc(1000*sizeof(int));
cin>>*n;
will read a number and put each digit in a different element of the dynamic array n. If that happened then the rest of your code would work (kind of). But of course it doesn't. Instead the number read is put into *n (or, same thing, n[0]) and the rest of the dynamic array elements are uninitialised, which explains the garbage values you see.
I'm struggling to understand why you thought your code might behave in the way you wanted. I guess you are just an optimistic person and think that if you wish hard enough the compiler will understand. This seems to be quite a common attitude among beginners. Unfortunately programming isn't like that.
When you cin >> *n, you don't read the number digit by digit, but read in as a whole.
So when you cin >> *n and type in 1234, *n becomes 1234.
If you want to print all the individual digits, like 1\n2\n3\n4, you need to separate the digits for yourself:
int pos = 1;
while (*n != 0)
{
n[pos] = n % 10;
n /= 10;
++pos;
}
for (--pos; pos > 0; --pos)
{
cout << n[pos] << endl;
}
However, the easiest approach is to read in the number as a string, not a number, then print out the characters, that is the digits, one by one.
char str[1000];
cin >> str;
for (char *s = str; *s; ++s)
{
cout << *s << endl;
}
You can also convert the number into a string, and do the same:
#include <cstring>
using namespace std;
...
char str[1000];
sprintf(str, "%d", *n);
for (char *s = str; *s; ++s)
{
cout << *s << endl;
}
------- Original Answer:
If you want to print the first element of n:
cout << *n;
or
cout << n[0];
Your code
for(int i=0;i<len;i++)
{
cout<<n[i]<<endl;
}
means
cout << n[0] << endl;
cout << n[1] << endl;
cout << n[2] << endl;
...
cout << n[len-1] << endl;
I have following piece of code,
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int input,n;
cin >> n;
vector<int> v(n);
for(int i=0;i<n;i++){
cin>>input;
v.push_back(input);
}
for(int i=0; i<v.size();i++){
cout << v[i] << endl;
}
cout << v.size() << endl;
return 0;
}
and
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int input,n;
vector<int> v(n);
cin >> n;
for(int i=0;i<n;i++){
cin>>input;
v.push_back(input);
}
for(int i=0; i<v.size();i++){
cout << v[i] << endl;
}
cout << v.size() << endl;
return 0;
}
for the following input, n=5, 1 2 3 4 5 , first program gives the output
0
0
0
0
0
1
2
3
4
5
10
and the second program gives the result
1
2
3
4
5
5
I donot understand why vector is initializing 0's in the first doubling the size but not in the second
Actually, neither of those are correct for what you want (I'm assuming here you want the five elements you input and nothing more - that may be an invalid assumption but it seems like a good bet to me).
In your first one, you have (comments added to explain what's happening):
int input,n; // n has arbitrary value.
cin >> n; // overwritten with 5.
vector<int> v(n); // initial vector has five zeros.
This means your vector will be created with five (assuming you input that for n) default-constructed entries. Then you go and insert five more, which is why you get five zeros followed by your actual data.
Your second one has:
int input,n; // n has arbitrary value.
vector<int> v(n); // initial vector of that arbitrary value (probably).
cin >> n; // overwritten with five but it's too late anyway.
This is actually undefined behaviour since you have no idea what n will be when you create a vector of that size. In your case, it appears to be zero but that's just a lucky coincidence.
Note the use of the word "probably" above. While it's likely that the vector will be created with some arbitrary number of entries, undefined behaviour means exactly that - you should not rely on it at all. By rights, it could quite easily delete all your files while playing derisive_laughter.wav through your sound system :-)
The most likely case however will be one of:
it'll work as you thought, because n is zero;
it'll have some arbitrary number of zeros at the start, similar to your first code snippet;
it'll cause an out-of-memory exception because n is ridiculously large; or
it'll cause an exception because n is negative.
In any case, you should generally either pre-allocate and just set the already-existing values:
vector<int> v(2);
v[0] = 7;
v[1] = 42;
or not pre-allocate, using push_back to expand the vector on demand:
vector<int> v;
v.push_back(7);
v.push_back(42);
Hope, one can write the 1st case of writing program in the question in the following way to get correct result
1
2
3
4
5
5
for the input given as in the question
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n;
cin>>n;
vector<int> v(n);
for(int i=0;i<n;i++){
cin>>v.at(i);
}
for(int i=0;i<v.size();i++){
cout << v[i] << endl;
}
cout << v.size() << endl;
return 0;
}
I'm trying to convert a for loop to while loop in c++ and do some checking for duplicates in a random number generator for generating lotto numbers so far all the stuff i'm trying seems to make the compiler very unhappy and I could really use a few pointers. It's the for loop in the Harray() function that feeds the Balls[] array
that i want to convert to a while loop.
#include<iostream>
#include<cstdlib> // to call rand and srand.
#include<ctime> // to make rand a bit more random with srand(time(0)) as first call.
#include<iomanip> // to manipulate the output with leading 0 where neccesary.
using namespace std;
// Hrand() function create and return a random number.
int Hrand()
{
int num = rand()%45+1; // make and store a random number change 45 for more or less Balls.
return num; // return the random number.
}
// Harray() function create and fill an array with random numbers and some formatting.
void Harray()
{
int Balls[6]; // change the number in Balls[6] and in the for loop for more or less nrs. a row.
for(int x=0; x<=6; x++) //the loop to fill array with random numbers.
{
int a; // made to pass the Balls[x] data into so i can format output.
int m = Hrand(); // calling the Hrand() function and passing it's value in int m.
Balls[x] = m; // throwing it into the array tought i did this because of an error.
a = Balls[x]; // throwing it into int a because of an type error.
cout<<"["<<setfill('0')<<setw(02)<<a<<"]"; //format output with leading 0 if neccesary.
}
cout<<endl; // start new row on new line.
}
// Main function do the thing if compiler swallows the junk.
int main() // start the program.
{
int h; // int to store user cchoice.
srand(time(0)); // make rand more random.
cout<<"How many rows do you want to generate?"<<endl; // ask how many rows?
cin>>h; // store user input.
for(int i=h; h>0; h--) // produce rows from user input choice.
{
Harray(); // calling Harray function into action.
}
return 0; // return zero keep the comipler happy.
}
I would like to always have six diffrent numbers in a row but i don't see how to get there with the for loops i think the while loop is way to go but am open to any suggestion that will work. I'm just starting with c++ i might have overlooked some options.
int x=0;
while(x<6)
{
int a;format output.
int m = Hrand();value in int m.
Balls[x] = m; because of an error.
a = Balls[x];
cout<<"["<<setfill('0')<<setw(02)<<a<<"]";
x++;
}
Here, I also fixed a bug. Since Balls has 6 elements, the last element will be 5. Thus you want x<6 instead of x<=6. That goes for the for loop too.
One drawback of while loops is that you cannot declare local variables with them.
First of all, you should realize that the difference between a for loop and a while loop is mostly syntactic--anything you can do with one, you can also do with the other.
In this case, given what you've stated as your desired output, what you probably really want is something like this:
std::vector<int> numbers;
std::set<int> dupe_tracker;
while (dupe_tracker.size() < 6) {
int i = Hrand();
if (dupe_tracker.insert(i).second)
numbers.push_back(i);
}
The basic idea here is that dupe_tracker keeps a copy of each number you've generated. So, you generate a number, and insert it into the set. That will fail (and return false in retval.second) if the number is already in the set. So, we only add the number to the result vector if it was not already in the set (i.e., if it's unique).
How convert for-loop to while-loop
#include <iostream>
class T545_t
{
// private data attributes
int j;
public:
int exec()
{
// A for-loop has 3 parameters, authors often fill 2 of them with magic
// numbers. (magic numbers are usually discouraged, but are expected
// in for-loops)
// Here, I create names for these 3 for-loop parameters
const int StartNum = 2;
const int EndNum = 7;
const int StrideNum = 2;
std::cout << std::endl << " ";
for (int i = StartNum; i < EndNum; i += StrideNum ) {
std::cout << i << " " << std::flush;
}
std::cout << std::flush;
// A while-loop must use / provide each of these 3 items also, but
// because of the increased code-layout flexibility (compared to
// for-loop), the use of magic numbers should be discouraged.
std::cout << std::endl << " ";
j = StartNum;
do {
if (j >= EndNum) break;
std::cout << j << " " << std::flush;
j += StrideNum;
} while(true);
std::cout << std::flush;
std::cout << std::endl << " ";
j = StartNum;
while(true) {
if (j >= EndNum) break;
std::cout << j << " " << std::flush;
j += StrideNum;
}
std::cout << std::flush;
std::cout << std::endl << " ";
j = StartNum;
while(j < EndNum) {
std::cout << j << " " << std::flush;
j += StrideNum;
}
std::cout << std::endl;
return 0;
}
}; // class T545_t
int main(int , char** )
{
T545_t t545;
return(t545.exec());
}
Ask me where 'j' is declared?
This code is marked as C++, so in this case, I have declared 'j' in the private data attribute 'section' of this class definition. That is where you'd look for it, right?
If your c++ code does not have class, what's the point?
My goal is to try and create a program that takes in grades in percents and multiply it with their weight value (either in decimal form or percent form). The equation is basically:
Overall grade = (grade1*weightInDecimal1)+(grade2*weightInDecimal2)+(grade3*weightInDecimal3)+...
or
Overall grade = (grade1*weight%1)+(grade2*weight%2)+(grade3*weight%3)+...
Is there a way to store the inputs and then recall it later in the code? Or possibly a more efficient way?
I also want to try and make a dynamic array. I want to make a program that asks the user for how many assignments they have and makes an array based on that. That way it's not stuck at 4 assignments
#include <string>
#include <iostream>
using namespace std;
int main() {
int numbers[4][2];
for(int i=0;i<4;i++)
{
cout<<"Grade #"<<i<<endl;
cin>>numbers[i][0];
cout<<"Weight for grade #"<<i<<":"<<endl;
cin>>numbers[i][1];
}
for (int i = 0; i<4; i++)
{
cout << "|" << numbers[i][0]*numbers[i][1]<< "|";
}
system ("PAUSE");
return 0;
}
This is what structs are for
#include <string>
#include <iostream>
#include <array>
using namespace std;
struct entry {
int grade;
int weight;
int gradeWeight; //grade*weight
};
int main() {
array<entry,4> numbers;
for(int i=0;i<numbers.max_size();i++)
{
cout<<"Grade #"<<i<<endl;
cin>>numbers[i].grade;
cout<<"Weight for grade #"<<i<<":"<<endl;
cin>>numbers[i].weight;
}
for (int i = 0; i<numbers.max_size(); i++)
{
numbers[i].gradeWeight = numbers[i].grade*numbers[i].weight;
cout << "|" << numbers[i].gradeWeight << "|";
}
system ("PAUSE");
return 0;
}
This way you can also increase the amount of numbers by just increasing the array size.
As pointed by others, if you ask the user for how many assignments they have, std::array is a wrong container because it's dimension is fixed at compile time.
As others, I discurage the use of direct memory allocation but the use of std::vector to manage it.
I just suggest the use of reserve() (method of std::vector), when you know how many assignments.
The following is a full example using, instead a couple of std::vector of int, a single std::vector of std::pair<int, int>
#include <utility>
#include <vector>
#include <iostream>
int main()
{
int valG, valW;
std::size_t dim;
std::vector<std::pair<int, int>> vec;
std::cout << "How many grade/weight couples? ";
std::cin >> dim;
vec.reserve(dim);
for ( auto i = 0U ; i < dim ; ++i )
{
std::cout << "Grade #" << i << "? " << std::endl;
std::cin >> valG;
std::cout << "Weight for grade #" << i << "? " << std::endl;
std::cin >> valW;
vec.emplace_back(valG, valW);
}
for ( auto const & p : vec )
std::cout << '|' << (p.first * p.second) << '|';
std::cout << std::endl;
return 0;
}
There are many reasons to avoid using arrays (dynamic or otherwise). See for example Stroustrup's FAQ entry What's wrong with arrays? As Greg suggests in the comments you will most likely write better quality code if you use a container like std::vector.
If you can calculate or input the size of your container before allocating it you can (if you wish) pass that size to the constructor ...
auto syze{ 0 };
auto initialValue{ 0 };
// calculate or input syze
. . .
// dynamically allocate an "array"
// of ints and an "array" of floats
std::vector<int> grades(syze, initialValue);
std::vector<float> weights(syze, initialValue);
On the other hand if you prefer to use a container that dynamically grows to hold data as it arrives you can do that too...
// dynamically allocate an empty "array"
// of ints and an empty "array" of floats
std::vector<int> grades;
std::vector<float> weights;
while (...condition...)
{
std::cin >> g; // input a grade ...
std::cin >> w; // ... and a weight
// grow the containers by adding
// one item at the end of each
grades.emplace_back(g);
weights.emplace_back(w);
}
Update
I should have pointed out how to calculate the result from the two vectors. You can calculate your overall grade with just one more line of code by using std::inner_product from the STL's <numeric> header. Note that in the code below the last argument is 0.0 (rather than just 0) so that std::inner_product returns a double rather than an int. That avoids any risk of float values being truncated to int (and avoids some pretty ugly warnings from the compiler).
auto overallGrade = std::inner_product(grades.begin(), grades.end(), weights.begin(), 0.0);