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).
Related
I have been given some integers and I have to count the frequency of a specific digit in the number.
example input:
5
447474
228
6664
40
81
The first number says number of integers in the list. I am finding frequency of 4 in this case. I tried to change the integer to an array, but it is not working.
#include<iostream>
#include<cmath>
#include<vector>
using namespace std;
int main() {
int n;
cin>>n;
for (int i=0; i<n; i++)
{
int x;
cin>>x;
int frequency=0;
int t=log10(x);
int arr[t];
for (i=t; i>0; i--)
{
arr[i]=x%10;
x=x/10;
}
for(int i=0; i<t; i++)
{
if(arr[i]==4)
{
frequency++;
}
}
std::cout << frequency << std::endl;
}
return 0;
}
No need to create an array, or to determine the number of digits. Just loop until the number reaches zero.
int digitCount(int n, int d) {
if(n < 0) n = -n;
int count = 0;
for(; n != 0; n /= 10)
if(n % 10 == d) count++;
return count;
}
Test:
cout << digitCount(447474, 4) << endl;
cout << digitCount(-447474, 4) << endl;
Output:
4
4
Your code uses VLAs which are not standard C++. See Why aren't variable-length arrays part of the C++ standard?.
log10(x) is not the number of digits. For example log10(1234) == 3.09131516 but it is 4 digits. Also you are accessing the array out of bounds in the first iteration of the loop: arr[t]. Valid indices in an array of size t are 0,1,2,...,t-1. Trying to access arr[t] is undefined behavior.
Actually you dont need any array. Instead of storing the digits in an array you can immediately check whether it is a 4 and count.
Even simpler would be to read the user input as a std::string:
#include <string>
#include <algorithm>
#include <iostream>
int main() {
std::string input;
std::cin >> input;
std::cout << std::count(input.begin(),input.end(),'4');
}
Perhaps you should add some checks to verify that the user input is actually a valid number. However, also when reading an int you should validate the input.
The funcion HIGHEST is all good and accepts variable number of arguments. The problem is how do I do variable amount of input? (idk what terms should be use to describe it, but examples should clear things up...)
/*cout << highest(n, A[0],A[1],A[2],A[3]) <<endl;
this is what I would like to achieve,
but with a change - the number of array changes with
the input file and n defines how many of these will be.
ex.: if n = 7 it needs to be (n, A[0],A[1],A[2],A[3], A[4], A[5], A[6])
*/
Duom.txt file if needed (i am now only working with 1st number 4 under it others will follow same/similar thing as 1st row they are not important now)
4
2008 5 2000.00 400.25
2010 5 4000.00 320.25
2009 9 3385.00 254.45
2008 6 1900.00 612.59
#include <iostream>
#include <iomanip>
#include <cmath>
#include <fstream>
#include <cstdarg>
using namespace std;
//Variable number of arguments in C++
int highest (int num,...) {
va_list valist;
int max = 0;
int a;
va_start(valist, num);
for (int i = 0; i < num; i++) {
a = va_arg(valist, int);
if(max < a) max = a;
else ;
}
va_end(valist);
return max;
}
int main () {
int n, A[25], B[25];
double C[25], D[25];
ifstream fd ("Duom.txt");
ofstream fr ("Rez.txt");
fd >> n;
cout << n <<endl;
for(int i = 0; i < n; i++){
fd >> A[i] >> B[i] >> C[i] >> D[i];
}
cout << highest(n, ) <<endl;
/*cout << highest(n, A[0],A[1],A[2],A[3]) <<endl;
this is what I would like to achieve,
but with a change - the number of array changes with
the input file and n defines how many of these will be.
ex.: if n = 7 it needs to be (n, A[0],A[1],A[2],A[3], A[4], A[5], A[6])
*/
return 0;
}
is there a specific reason you want the function Highest to get all array integers separately? Also - why did you choose to use an array instead of a vector?
Assuming that you want to use an array, I'd suggest to change the function's arguments as follows:
int highest (int num,int *arr);
where arr is the name of your array and in fact a pointer to the first integer of the array.
Then, inside the function, you can just access the array using subscript notation or dereferencing:
first_array_int=*(arr); //dereferencing example
second_array_int=*(arr+1); //dereferencing example
or
first_array_int=arr[0]; //subscript example
second_array_int=arr[1]; //subscript example
note that by doing that you can change the passed array within the function.
Again, I'd suggest to use a vector instead, then define the function:
int highest (int num,vector <int> *A);
if you want to pass a pointer, or:
int highest (int num,vector <int> A);
if you want to pass by value. Ofcourse, don't forget to include the vector library with
#include <vector>
I hope I understood your question well and that this is helpful.
Goodluck!
Guy
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.
#include<iostream>
using namespace std;
int main()
{
int s;
cin>>s;
int t=3;
int maxValue,imax[t],maxIndex,arr[s];
for(int i=0; i<s; i++){
cin>>arr[i];
}
maxValue=arr[0];
for(int i=0;i<s;i++){
if(arr[i]>maxValue){
maxValue=arr[i];
imax[0] = i;
}
}
maxValue=arr[0];
for(int i=0;i<s;i++){
if (i == imax[0]) { continue; }
if(arr[i]>maxValue){
maxValue=arr[i];
imax[1] = i;
}
}
maxValue=arr[0];
for(int i=0;i<s;i++){
if (i == imax[0]) { continue; }
if (i == imax[1]) { continue; }
if(arr[i]>maxValue){
maxValue=arr[i];
imax[2] = i;
}
}
cout<<"First biggest number:"<<arr[imax[0]]<<"\n";
cout<<"Second biggest number:"<<arr[imax[1]]<<"\n";
cout<<"Third biggest number:"<<arr[imax[2]];
return 0;
}
This program must return tree numbers which is biggest in this arraybut , i do not know why when I introduce as example five numbers (121,34,56,67,545) and the compiler was return 545 and then crash.
Thank you in advance for the answer.
The problem is that before iterating the loop, you first set the maxValue to be the first element in the array. The imax only gets updated whenever there is at least one element greater than the current maxValue. However, if the first element is somehow the maxValue you are looking for, then the imax never gets set, which would be uninitialized causing segmentation fault at the end.
In your code, after finding the largest element 545, the second largest element was never found, since 121 is the first element in the array. Hence after printing out 545, imax[1] is uninitialized and the program crashes.
You use uninitialized array values in lines
cout<<"First biggest number:"<<arr[imax[0]]<<"\n";
cout<<"Second biggest number:"<<arr[imax[1]]<<"\n";
cout<<"Third biggest number:"<<arr[imax[2]];
If there are less than 3 different numbers in input, some imax array elements will not be initialized. Also if input array is empty, imax will not be initialized at all.
Therefore in expression arr[imax[1]] you read element of arr with index, which was not initialized and can be some very big number. It can be fixed if you declare iarr as
int imax[t] = {};
This will zero-initialize all elements of array and will prevent crashing.
Your program also doesn't check number of elements in input array, so if there are less than three input numbers arr[2] will also print uninitialized value.
Here's proper solution using STL algorithms and std::vector. It works with any number of t - you can easily change it to print largest 10 numbers. It is also memory efficient - it does not need to store whole input array so you can process large inputs with it.
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
int s;
std::cin >> s;
unsigned t = 3;
std::vector<int> max_numbers;
max_numbers.reserve(t + 1);
for (int i = 0; i < s; ++i) {
int number;
if (std::cin >> number) { //Check basic input errors
max_numbers.push_back(number); // Add number to top-3 list
// Sort elements in descending order
std::sort(max_numbers.begin(), max_numbers.end(), std::greater<int>());
// Remove duplicates
max_numbers.erase(std::unique(max_numbers.begin(), max_numbers.end()),
max_numbers.end());
// Remove excess elements
if (max_numbers.size() > t) {
max_numbers.resize(t);
}
}
}
std::cout << "Biggest " << t << " numbers are" << std::endl;
for (int i : max_numbers) {
std::cout << i << std::endl;
}
}
I'm creating this very simple C++ program.
the program asks the user to enter a few integers and stores them in an array.but when a specific integer(for example 50)is entered,the input is ended and then,all of the integers are displayed on the screen except for 50.
for example:
input:
1
2
88
50
output:
1
2
88
the error i'm getting is when i use cout to print the array,all of numbers are shown,including 50 and numbers i did'nt even entered.
this is my code so far:
#include<iostream>
int main() {
int num[100];
for(int i=0;i<=100;i++) {
cin >> num[i];
if (num[i]!=50) break;
}
for(int j=0;j<=100;j++) {
cout << num[j] << endl;
}
return 0;
}
Change the program the following way
#include<iostream>
int main()
{
const size_t N = 100;
int num[N];
size_t n = 0;
int value;
while ( n < N && std::cin >> value && value != 50 ) num[n++] = value;
for ( size_t i = 0; i < n; i++ ) std::cout << num[i] << std::endl;
return 0;
}
Here in the first loop variable n is used to count the actual number of entered values. And then this variable is used as the upper bound for the second loop.
As for your program then the valid range of indices for the first loop is 0-99 and you have to output only whose elements of the array that were inputed.
A do while loop is more suitable for your problem. The stop condition will check if the number fit inside the array (if k is not bigger than 100) and if number entered is 50.
#include<iostream>
using namespace std;
int main() {
int num[100];
int k = 0;
// A do while loop will be more suitable
do{
cin >> num[k++];
}while(k<100&&num[k-1]!=50);
for (int j = 0; j < k-1; j++) {
cout << num[j] << endl;
}
return 0;
}
Also, a better solution to get rid of 100 limitation is to use std::vector data structure that automatically adjust it's size, like this:
vector<int> num;
int temp;
do {
cin >> temp;
num.push_back(temp);
} while (temp != 50);
Note, you can use temp.size() to get the number of items stored.
You read up to 101 numbers, but if you enter 50 you break the loop and go for printing it. In the printing loop you go through all 101 numbers, but you actually may have not set all of them.
In the first loop count in a count variable the numbers you read until you meet 50 and in the printing loop just iterate count-1 times.
You have allocated an array of 100 integers on the stack. The values are not initialized to zero by default, so you end up having whatever was on the stack previously appear in your array.
You have also off-by-one in both of your loops, you allocated array of 100 integers so that means index range of 0-99.
As the question is tagged as C++, I would suggest that you leave the C-style array and instead use a std::vector to store the values. This makes it more flexible as you don't have to specify a fixed size (or manage memory) and you don't end up with uninitialized values.
Little example code (requires C++11 compiler):
#include <iostream>
#include <vector>
int main()
{
std::vector<int> numbers; // Store the numbers here
for(int i = 0; i < 100; ++i) // Ask a number 100 times
{
int n;
std::cin >> n;
if( n == 50 ) // Stop if user enters 50
break;
numbers.push_back(n); // Add the number to the numbers vector
}
for (auto n : numbers) // Print all the values in the numbers vector
std::cout << n << std::endl;
return 0;
}
There are just 2 changes in your code check it out :
int main()
{
int num[100],i; //initialize i outside scope to count number of inputs
for(i=0;i<100;i++) {
cin >> num[i];
if (num[i]==50) break; //break if the entered number is 50
}
for(int j=0;j<=i-1;j++)
{
cout << num[j] << endl;
}
return 0;
}
Okay, others already pointed out the two mistakes. You should use i < 100 in the loop conditions instead of i <= 100 and you have to keep track of how many elements you entered.
Now let me add an answer how I think it would be better.
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers; // Create an empty vector.
for (int temp; // a temp variable in the for loop.
numbers.size() < 100 && // check that we have less than 100 elements.
std::cin >> temp && // read in the temp variable,
// and check if the read was a success.
temp != 50) // lastly check that the value we read isn't 50.
{
numbers.push_back(temp); // Now we just add it to the vector.
}
for (int i = 0; i < numbers.size(); ++i)
std::cout << numbers[i]; // Now we just print all the elements of
// the vector. We only added correct items.
}
The above code doesn't even read anymore numbers after it found 50. And if you want to be able to enter any number of elements you just have to remove the check that we have less than 100 elements.
Now I commented the above code a bit much, if you compress it it'll reduce to just:
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers; // Create an empty vector.
for (int temp; numbers.size() < 100 && std::cin >> temp && temp != 50)
numbers.push_back(temp);
for (int i = 0; i < numbers.size(); ++i)
std::cout << numbers[i];
}
If you can use the C++11 standard it reduces to:
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers; // Create an empty vector.
for (int temp; numbers.size() < 100 && std::cin >> temp && temp != 50)
numbers.push_back(temp);
for (int element : numbers)
std::cout << element;
}
for (auto element : numbers) is new, it basically means for every int 'element' in 'numbers'.