i am currently having problem getting largest values from an array, here is my code:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a[10],max=0,j,secondbig=0;
for(int i=0;i<10;i++)
{
cin>>a[i];
}
max = a[0];
for(int i=0;i<10;i++)
{
if(a[i]>max){
max=a[i];
j=i;
}
}
secondbig=a[10-j-1];
for(int i=0;i<10;i++)
{
if(secondbig <a[i] && j != i)
secondbig =a[i];
}
cout<<max<<"\n"<<secondbig;
return 0;
}
What i want to do is to first get maximum value from an array and then leave one array value and then get second largest value and same for third largest value, for example :
200
100
50
300
400
500
600
700
800
900
If in the above test values 900 is the largest value then the subsequent second and third largest value should be 700 and 500, is there anyway to do that?
maybe you can sort the array
int *pbeg = begin(a);
int *pend = end(a);
sort(pbeg, pend);
this will sort all elements in the range[pbeg, pend) with operator <,
or sort all elements by using the binary predicate
Given your original code, I presume this is in the style of what you were attempting. it will retrun the three highest vaule. Notice that you only needed to create a loop to repeat the inital computation. You want the max remaining value less than the prior max value.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <limits>
using namespace std;
int main()
{
int a[10], max, prior_max = numeric_limits<int>::max();
for(int i=0;i<10;i++)
{
cin>>a[i];
}
for( int j = 0; j<3; j++){
max = numeric_limits<int>::min();
for(int i=0;i<10;i++)
{
if(a[i]>max && a[i]<prior_max){
max=a[i];
}
}
cout << max << endl;
prior_max = max;
}
return 0;
}
Assuming that you're happy to get the values in place, I'd use a vector.
std::sort(std::begin(a), std::end(a), std::greater<int>());
then print or copy the first n elements of the array (assuming n is no more than your array size, 10). They will be in reverse order, but that can be easily corrected.
As per your follow on question, If you want to list all the max values, change the j<3 to j<10. If you want the numeric sum of the max values that you have extracted from the array, you need to add one more variable:
int a[10], total, max, prior_max = numeric_limits<int>::max();
then within the outer loop, place at the end of the inner loop this statement:
total += max;
Then after the execution of the loops are complete, you can print out the total or otherwise use it. as in:
cout << 'Total: ' << total << endl;
Related
I'm new to c++ but long story short , i want to write a c++ program that will accept input from user through an array and it will sum each array element input
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
int main() {
int array[100];
int sum;
for(int i=0; i<100; i++){
cout<<"Insert element "<<i<<": ";
cin>>array[i];
sum = array[i]+ //summ with the next array input;
cout<<sum;
}
return 0;
}
means that if i enter any integer the program should be able to give the summation of the inputs in sequence from the first input to the last input
C++ standard library already has a function to do this which is std::accumulate:
#include <iostream>
#include <numeric>
int main() {
int array[5] = {1,2,3,4,5};
int total = std::accumulate(std::begin(array), std::end(array), 0);
return 0;
}
If you plan to use not a full array you should use std::begin(array), std::begin(array) + amount as ranges.
initialize your sum var to 0 initially and write sum+=array[i] instead of what you have written, there is also a limitation in this program as value of sum after all user input should be <=10^9 as int datatype store no. approximately upto 10^9 so take note of this fact also. Write cout<<sum<<endl; instead to be able to distinguish till previous input sum to the new input sum.
Hope this will help.
You can use a do while loop:
#include<iostream>
#include<string>
#include<math.h>
int main()
{
int array[100];
int sum=0;
int i=0;
std::cout<<"Insert element"<<" "<<i<<": ";
std::cin>>array[i];
do
{
sum=sum+array[i];
std::cout<<sum<<std::endl;
i++;
std::cout<<"Insert element"<<" "<<i<<": ";
}while(std::cin>>array[i]);
return 0;
}
If all you want is the sum then just compute the sum. No need to store anything:
#include <iostream>
#include <string>
#include <math.h>
int main() {
int sum = 0;
for(int i=0; i<100; i++){
std::cout << "Insert element " << i << ": ";
int t;
std::cin >> t;
sum += t
std::cout << sum;
}
}
I've written some code in c++ that is meant to find the minimum and maximum values that can be calculated by summing 4 of the 5 integers presented in an array. My thinking was that I could add up all elements of the array and loop through subtracting each of the elements to figure out which subtraction would lead to the smallest and largest totals. I know this isn't the smartest way to do it, but I'm just curious why this brute force method isn't working when I code it. Any feedback would be very much appreciated.
#include <iostream>
#include <vector>
#include <limits.h>
using namespace std;
void minimaxsum(vector<int> arr){
int i,j,temp;
int n=sizeof(arr);
int sum=0;
int low=INT_MAX;
int high=0;
for (j=0;j<n;j++){
for (i=0;i<n;i++){
sum+=arr[i];
}
temp=sum-arr[j];
if(temp<low){
low=temp;
}
else if(temp>high){
high=temp;
}
}
cout<<low;
cout<<high<<endl;
}
int main (){
vector<int> arr;
arr.push_back(1.0);
arr.push_back(2.0);
arr.push_back(3.0);
arr.push_back(1.0);
arr.push_back(2.0);
minimaxsum(arr);
return 0;
}
There are 2 problems.
Your code is unfortunately buggy and cannot deliver the correct result.
The solution approach, the design is wrong
I will show you what is wrong and how it could be refactored.
But first and most important: Before you start coding, you need to think. At least 1 day. After that, take a piece of paper and sketch your solution idea. Refactor this idea several times, which will take a complete additional day.
Then, start to write your code. This will take 3 minutes and if you do it with high quality, then it takes 10 minutes.
Let us look first at you code. I will add comments in the source code to indicate some of the problems. Please see:
#include <iostream>
#include <vector>
#include <limits.h> // Do not use .h include files from C-language. Use limits
using namespace std; // Never open the complete std-namepsace. Use fully qualified names
void minimaxsum(vector<int> arr) { // Pass per reference and not per value to avoid copies
int i, j, temp; // Always define variables when you need them, not before. Always initialize
int n = sizeof(arr); // This will not work. You mean "arr.size();"
int sum = 0;
int low = INT_MAX; // Use numeric_limits from C++
int high = 0; // Initialize with MIN value. Otherwise it will fail for negative integers
for (j = 0; j < n; j++) { // It is not understandable, why you use a nested loop, using the same parameters
for (i = 0; i < n; i++) { // Outside sum should be calculated only once
sum += arr[i]; // You will sum up always. Sum is never reset
}
temp = sum - arr[j];
if (temp < low) {
low = temp;
}
else if (temp > high) {
high = temp;
}
}
cout << low; // You miss a '\n' at the end
cout << high << endl; // endl is not necessary for cout. '\n' is sufficent
}
int main() {
vector<int> arr; // use an initializer list
arr.push_back(1.0); // Do not push back doubles into an integer vector
arr.push_back(2.0);
arr.push_back(3.0);
arr.push_back(1.0);
arr.push_back(2.0);
minimaxsum(arr);
return 0;
}
Basically your idea to subtract only one value from the overall sum is correct. But there is not need to calculate the overall sum all the time.
Refactoring your code to a working, but still not an optimal C++ solution could look like:
#include <iostream>
#include <vector>
#include <limits>
// Function to show the min and max sum from 4 out of 5 values
void minimaxsum(std::vector<int>& arr) {
// Initialize the resulting values in a way, the the first comparison will always be true
int low = std::numeric_limits<int>::max();
int high = std::numeric_limits<int>::min();;
// Calculate the sum of all 5 values
int sumOf5 = 0;
for (const int i : arr)
sumOf5 += i;
// Now subtract one value from the sum of 5
for (const int i : arr) {
if (sumOf5 - i < low) // Check for new min
low = sumOf5 - i;
if (sumOf5 - i > high) // Check for new max
high = sumOf5 - i;
}
std::cout << "Min: " << low << "\tMax: " << high << '\n';
}
int main() {
std::vector<int> arr{ 1,2,3,1,2 }; // The test Data
minimaxsum(arr); // Show min and max result
}
The problem is to take 3 inputs:
1) No. of test cases
2) No. of digits in a number
3) N space separated digit numbers
And to output :
1) No. of sets
2) No. of combinations in each set
I want to print those outputs but No of combination output is returning zero on each and every set
I've already tried troubleshooting and debugging the problem, but none of those worked....
/* Read input from STDIN. Print your output to STDOUT*/
#include<iostream>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
using namespace std;
int factorial (int count);
int main(int argc, char *a[])
{
//intialize variables
int i,T,b,S[i],N,NN[i],C[i],count=0;
cin >> T;
while(T>0) {
cin >> N;
for(i=0;i<N;i++) {
cin >> NN[i];
if(i<N-1) {
S[i] = (N-i);// S[i] is Category 02
count++;
}//end of if
}//end of for loop
for(int j=0;j<N;j++) {
C[i] = factorial(count)/(factorial(i)*factorial(count - i));//
}//end of for loop
cout <<"No. of sets =" <<count++<<endl;
for(int k=0;k<N;k++) {
cout<<"No.of combinations on each set :";
cout<<C[i]<<endl;
} // end fo for loop
}//end of while loop
return 0;
}//end of main
int factorial(int count)
{
int i;
for(i = count-1; i > 1; i--)
count *= i;
return count ;
}//end of function
THIS OUTPUT IS COMING:
"No. of combinations on set 0 : 0"
"No. of combinations on set 1 : 0"
………….
Well it's gone wrong already here
//intialize variables
int i,T,b,S[i],N,NN[i],C[i],count=0;
What's the value of i here? Answer, it doesn't have one. If i doesn't have a value then what's the size of this array NN[i]? Answer, who knows.
When you declare an array in C++, you must give it a size. The size cannot be a variable, it must be a cosntant. And it especialy cannot be a variable without a value.
Your program has undefined behaviour.
EDIT - this would be an improvement
#include <vector>
int main()
{
int T;
cin >> T;
while (T > 0)
{
int N;
cin >> N;
std::vector<int> NN(N), S(N);
for (int i = 0; i < N; i++)
{
...
First improvement is that I using a std::vector instead of an array. Unlike arrays vectors can have variable sizes. Second improvement is that I only declare variables when I need them, I don't declare all the variables at the start of the function. So I only declare NN and S when I know what the value of N is, so I know how big the vectors need to be.
Task
You'll be given an array of N integers and you have to print the integers in the reverse order.
Constraints
1<=N<=1000
1<=A_i<=10000, where A_i is the ith integer in the array.
Input
4
1 2 3 4
Output
4 3 2 1
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int N, y; //declaring N as the length of array
cin >> N; //intakes the length as an input
if (N>=1 && N<=1000){ //checks whether the length satisfies the rules
int a[N]; // makes an array containing N elements
for (int x =1; x<N; x++){ //starts transcription on the array
cin>>y; //temporarily assigns the input on a variable
if (y>=1&&y<=10000){ //checks if the input meets rules
a[x]=y; //copies the variable on the array
}
}
for (int z = N; z>1; z--){ //runs a loop to print in reverse
cout<<a[z]<<endl;
}
}
return 0;
}
Problem
Obtained output is
-1249504352
3
2
Indicating an error in transcription.
Question
Can somebody please tell me where I am making a mistake? Secondly, is it possible to directly check whether an input is meeting requirement rather than temporarily declaring a variable for it?
Here is a solution in idiomatic c++11, using std::vector, which is a dynamically resizable container useful for applications like this.
#include <vector>
#include <iostream>
#include <algorithm>
int main() {
int size;
std::cin >> size; // take in the length as an input
// check that the input satisfies the requirements,
// use the return code to indicate a problem
if (size < 1 || size > 1000) return 1;
std::vector<int> numbers; // initialise a vector to hold the 'array'
numbers.reserve(size); // reserve space for all the inputs
for (int i = 0; i < size; i++) {
int num;
std::cin >> num; // take in the next number as an input
if (num < 1 || num > 10000) return 1;
numbers.push_back(num);
}
std::reverse(numbers.begin(), numbers.end()); // reverse the vector
// print each number in the vector
for (auto &num : numbers) {
std::cout << num << "\n";
}
return 0;
}
A few things to note:
using namespace std is considered bad practice most of the time. Use (e.g.) std::cin instead for things which come from the std namespace.
numbers.reserve(size) is not necessary for correctness, but will make the program faster by reserving space in advance.
for ( auto &num : numbers ) uses a range-based for loop, available in c++11 and later versions.
You could make your for loop indices go from high to low:
for (int i = N-1; i > 0; --i)
{
std::cout << a[i] << "\n"; // Replace '\n' with space for horizontal printing.
}
std::cout << "\n";
This would apply with std::vector as well.
With std::vector, you can use a reverse iterator. There are other techniques available (as in other answers).
I have in C++ an array of 100 elements, so v[1], ... ,v[100] contains numbers. How can i display, 25 random numbers from this array? So i wanna select 25 random positions from this array and display the values.. How can i do this in C++?
Thanks!
#include <cstdlib>
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <vector>
using namespace std;
int aleator(int n)
{
return (rand()%n)+1;
}
int main()
{
int r;
int indexes[100]={0};
// const int size=100;
//int a[size];
std::vector<int>v;
srand(time(0));
for (int i=0;i<25;i++)
{
int index = aleator(100);
if (indexes[index] != 0)
{
// try again
i--;
continue;
}
indexes[index] = 1;
cout << v[index] ;
}
cout<<" "<<endl;
system("pause");
return 0;
}
The idea is that i have this code, and i generate 100 random numbers. What i want is an array with random 25 elements from those 100 generated.. But i don't know how to do that
Regards
Short Answer
Use std::random_shuffle(v.begin(),v.end()) to shuffle the array, and then display the first 25 elements.
Long Answer
First of all, the elements would be v[0]...v[99] (C++ uses 0-based indexing), not v[1]...v[100]. To answer your question, though, it depends on whether it is acceptable to repeat elements of the array or not. If you aren't worried about repeats, then simply use the index rand()%v.size(), repeatedly until you have selected a sufficient number of indices (25 in your question). If repeats are not acceptable, then you need to shuffle the array (by swapping elements at random), and then display the first (or last, or any contiguous region of) N elements (in this case N=25). You can use std::random_shuffle to shuffle the array. That does the bulk of the work for you. Once you've done that, just show 25 elements.
If you want to print 25 numbers of an array V you can use this code do:
int V[100]={1,2,5,...} ;
srand ( time (0) ) ;
for (int i=0;i<25;i++)
{
cout << V[rand() % 100 + 1]<<" " ;
}
I modified the version of Mehdi a little in order to make it choose differnet indexes
NOTE: This makes the algorithm not deterministic - it relies on the RNG.
int indexes[100]={0};
srand ( time (0) );
for (int i=0;i<25;i++)
{
int index = rand() % 100;
if (indexes[index] != 0)
{
// try again
i--;
continue;
}
indexes[index] = 1;
cout << v[index] ; cout << endl;
}