I wrote this piece of code, which has t test cases, and for every test cases it would input 3 digits. I want this program to then identify the minimum element among those three inputs, and then print the minimum element. What should I do?
int main()
{
int t;
cin>>t;
while(t--)
{
for(int i=0;i<3;i++)
{
int n;
cin>>n;
}
}
return 0;
}
Here's a example of finding the minimum of three digits, using a running minimum:
#include <iostream>
int main()
{
unsigned int test_case_quantity = 0U;
std::cin >> test_case_quantity;
while(test_case_quantity--)
{
char minimum;
std::cin >> minimum;
char digit;
std::cin >> digit;
if (digit < minimum) minimum = digit;
std::cin >> digit;
if (digit < minimum) minimum = digit;
std::cout << " minimum: " << minimum << "\n";
std::cin.ignore(100000, '\n'); // Synchronize to next line.
}
return 0;
}
For a more robust program, you can add validation that the character read is actually numeric.
We can make use of an extra variable say small and when we are inputting the very first number, we can assign that first number to the small and in all other cases we can compare whether the current number is less than small, if yes then update small.
Finally outside the loop we can print the value of small and this will be our answer.
int main()
{
int t;
cin>>t;
while(t--)
{
int small;
for(int i=0;i<3;i++)
{
int n;
cin>>n;
if (i == 0)
small = n;
else {
if (n < small)
small = n;
}
}
cout<<"Smallest number is :" << small;
}
return 0;
}
input :
1
10 2 3
output :
Smallest number is :2
Flow :
At first the value 10 will be assigned as small, then for the next element 2, we compare whether 2 is less than small which is 10 in that case, and reassign small to 2. Then this small is checked with 3, but 2 < 3, so small value remains unchanged.
I assume there will be only integer values as input.
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.
I have been trying to solve this simple problem in C++ but every time I submit, it says wrong answer. I am pretty sure I have got the logic right. Any help is appreciated.
Question: Find the sum of distances between the inputted numbers.
Ex. Input: 2 5 8 2 1
Distance=2+2+5+0
=9, (1 < n < 1000000)
PS: Input can't have the same number consecutively.
PSS: Subtask two is giving Wrong Answer
Code:
#include <iostream>
using namespace std;
int main() {
// your code goes here
int t,a[100000],n,sum=0;
cin>>t;
for(int i=0;i<t;i++)
{
cin>>n;
for(int j=0;j<n;j++)
{
cin>>a[j];
}
for(int j=0;j<n-1;j++)
{
if(a[j]!=a[j+1])
{
sum = sum + abs(a[j]-a[j+1])-1;
}
}
cout<<sum<<endl;
sum=0;
}
}
The problem with your code is that you are using int type for sum whose maximum value (1E11) can exceed the upper limit of int(if it's 32-bit or less). Use long long(atleast 64-bit) instead to store your sum.
Well, you can also optimize the code because you don't exactly need an array of 100000 integers and store the values in it. You can do so using only two variables.
Here is a modified implementation of your logic:
#include <iostream>
int main() {
int t, n, first, second;
long long sum; // or better use std::int_fast64_t sum;
std::cin >> t;
while (t--) {
sum = 0;
std::cin >> n >> first;
for (int i = 0; i < n - 1; ++i) {
std::cin >> second;
sum += std::abs(first - second) - 1;
first = second;
}
std::cout << sum << std::endl;
}
}
PS: In competitive coding checking the provided constraints like if(a[j]!=a[j+1]) is useless. The problem statement simply guarantees it that it will never be false.
I'm working on an assignment for class and am having a bit of a hard time putting it together. I had just started learning arrays and am not sure exactly how to get user input in the array.
Here is the assignment prompt: Create a program that inputs up to 100 integers (space separated!) and outputs their sum. For example:
1 2 3 4 5 6 7 8 9 10
55
This is what I have so far (edit because I forgot to change comments):
#include <iostream>
using namespace std;
int addNum(int n);
int main() {
int n;
// prompt user to input numbers
cout << "Please enter in values to add together: ";
cin >> n;
cout << addNum(n);
// pause and exit
getchar();
getchar();
return 0;
}
// function
int addNum(int n) {
int arr[99] = {};
int sum = 0;
for (int i = 0; i < n; i++) {
sum = sum + arr[i];
}
return sum;
}
Since this is a learning exercise, I wouldn't correct your code, but explain what you've missed so far:
The assignment asks to read integers until there's no more input; your code prompts the user for the count upfront, which should be removed.
You do not need an array to store the individual numbers, because the assignment asks only for the total. This can be computed on the fly: read a number, add it to sum, and forget the number.
You can read numbers until the end of input with a simple loop that uses >> operator below.
Here is an example that limits the input to 100 numbers, or stops when the input stream ends:
int limit = 0;
int nextNumber;
while ((limit++ != 100) && (cin >> nextNumber)) {
... // Process the next number
}
If you are giving your program input from console (as opposed to feeding it a file with numbers) and you need to end your input sequence, press Ctrl+z on Windows or Ctrl+d on UNIX.
In order to provide a diverse range of answers, std::accumulate is pretty cool.
http://en.cppreference.com/w/cpp/algorithm/accumulate
int sum = std::accumulate(v.begin(), v.end(), 0);
or in your case
int sum = std::accumulate(arr, arr + 99, 0);
Another functional approach is to use std::reduce introduced in C++17
http://en.cppreference.com/w/cpp/algorithm/reduce
Was able to get a working code after talking to the professor about it! Here's the working code:
#include <iostream>
using namespace std;
int main() {
// variable declarations
int sum = 0, count = 0;
int c;
// array declaration
int arr[100] = { 0 };
// prompt user to input numbers & add
cout << "Please enter in values to add together: ";
for (int i = 0; i < 100; i++) {
cin >> arr[i];
c = cin.peek();
sum = sum + arr[i];
// if user presses enter, skip to outputting sum without waiting for 100 values
if (c == '\n'){
break;
}
}
// output the sum of input
cout << sum;
// pause and exit
getchar();
getchar();
return 0;
}
For a project I need to write a program that reads in a series of positive integers, stored in an array, terminated by a -1. Then it should reverse the order of the array and print that along with the average of all the numbers.
ex: Input: 21 34 63
Output: 63 34 21 Ave: 39.3
I am not sure where to begin. I thought maybe getting a user input in a while loop. So,
int num, i;
const int SIZE = 9;
int arr [SIZE] = {i};
i = 1;
while(num !=-1){
cout << "Enter a number: ";
cin >> num;
arr[i] = num;
i++;
}
cout << arr;
Okay so, first how do I create an array that takes user inputs and stores it as separate variables in the array? (Above is my unsuccessful attempt at that.)
Thats a simple problem. You first need to take the input and then reverse it.
int num=0, i,j,k;
const int SIZE = 99; //any upperbound value, just to ensure user doesnt enter more values then size of array
int arr [SIZE] = {0}; //better to initialize with 0
i = 0; //considering 0 indexed
int sum=0; // for average
while(num !=-1){
cout << "Enter a number: ";
cin >> num;
if(num!=-1)
{
arr[i] = num;
sum+=num;
}
i++;
}
int temp;
//now reversing
// size of the input array is now i
for(j=0,k=i-1;j<k;j++,k--)
{
temp=arr[j];
arr[j]=arr[k];
arr[k]=temp;
}
//what i am doing here is- keeping the index j on the beginning of the
//array and k to the end of the array. Then swap the values at j and k, then
//increase j and decrease k to move to next pair of points. We do this until j is
//less then k, means until we doesnt reach mid of the array
//printing the reversed array and average
cout<<"reversed array"<<endl;
for(j=0;j<i;j++)
cout<<arr[j]<<" ";
cout<<"average"<<float(sum)/i;
see the comments for suggestions
Since you are writing your program in c++, you should take a look at std::vector and the reverse function that the STL provides you.
Using the above tools the solution to your problem is the following:
#include <vector>//include to use std::vector
#include <algorithm>//include to use reverse
int main()
{
std::vector<int> v;
int i;
float sum = 0.0f;
while(std::cin>>i && i != -1)
{
v.push_back(i);
sum+=i;
}
reverse(v.begin(),v.end());
for(int num : v)
std::cout<<num<<" ";
std::cout<<"average:"<<sum/v.size()<<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'.