I make the user to type maximum elements and then enter that elements into first array p,then I want to take only the elements that are bigger than 0 and transfer them to a new array w. Here's the code and where exactly I make mistake:
void main(){
int p[10], w[10], n,i,j;
cout << "Maximum elements: "; cin >> n;
for (i = 0; i < n; i++){
cout << "Enter " << i << "-nd element"; cin >> p[i];
}
j = 0;
for (i = 0; i < n; i++){
if (p[i] > 0){
w[j] = p[i];
j++;
}
for (j = 0; j < n; j++){
cout << w[j];
}
}
system("pause");
}
In:
for (i = 0; i < n; i++){
if (p[i] > 0){
w[j] = p[i];
j++;
}
for (j = 0; j < n; j++){
cout << w[j];
}
}
the inner loop is printing every element of the array w. That loop is executed for every element of p (being it inside the outer for loop).
This mean that, for example, the first time it visits p to check if the first element is 0, it may assign w[0] and then go on and print all the elements of w. Problem is that w is not initialised at that point, so what you see is random garbage (probably).
Just move the loop outside and make it so it only prints the part of the array that is populated:
for (i = 0; i < n; i++){
if (p[i] > 0){
w[j] = p[i];
j++;
}
}
for (int k = 0; k < j; k++){
cout << w[k];
}
Live demo
Also learn how to use std::vector or std::array and the algorithms in <algorithm>.
Also remember that main has return type int.
Using std::copy_if from <algorithm> do the job you want, as in the example provided in http://www.cplusplus.com/reference/algorithm/copy_if/:
// copy_if example
#include <iostream> // std::cout
#include <algorithm> // std::copy_if, std::distance
#include <vector> // std::vector
int main () {
std::vector<int> foo = {25,15,5,-5,-15};
std::vector<int> bar (foo.size());
// copy only positive numbers:
auto it = std::copy_if (foo.begin(), foo.end(), bar.begin(), [](int i){return !(i<0);} );
bar.resize(std::distance(bar.begin(),it)); // shrink container to new size
std::cout << "bar contains:";
for (int& x: bar) std::cout << ' ' << x;
std::cout << '\n';
return 0;
}
For you code, the problem is that you modify j in the printing loop whereas it is primary used as output index. Try to reduce scope of your local variable to out spot those issues, creating sub function may also help.
Finnaly, your fixed code may be something like:
void main(){
std::cout << "Maximum elements: ";
int n;
std::cin >> n;
int p[10];
for (int i = 0; i < n; i++){
std::cout << "Enter " << i << "-nd element";
std::cin >> p[i];
}
int w[10];
int w_size = 0;
for (int i = 0; i < n; i++){
if (p[i] > 0){
w[w_size] = p[i];
w_size++;
}
}
for (int i = 0; i < w_size; i++){
std::cout << w[i];
}
system("pause");
}
Related
I want a program that asks the number of rows and columns of the multidimensional array and then using For loop iterate values in the array.
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n, m, x;
int a[n][m];
cin>>n>>m;
for(int i; i<n ; i++)
{
for(int j; j<m ; j++)
{
cout<<"Enter the values";
cin>>x;
a[i][j] = x;
}
}
return 0;
}
here it gets error:
main.cpp|6|warning: 'm' is used uninitialized in this function [-Wuninitialized]|
main.cpp|6|warning: 'n' is used uninitialized in this function [-Wuninitialized]|
You can't declare the array unknown size. You must do it dynamically.
#include <iostream>
using namespace std;
int main()
{
int n = 0, m = 0;
//. Get the matrix's size
while (true)
{
cout << "Input the row count: "; cin >> n;
cout << "Input the column count: "; cin >> m;
if (n < 1 || m < 1)
{
cout << "Invalid values. Please retry." << endl;
continue;
}
break;
}
//. Allocate multi-dimensional array dynamically.
int ** mat = new int *[n];
for (int i = 0; i < n; i++)
{
mat[i] = new int[m];
}
//. Receive the elements.
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cout << "Input the element of (" << i + 1 << "," << j + 1 << "): ";
cin >> mat[i][j];
}
}
//. Print matrix.
cout << endl << "Your matrix:" << endl;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cout << mat[i][j] << "\t";
}
cout << std::endl;
}
//. Free memories.
for (int i = 0; i < n; i++)
{
delete[] mat[i];
}
delete[] mat;
return 0;
}
If you like to use stl, it can be simple.
#include <iostream>
#include <vector>
using namespace std;
using ROW = vector<int>;
using MATRIX = vector<ROW>;
int main()
{
int n = 0, m = 0;
MATRIX mat;
cin >> n >> m;
for (int i = 0; i < n; i++)
{
ROW row;
row.resize(m);
for (int j = 0; j < m; j++)
{
cin >> row[j];
}
mat.push_back(row);
}
for (auto & row : mat)
{
for (auto & iter : row)
{
cout << iter << "\t";
}
cout << endl;
}
return 0;
}
Some comments.
Please never use #include<bits/stdc++.h>. This is a none C++ compliant compiler extension
Please do not use using namespace std;. Always use fully qualified names.
For the above to statements you will find thousands of entries here on SO
In C++ you cannot use VLAs, Variable Length Array, like int a[n][m];. This is not part of the C++ language
You should not use C-Style arrays at all. Use std::array or, for your case std::vector.
Use meaningful variable names
Write comments
Always initialize all variables, before using them!!!
And, last but not least. You will not learn C++ on this nonesens "competition - programming" sites.
And one of many millions possible C++ solutions (advanced) could look like that:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main() {
// Read the dimension of the 3d data
if (unsigned int numberOfRows{}, numberOfCoulmns{}; (std::cin >> numberOfRows >> numberOfCoulmns) and (numberOfRows > 0u) and (numberOfCoulmns > 0u)) {
// Define a vector with the requested size
std::vector<std::vector<int>> data(numberOfRows, std::vector<int>(numberOfCoulmns, 0));
// Read all data
std::for_each(data.begin(), data.end(), [&](std::vector<int>& col) mutable
{ auto it = col.begin(); std::copy_n(std::istream_iterator<int>(std::cin), numberOfCoulmns, it++); });
// Show debug output
std::for_each(data.begin(), data.end(), [](std::vector<int>& col)
{std::copy(col.begin(), col.end(), std::ostream_iterator<int>(std::cout, "\t")); std::cout << '\n'; });
}
else std::cerr << "\nError: Invalid input given\n\n";
return 0;
}
If I enter an array , at first the code finds the minimums then I want to put zeroes after all the minimums . For example
given an array = 1,1,3,1,1
As we see 1s are the minimum so the result should be = 1,0,1,0,3,1,0,1,0
CODE
#include <pch.h>
#include <iostream>
int main()
{
int min = 10000;
int n;
std::cout << "Enter the number of elements (n): "; //no of elements in the
std::cin >> n; //array
int *array = new int[2 * n];
std::cout << "Enter the elements" << std::endl;
for (int i = 0; i < n; i++) {
std::cin >> array[i];
if (array[i] > min)
min = array[i];
}
for (int i = 0; i < n; i++) {
if (array[i] == min) { // Not very clear about this
for (int k = n; k > i; k--) // part of the code, my teacher
array[k] = array[k - 1]; //explained it to me , but i
array[i + 1] = 0; // didn't understand (from the
i++; // `for loop k` to be precise)
n++;
}
std::cout << array[i] << ", 0";
}
return 0;
}
But my answer doen't put zeroes exactly after minimums
There are few issues in your code, first of all your min is wrong. I have fixed your code with comments on fixes I have made. Please take a look :
#include "stdafx.h"
#include <iostream>
int main()
{
int min = 10000;
bool found = 0;
int n;
std::cout << "Enter the number of elements (n): "; //no of elements in the
std::cin >> n; //array
int *array = new int[2 * n];
std::cout << "Enter the elements" << std::endl;
for (int i = 0; i < n; i++) {
std::cin >> array[i];
if (array[i] < min) //< instead of >
min = array[i];
}
for (int i = 0; i < n; i++) {
if (array[i] == min)
{
for (int k = n; k > i; k--)
{
array[k] = array[k - 1];
}
array[i + 1] = 0;
i++; //increment i here because you don't want to consider 0 that you have just added above.
n++; //since total number of elements in the array has increased by one (because of 0 that we added), we need to increment n
}
}
//print the array separately
for (int i = 0; i < n; i++)
{
std::cout << array[i];
if (i != n - 1)
{
std::cout << ",";
}
}
return 0;
}
The first issue was in the calculation of min: < instead of >.
Another problem if that you are modifyng the paramers iand ninside the loop. This is rather dangerous and implies to be very cautious.
Another issue was that it should be i++; n++; instead of i--,n--;
Here is the code:
// #include <pch.h>
#include <iostream>
int main()
{
int min = 1000000;
int n;
std::cout << "Enter the number of elements (n): "; //no of elements in the
std::cin >> n; //array
int *array = new int[2 * n];
std::cout << "Enter the elements" << std::endl;
for (int i = 0; i < n; i++) {
std::cin >> array[i];
if (array[i] < min)
min = array[i];
}
for (int i = 0; i < n; i++) {
if (array[i] == min) { // Not very clear about this
for (int k = n; k > i; k--) // part of the code, my teacher
array[k] = array[k - 1]; //explained it to me , but i
array[i + 1] = 0; // didn't understand (from the)
i++;
n++;
}
}
for (int i = 0; i < n; i++) {
std::cout << array[i] << " ";
}
std::cout << "\n";
return 0;
}
I have a code where i should introduce 3 numbers and an multi-dimensional array. I should print all numbers from array that are divisors with 3 numbers from start..
Here's my code:
#include <vector>
#include <iostream>
using namespace std;
int main() {
int r, p, k, nr, n, m, counter=0, temp;
vector <int> numbers;
cout << "Enter value of r, p, k: ";
cin >> r >> p >> k;
cout << "Enter the number of rows and columns: ";
cin >> n >> m;
int T[n][m];
cout << "Enter values: ";
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
cin >> T[i][j];
}
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
for(int a = 0; a < 1; a++) {
numbers.push_back(T[i][j]);
counter++;
}
}
}
for(int f = 0; f < counter; f++) {
if(r%numbers[f]==0 && p%numbers[f]==0 && k%numbers[f]==0) {
cout << numbers[f] << ' ';
}
}
return 0;
}
So, my question is.. how to push in vector numbers that repeats only 1 time.. I mean if in array are 2 the same number, dont print both of them but just one of them.
Thanks in advance.
Use a set: http://en.cppreference.com/w/cpp/container/set
A set does not allow duplicates. For example, if you insert the number 5 more than once, there will still only be one 5 in the set.
First #include<set>.
Then replace vector <int> numbers; with set<int> numbers;
Then replace
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
for(int a = 0; a < 1; a++) {
numbers.push_back(T[i][j]);
counter++;
}
}
}
with
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
numbers.insert(T[i][j]);
Then replace
for(int f = 0; f < counter; f++) {
if(r%numbers[f]==0 && p%numbers[f]==0 && k%numbers[f]==0) {
cout << numbers[f] << ' ';
}
}
with
for (auto i = numbers.cbegin(); i != numbers.cend(); ++i)
if(r % *i == 0 && p % *i == 0 && k % *i == 0)
cout << *i << ' ';
That should do it. You can eliminate the counter variable from the program because numbers.size() gives you the number of objects in the set. Also, your temp variable is not used, so eliminate that as well. Also, note that set is an ordered container, so printing it like this will print the numbers in ascending order.
(Also note that the length of an array such as int arr[3]; must be known at compile time to be strictly valid C++. Here 3 is a literal and so is known at compile time. Asking the user to input the length of the array means that it is not known at compile time.)
After you fill your vector, you can first sort all elements in it and than call std::unique, to remove all duplicates from it.
Try to look references for std::unique and std::sort
Link to the problem in question: http://codeforces.com/problemset/problem/784/F
It's nothing but a sorting problem so I used bubble sort on my array. But when I submit my answer it keeps rejecting on test 1 even though it works just fine when I run it. I made sure I chose the right compiler for my code so that's not the problem. Is there something wrong with my code?
Here's my code:
int arr[10];
/* number of inputs */
int n;
cin >> n;
/* inputting n numbers to the array */
for (int i = 0; i < n; ++i)
cin >> arr[i];
/* bubble sort array */
for (int i = 0; i < n - 1; ++i) {
for (int j = 0; j < n - i - 1; ++j) {
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j + 1] = temp;
}
}
}
/* printing all the numbers in array */
for (int i = 0; i < n; ++i) {
cout << arr[i] << ' ';
}
cout << endl;
You do not need to implement everything your self, just use the standard library:
// number of inputs
int n;
std::cin >> n;
// Vector storing the numbers
std::vector<int> v(n);
// Input n numbers
for (int i = 0; i < n; ++i)
{
std::cin >> arr[i];
}
// Sort the numbers
std::sort(v.begin(), v.end());
// Removed all duplicates (all numbers are unique)
auto last = std::unique(v.begin(), v.end());
v.erase(last, v.end());
// Print all the numbers
for (int i : v)
std::cout << i << ' ';
std::cout << std::endl;
I am trying to create some test cases for my 'minimum dot product' problem. I want 10 test cases , each generating different set of values for both vector a and b.
The Problem is that even after using srand( time( NULL ) ) though a new input is generated every time I compile and run the code but that same input is used for all the 10 test cases.
#include <algorithm>
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using std::vector;
void sort_asc(vector<int> &manav, int sizes)
{
int temp = 0;
for (int i = 0; i<sizes; i++)
{
for (int j = i + 1; j<sizes; j++)
{
if (manav[i] > manav[j])
{
temp = manav[i];
manav[i] = manav[j];
manav[j] = temp;
}
}
}
std::cout << "b in asc order : ";
for (int i = 0; i<sizes; i++)
{
std::cout << manav[i] << " ";
}
std::cout << std::endl;
}
void sort_desc(vector<int> &manav, int sizes)
{
int temp = 0;
for (int i = 0; i<sizes; i++)
{
for (int j = i + 1; j<sizes; j++)
{
if (manav[i] < manav[j])
{
temp = manav[i];
manav[i] = manav[j];
manav[j] = temp;
}
}
}
std::cout << "a in desc : ";
for (int i = 0; i<sizes; i++)
{
std::cout << manav[i] << " ";
}
std::cout << std::endl;
}
long long min_dot_product(vector<int> a, vector<int> b, int sizes) {
long long result = 0;
sort_desc(a, sizes);
sort_asc(b, sizes);
for (size_t i = 0; i < sizes; i++) {
result += a[i] * b[i];
}
return result;
}
int main() {
srand(time(NULL));
/*
std::cin >> n;
vector<int> a(n), b(n);
for (size_t i = 0; i < n; i++) {
std::cin >> a[i];
}
for (size_t i = 0; i < n; i++) {
std::cin >> b[i];
}
*/
//================================================================ TESTING =========================================================================
int z = 0;
int n = (rand() % 10) + 1; // generating the size of the vectors [1-10]
std::cout << "n = " << n << "\n";
vector<int> a;
vector<int> b;
while (z != 10) {
for (int i = 0; i < n; ++i)
{
int p = (rand() % 10) - 5;
a.push_back(p); // input values [-5,4] in 'a'
}
std::cout << "Unsorted Vector a = ";
for (int i = 0; i<n; i++)
{
std::cout << a[i] << " ";
}
std::cout << std::endl;
for (int i = 0; i < n; ++i)
{
int q = (rand() % 10) - 5;
b.push_back(q); // inputing values [-5,4] in 'b'
}
std::cout << "Unsorted Vector b = ";
for (int i = 0; i<n; i++)
{
std::cout << b[i] << " ";
}
std::cout << std::endl;
std::cout << "min_dot_product = " << min_dot_product(a, b, n) << std::endl;
z++;
}
return 0;
}
I somehow want to generate a different set of values for vector a and b for all of the 10 test cases every time I run the code.
I have tried srand(i) within the respective for loops before pushing the value in vectors but its not working for me, also reusing srand( time( NULL ) ) within the for loops is not gonna help either. Is there some other simple way I can achieve this?
The problem is you never clear out the vector on each iteration. Since you don't all of the new random numbers you generate are being added to the end of the vector and you ignore them since n never changes.
What you need to do is add
a.clear();
b.clear();
to the end of the while loop. This will clear out the vectors and then when you start the next iteration the new random numbers will get added into the part of the vector you use in your functions.
You could also set the vector the proper size and then use [] to access the elements. This way you would just overwrite the previous values and you would not have to call clear()
vector<int> a(n);
vector<int> b(n);
//...
for (int i = 0; i < n; ++i)
{
a[i] = (rand() % 10) - 5;
b[i] = (rand() % 10) - 5;
}
I put both assignments in the same for loop to save space. You can do this in two separate loops but it is not needed.