Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I need to receive an undetermined number of integer numbers in between (0-9). With this numbers, print them forwards and backwards, and then erase the numbers at the corners.
Example:
3 5 1 9 4 6 2 4 4 2 6 4 9 1 5 3
5 1 9 4 6 2 4 4 2 6 4 9 1 5
1 9 4 6 2 4 4 2 6 4 9 1
9 4 6 2 4 4 2 6 4 9
4 6 2 4 4 2 6 4
6 2 4 4 2 6
2 4 4 2
4 4
And here is the code I have so far:
#include <iostream>
using namespace std;
int a;
int p;
int set;
void numberss()
{
for set[](int a=0; a<p; a++)
}
int main()
{
cin >> p;
cin >> a;
const int SIZE = p;
int set[] = {a};
int *numPtr;
numPtr = set;
for (int index = 0; index < SIZE; index++)
{
cout << *numPtr << " ";
numPtr++;
}
for (int index = 0; index < SIZE; index++)
{
numPtr--;
cout << *numPtr << " ";
}
return 0;
}
If we ignore errors, you can read the numbers in one at a time, and form a string for the first line of output. Forming the string will involve appending a reversed copy to the original. Once the string is formed, you can output that string for the first line. Then replace the first number with a space character, and shrink the string from the back by two characters. Keep doing that until you are done.
This works because the numbers are all single digit.
int main (void)
{
int N;
std::string nums;
std::cin >> N;
for (int i = 0, x; i < N; ++i) {
std::cin >> x;
nums += std::to_string(x) + ' ';
}
nums.append(nums.rbegin() + 1, nums.rend());
for (int i = 0; i < N; ++i) {
std::cout << nums << '\n';
nums[2*i] = ' ';
nums.resize(nums.size()-2);
}
}
DEMO
Your code doesn't work because you are not reading all of the numbers from the user's input, you are only reading the count and the 1st number. Also, you are not looping enough times to output the numbers in a triangular fashion, you are only outputting the 1st line of the triangle.
Try this instead:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int p;
vector<int> set;
cin >> p;
set.resize(p);
for (int i = 0; i < p; ++i)
cin >> set[i];
for (int index = 0; index < p; index++)
{
int *numPtr = &set[index];
for (int i = 0; i < index; ++i)
cout << " ";
for (int i = index; i < p; ++i)
cout << *numPtr++ << " ";
for (int i = index; i < p; i++)
cout << *--numPtr << " ";
cout << endl;
}
return 0;
}
Live Demo
That being said, here is an alternative approach that is more C++-ish and less C-ish, by using iterators instead of pointers, and using STL algorithms. Also, you should always validate user input before using it:
#include <iostream>
#include <vector>
#include <iomanip>
#include <algorithm>
#include <limits>
#include <iterator>
#include <cstdint>
using uint16vec = std::vector<uint16_t>; // there is no operator>> for uint8_t...
int main()
{
size_t count = 0;
std::cin >> count;
uint16vec set;
set.reserve(count);
for (size_t i = 0; i < count; ++i)
{
uint16vec::value_type num;
while (!((std::cin >> num) && (num <= 9)))
{
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cin.clear();
std::cout << "Enter a valid number 0..9!" << std::endl;
}
set.push_back(num);
}
auto begin = set.begin(), end = set.end();
auto rbegin = set.rbegin(), rend = set.rend();
auto out = std::ostream_iterator<uint16vec::value_type>(std::cout, " ");
std::cout << std::setfill(' ');
for (size_t i = 0; i < count; ++i)
{
std::cout << std::setw((i*2)+1);
std::copy(begin++, end, out);
std::copy(rbegin, rend--, out);
std::cout << std::endl;
}
return 0;
}
Live Demo
Give this a shot, mate. I've commented it so you can follow along. It allows for characters other than numbers because that seemingly wasn't a requirement of your assignment, so it's on you to sort and filter those out. It prints as intended, so here's hoping that this is what you're looking for to start off with your search for the right answer.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void pop_front(vector<char>& _vector)
{
_vector.front() = move(_vector.back());
_vector.pop_back();
}
int main()
{
vector<char> characterList;
string consoleInput;
cin >> consoleInput;
//Initialize by pushing everyting from the console into our vector.
for (char c : consoleInput)
{
characterList.push_back(c);
}
//After adding from the console, now we'll do it in reverse.
for (int i = consoleInput.length() - 1; i > -1; i--)
{
characterList.push_back(consoleInput[i]);
}
//Print where we are currently up to for display purposes.
for (char c : characterList)
{
cout << c;
}
// Newline.
cout << "\n";
//Now let's start to chop it down. It'll take the same iterations as the console input, because we're doubling down.
for (int i = 0; i < consoleInput.length() - 1; i++)
{
characterList.erase(characterList.begin());
characterList.pop_back();
for (char c : characterList)
{
cout << c;
}
cout << "\n";
}
return 0;
}
Related
I am trying to write a C++ program to ask user to input a list of 5 numbers and print out the counts of the first number in the input. I have been trying to use array[] but I have some problems. The ideal inputs and outputs are :
Input : 1 1 2 3 1 Output: 3 because there are 3 counts of 1
Input : 1 2 3 4 5 Output: 1
Input : 1 1 1 0 0 Output: 3
Here are my codes, my code allows me to take the inputs but it does not do anything with it. Any help is appreciated!
#include <iostream>
using namespace std;
//frequency function
int frequency(int a[])
{
int count = 0;
for (int i=0; i < 6; i++)
if (a[i] == a[0])
{
count++;
}
cout << count << endl ;
return count;
}
// Driver program
int main() {
int i;
cout << "Please enter your numbers: ";
int a[5] = {a[0],a[1],a[2],a[3],a[4]};
for (i = 1; i < 6; i++)
{
// Reading User Input value Based on index
cin >> a[0] >> a[1] >> a[2]>> a[3] >> a[4];
return 0;
}
int n = sizeof(a)/sizeof(a[0]);
cout << frequency(a);
}
I tried another simpler approach but it needs a little more help
#include <iostream>
#include <string>
using namespace std ;
int main(){
cout << "Please enter your numbers: ";
int a[5];
int repeat;
int first = a[0];
int i;
for (i = 0; i < 6; i++)
{
// Reading User Input value Based on index
cin >> a[i];
}
if (a[i] == first){
repeat++;
}
cout << "Count: " << repeat;
}
you have an odd mixture of techniques for reading a set of numbers. You simply need
cout << "Please enter your numbers: ";
int a[5];
for (int i = 0; i < 5; i++)
{
// Reading User Input value Based on index
cin >> a[i];
}
and you certainly dont want that return as it will end the program
you would be better off using std::vector then you would not need to hard code the array size.
Note at the moment you have 6 as the arrays size in 'frequency' but 5 in main
I am trying to check whether there is any duplicate integer in the user input array. The problem is that the validation of the duplicate does not work properly and I have no idea why it is not showing the desired output. Following is the code:
#include <iostream>
using namespace std;
int main()
{
int length;
int arrValue;
cout << "Enter the length : ";
cin >> length;
int *arr = new int[length];
cout << "Enter " << length << " integers for array : ";
for(int i = 0; i < length; i++)
{
cin >> arr[i];
}
cout << "Array : ";
for(int i = 0; i < length; i++)
{
arrValue = arr[i];
for(int k = i + 1; k < length; k++)
{
if(arr[i] == arr[k])
{
cout << "Duplicate found" << endl;
break;
}
else
{
cout << arrValue << " ";
}
}
}
delete[] arr;
}
Current result (assuming no duplicate in user input):
Enter the length: 5
Enter 5 integers for array : 5 4 3 2 1
Array : 5 5 5 5 4 4 4 3 3 2
Expected result (assuming no duplicate in user input):
Enter the length: 5
Enter 5 integers for array : 5 4 3 2 1
Array : 5 4 3 2 1
Current result (assuming duplicate in user input):
Enter the length: 5
Enter 5 integers for array : 5 4 4 2 1
Array : 5 5 5 5 Duplicate found 4 4 3
Expected result (assuming duplicate in user input):
Enter the length: 5
Enter 5 integers for array : 5 4 4 2 1
Array : Duplicate found
I believe my loops is the source to the problem. The current result output 10 times and I do not understand why there will be so many same numbers appearing.
Do note that I am trying to apply the validation using loop only and not from C++ standard library.
The issue in your code is that you are printing out each array element every time a particular element is not matching another element. It seems that you only want to print out whether any duplicate values are found. For this, you can use a bool flag to indicate whether any element is duplicated:
bool found_dup = false;
for(int i = 0; i < length; i++)
for(int k = i + 1; k < length; k++)
if(arr[i] == arr[k])
{
found_dup = true;
break;
}
// else: don't print anything yet
and then at the end print out the array:
if (found_dup)
std::cout << "Duplicate found";
else
for(int i = 0; i < length; i++)
std::cout << arr[i] << " ";
You may achieve the program in a more enhanced way (where you don't need to define the length manually - notice the explanation given as comments in code):
#include <iostream> // for input/output operation
#include <vector> // for dynamic array management
#include <sstream> // to split the user inputs and assign them to the vector
#include <algorithm> // to sort the vector
#include <string> // to work with getline()
// using this statement isn't recommended, but for sake of simplicity
// and avoiding the use of std:: everywhere temporarily (for small programs)
using namespace std;
int main(void) {
vector<int> numbers;
vector<int> duplicates;
string input;
int temp;
// getting the user input as string
cout << "Enter the numbers: ";
getline(cin, input);
stringstream ss(input);
// splitting the user input string into integers and assigning
// them into the vector
while (ss >> temp)
numbers.push_back(temp);
// sorting the vector in increasing order
sort(numbers.begin(), numbers.end());
// getting the unique numbers (which are not repeated)
cout << "Unique numbers: ";
for (size_t i = 0, len = numbers.size(); i < len; i++) {
if (temp == numbers[i])
// if found a duplicate, then push into the 'duplicates' vector
duplicates.push_back(temp);
else
cout << numbers[i] << ' ';
temp = numbers[i];
}
// getting the duplicates
cout << "Total duplicates: ";
for (size_t i = 0, len = duplicates.size(); i < len; i++)
cout << duplicates[i] << ' ';
cout << endl;
return 0;
}
It'll output something like:
Enter the numbers: 1 4 8 9 3 2 3 3 2 1 4 8
Unique numbers: 1 2 3 4 8 9
Total duplicates: 1 2 3 3 4 8
Please change the if condition to something like this.
cout << "Enter the length : ";
cin >> length;
int *arr = new int[length];
cout << "Enter " << length << " integers for array : ";
for(int i = 0; i < length; i++)
{
cin >> arr[i];
}
cout << "Array : ";
for(int i = 0; i < length; i++)
{
arrValue = arr[i];
for(int k = i + 1; k < length; k++)
{
if(arrValue == arr[k]) //change here.
{
cout << "Duplicate found" << endl;
break;
}
else
{
cout << arrValue << " ";
}
}
}
delete[] arr;
}
I would also suggest to use a map data structure. Map allows you to count the frequency of numbers, and thus detect duplicates in linear time.
map<int, int> m; // specify the key-value data-type.
for(int i = 0;i<length;i++)
{
m[arr[i]]++;
}
map<int, int>::iterator it; // an iterator to iterate over the datastructure.
for(it = m.begin();it!=m.end();it++)
{
if(it->second>1) //it->second refers to the value(here, count).
{
cout<<it->first<<" "; //it->first refers to the key.
}
}
Your loops are actually iterating n-1 times for first element, n-2 times for second element etc., where n is the length of your array. This is why for 5 element array you have printed 5 4 times.
But generally, if the purpose is to detect duplicates in the array, this strategy is not the best one. Please note that having exemplary array 4 3 4, with current approach you will correctly detect for the first 4 that the third element is also 4 but once you will move to the third element, it will be marked as ok since it is not checked with the first one element.
You may consider another strategy: create another array of the n size. Then iterate through your original array and for each element check if that element is already in the new array. If you detect the presence, you may raise duplicate event. Otherwise you can add this element to the array.
It doesn't work because you're trying to print the same value everytime you find a different one. I got here a solution with one more array that will store the array. It would work too with just one array.
#include <iostream>
using namespace std;
int main()
{
int length;
int arrValue;
cout << "Enter the length : ";
cin >> length;
int *arr = new int[length];
int *noDuplicateArr = new int[length];
cout << "Enter " << length << " integers for array : ";
for(int i = 0; i < length; i++)
cin >> arr[i];
cout << "Array : ";
bool duplicateFound = false;
int noDuplicateArrLen = 0;
for(int i = 0; i < length && !duplicateFound; i++)
{
arrValue = arr[i];
int k;
for(k = i + 1; k < length; k++)
{
if(arrValue == arr[k])
{
duplicateFound = true;
break;
}
}
if (k == length)
noDuplicateArr[noDuplicateArrLen++] = arrValue;
}
if (duplicateFound)
{
cout << "Duplicate found";
}
else
{
for (int i = 0; i < noDuplicateArrLen; i++)
{
cout << noDuplicateArr[i] << " ";
}
}
delete[] arr;
delete[] noDuplicateArr;
}
Here is the version with just one array:
#include <iostream>
using namespace std;
int main()
{
int length;
int arrValue;
cout << "Enter the length : ";
cin >> length;
int *arr = new int[length];
cout << "Enter " << length << " integers for array : ";
for(int i = 0; i < length; i++)
cin >> arr[i];
cout << "Array : ";
bool duplicateFound = false;
int noDuplicateArrLen = 0;
for(int i = 0; i < length && !duplicateFound; i++)
{
arrValue = arr[i];
int k;
for(k = i + 1; k < length; k++)
{
if(arrValue == arr[k])
{
duplicateFound = true;
break;
}
}
if (k == length)
arr[noDuplicateArrLen++] = arrValue;
}
if (duplicateFound)
{
cout << "Duplicate found";
}
else
{
for (int i = 0; i < noDuplicateArrLen; i++)
{
cout << arr[i] << " ";
}
}
delete[] arr;
}
I am a novice in C++. I am trying to get input from the user for inserting in a multidimensional vector. The code works fine. But when I give extra inputs in the same line, my program does not disregard it and considers it in the next iteration.
For example when I give input in the following format:
m=3 n=4
1 2 3 4 5
1 3 5 5
1 345 65 567
the output is
1 2 3 4
5 1 3 5
5 1 345 65
But what the output I want is
1 2 3 4
1 3 5 5
1 345 67 567
int main() {
vector<vector<int>> vec;
int m, n, dat;
cout << "Enter dimensions of Vector";
cin >> m >> n;
// takes data n times into a subvector temp and inserts it into the vector vec m
// times
cout << "Enter elements one row at a time";
for(int i = 0; i < m; ++i) {
vector<int> temp;
for(int j = 0; j < n; ++j) {
cin >> dat;
temp.push_back(dat);
}
vec.push_back(temp);
}
for(int k = 0; k < vec.size(); ++k) {
for(int i = 0; i < vec[k].size(); ++i) {
cout << setw(4) << vec[k][i];
}
cout << endl;
}
}
Consider using std::getline to read a complete line. You can then use that to populate a std::istringstream that you then use to extract the exact number of elements you want. Also note:
Why is “using namespace std;” considered bad practice?
Example:
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main() {
std::vector<std::vector<int>> vec;
int m, n, dat;
std::cout << "Enter dimensions of Vector";
std::cin >> m >> n;
std::cin.ignore(); // skip newline
// takes data n times into a subvector temp and inserts it into the vector vec m
// times
std::cout << "Enter elements one row at a time\n";
for(int i = 0; i < m; ++i) {
std::string line;
std::vector<int> temp;
std::cout << " row " << (i + 1) << ": ";
std::getline(std::cin, line);
std::istringstream iss(line);
for(int j = 0; j < n; ++j) {
iss >> dat;
temp.push_back(dat);
}
vec.push_back(temp);
}
for(const auto& row : vec) {
for(int colval : row) {
std::cout << std::setw(4) << colval;
}
std::cout << "\n";
}
}
can someone fix my code?
this is the result that should be showed when i input number 5 in c++
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15
my result:
1
2 6
3 7 10
4 8 11 14
5 9 12 15 18
my code:
#include <iostream.h>
#include <conio.h>
#include <math.h>
void main()
{
int n,i,j;
cout<<"insert number"<<endl;
cin>>n;
for (i=1;i<=n;i++)
{
int y=1;
int g=1;
cout<<i<<" ";
for (j=1;j<=i-1;j++)
{
int x=n;
int b=i;
x--;
g--;
cout<<(x*y)+b+g<<" ";
y++;
}
cout<<endl;
}
getch ();
}
what did i do wrong?
sorry if my code messy i'm a c++ new learner.
You could it like this:
#include <iostream>
using namespace std;
int main()
{
int n , i ,j, sum;
cout << "masukkan bilanga" << endl;
cin >> n;
for(i = 0; i < n; i++)
{
cout << i + 1 << " ";
sum = i + 1;
for(j = 0; j < i; j++)
{
sum += n - 1 - j;
cout << sum << " ";
}
cout << endl;
}
return 0;
}
where the key point is that you want to print all the numbers, starting from 1, in a column-major manner, until a triangular n x n matrix is created.
Driven from the output, one can easily see that every element of the next column is what the current element is, plus n - 1, and that factor decreases by one as we advance to the right part of the matrix.
Try this code, hope this is what you need:
#include <iostream>
#include <string>
void printMatrix(int number);
void main()
{
int number = 1;
std::cout << "Enter a number: ";
std::cin >> number;
printMatrix(number);
}
void printMatrix(int number) {
std::cout << std::endl;
for (int i = 1; i <= number; i++) {
std::cout << i << " ";
int n = i;
for(int j = 1; j < i; j++) {
n += number - j;
std::cout << n << " ";
}
std::cout << std::endl;
}
}
I am trying to make a code for one of the problems on an online coding platform. I have already made the code, but cannot get the input in the desired format. I need to take an input which has three integers (say n1, n2 and m). The question says that the input can be numbers separated by white spaces. I tried looking for help and even found a way, but it isn't working.
Here is my code:
#include <string>
#include <ctype.h>
#include <iostream>
#include <conio.h>
#include <stdlib.h>
using namespace std;
int main()
{
int t;
cout << "Enter the number of test cases" << endl;
cin >> t;
do
{
string rawInput;
int isNum, n1, n2, m, t, i, j;
int arr[3];
arr[0] = 0;
arr[1] = 0;
arr[2] = 0;
cout << "Enter a number, or numbers separated by a space, between 1 and 1000." << endl;
while (getline(cin, rawInput))
{
cout << "Rawinput" << rawInput.length();
for (i = 0; i < rawInput.length(); ++i)
{
cout << rawInput[i];
}
int j = 0, k = 0;
for (int j; j < rawInput.length(); ++j)
{
isNum = isdigit(rawInput[j]);
if (isNum)
{
arr[k] = arr[k] * 10 + atoi(rawInput[j]);
}
else
k = k++;
}
cout << "I am Array" << endl;
for (int l = 0; l < 3; l++)
cout << arr[l] << endl;
}
if (arr[0] >= arr[2] && arr[1] >= arr[2])
{
for (int i = 1; i <= arr[2]; i++)
{
if (arr[0] >= i && arr[1] >= i)
{
arr[0] = arr[0] - i;
arr[1] = arr[1] - i;
}
}
}
cout << arr[1] + arr[0];
t--;
} while (t > 0);
}
Specifically the function atoi doesn't seem to work. I tried using stoi, but even that isn't working.
If you are simply trying to collect a series of integers separated by spaces as user input..ie 1 2 3 4 5, you don't have to user the getline method.
You can redo the while loop for a condition like this:
int input;
while (cin >> input)
{
<<HANDLE INPUT>>
}
This is drastically reduce the line parsing you are trying to do and will capture the next inputted integer on that line as long as there is one to take. The loop iteration will go like this with the same series above...
Loop # Input Taken
1 1
2 2
3 3
... ...
This way there is no parsing necessary as it will handle ONE integer input per iteration.