I want to create an array and raise 2 to every element in that array and store it as new array arr2. Here is my code
#include <iostream>
using namespace std;
int main(){
int arr1[7] = {1, 2, 3, 4, 5, 6, 7};
auto arr2 = 2 ** arr1;
cout << arr2 << endl;
}
But, it prints only the first element, it does not print the whole array. Why? So, basicaly, what I did here is I created arr1 with elements {1,2,3,4,5,6,7} and then I want arr2 to be
[2, 4, 8, 16, 32, 64, 128]
but for some reason it prints only the first element of array, it prints 2, but I want it to print all elements. Notice that 2 ** arr1 is the line where I am raising 2 to power (using exponentiation operator, i think it is how you call it if I'm not wrong) and then it should store array at array2.
What is wrong and why does it print only the first element instead all the elements?
** is not an exponentation operator. C++ is not Fortran.
You have multiplied 2 by the first element of arr: your statement is equivalent to int arr2 = 2 * arr1[0];. What you have entered is perfectly legal C++ (consisting of multiplication and pointer dereference), and the use of auto is adding to the obfuscation.
This statement
auto arr2 = 2 ** arr1;
is equivalent to
auto arr2 = 2 * *arr1;
Array designators in expressions are converted (with rare exceptions) to pointers to their first elements.
So the above statement can be rewritten like
auto arr2 = 2 * *( &arr1[0] );
As the first element of the array arr1 is equal to 1 then you have
auto arr2 = 2 * 1;
The expression 2 * 1 has the type int.
So as result the statement can be just rewritten like
int arr2 = 2;
There is no such operator as ** in C++. Instead you have to use standard function pow.
You can do the task either by writing an appropriate loop manually or using for example the standard algorithm std::transform.
Here is a demonstrative program
#include <iostream>
#include <cmath>
#include <algorithm>
#include <iterator>
int main()
{
int arr1[] = { 1, 2, 3, 4, 5, 6, 7 };
int arr2[sizeof( arr1 ) / sizeof( *arr1 )];
std::transform(std::begin(arr1), std::end(arr1),
std::begin(arr2),
[](int x) { return pow( 2, x ); });
for (int x : arr1) std::cout << x << ' ';
std::cout << std::endl;
for (int x : arr2) std::cout << x << ' ';
std::cout << std::endl;
return 0;
}
Its output is
1 2 3 4 5 6 7
2 4 8 16 32 64 128
The simplest way to do what you want can be something like this.
#include<iostream>
#include<math.h>
using namespace std;
int main(){
int arr1[7] = {1,2,3,4,5,6,7}, arr2[7];
for(int i = 0; i<7; i++){
arr2[i] = pow(2, arr1[i]); //arr2 will be created.
cout<<arr2[i]<<" "; //Show arr2.
}
}
Related
#include <iostream>
using namespace std;
int main()
{
const int ARRAY_SIZE = 10;
int value[ARRAY_SIZE] = { 1, 2, 3, 4, 3, 4, 2, 3, 5, 6};
int value2[100];
for (int i = 0; i < ARRAY_SIZE; i++)
{
for (int j = i + 1; j <= ARRAY_SIZE; j++)
{
if (value[i] == value[j])
{
cout << value[i] << " ";
}
}
}
return 0;
}
The output is
2 3 3 4 3
How can I make the output become 2 3 4 ?
Edit: I'm trying to print all numbers appearing more than once in the value array
I think I should create one more array to store value, but I stuck with it and don't know how to do it.
It helps considerably to sort your array. Then you only need two indices:
a write index, starting at 0
a read index, starting at 1
Loop over your array using the read index. For every array[read] that has a duplicate value at array[read-1], IFF that value also does not exist at array[write], then copy it over and increment your write index.
Finally, the new length of your data is equal to your write index.
The basic idea is this: if I have a sorted list of values:
1 3 3 4 5 5 5 7 7 9
Then I can easily see if a value is a duplicate or not by comparing the current (read) with the previous.
┌────┐
1 3 3 │4 5│ 5 5 7 7 9 -- not duplicates
└────┘
↑
┌────┐
1 3 3 4 │5 5│ 5 7 7 9 -- duplicate values
└────┘
↑
The only remaining trick is to make just a single copy of that value to the write index, which we can do by simply looking at the last thing we wrote.
You can use a std::map to count the number of times a value is in the array. If the number appears 2 or more times, then print it.
#include <iostream>
#include <map>
int main()
{
const int ARRAY_SIZE = 10;
int value[ARRAY_SIZE] = { 1, 2, 3, 4, 3, 4, 2, 3, 5, 6};
std::map <int, int> mp;
for(int i : value)
++mp[i];
for(const auto& p : mp)
if(p.second > 1)
std::cout << p.first << ' ';
}
Link.
I was attempting to solve this question on some website where you have the find the kth smallest value in c++ so I came up with:
#include <bits/stdc++.h>
using namespace std;
int kthSmallest(int arr[], int l, int r, int k) {
// l is the first index
// r is the index of the last element (size - 1)
// k is the kth smallest value
set<int> s(arr, arr + r);
set<int>:: iterator itr = s.begin();
advance(itr, (k - 1));
return *itr;
}
int main() {
int arr[] = {7, 10, 4, 20, 15};
cout << kthSmallest(arr, 0, 4, 4);
return 0;
}
This shows the output of 20 instead of 15 which is the right answer and I cannot figure out what I did wrong here.
The 2nd argument of the constructor of std::set should be an iterator for an element next to the last element, not one for the last element.
Therefore, you are operating with a set whose members are {7, 10, 4, 20}.
The line
set<int> s(arr, arr + r);
should be
set<int> s(arr, arr + r + 1);
or (to match the comment)
set<int> s(arr + l, arr + r + 1);
The range in this statement
set<int> s(arr, arr + r);
is specified incorrectly when r is equal to 4 for this array
int arr[] = {7, 10, 4, 20, 15};
that has 5 elements. It means that 15 is not present in the range [7, 10, 4, 20]. You have to specify the parameter r equal to 5 that is to the number of elements in the array instead of 4.
Also the parameter l is not used in the function.
And you need to check whether the value of k is not greater than the value of r calling the function std::advance.
Also pay attention to that the array can have duplicated values. In this case the function can return an incorrect value.
So in general your function is incorrect and unsafe.
Instead of returning an object of the type int you should return either an iterator that points to the target object in the array or to the end of the range or the index of the target element..
With your approach you should use std::multiset instead of std::set. And the value of k should start from 0 as all indices in C++. Otherwise calling the function with the value of k equal to 0 you will get undefined behavior.
Here is a demonstration program.
#include <iostream>
#include <functional>
#include <set>
#include <iterator>
size_t kthSmallest( const int arr[], size_t n, size_t k )
{
if ( not ( k < n ) ) return n;
std::multiset<std::reference_wrapper<const int>> s;
for ( size_t i = 0; i < n; i++ )
{
s.insert( std::ref( arr[i]) );
}
auto it = std::next( std::begin( s ), k );
size_t result = std::distance( arr, &it->get() );
return result;
}
int main()
{
int arr[] = {7, 10, 4, 20, 15};
const size_t N = sizeof( arr ) / sizeof( *arr );
for ( size_t i = 0; i < N; i++ )
{
std::cout << i << ": " << arr[kthSmallest( arr, N, i )] << '\n';
}
return 0;
}
The program output is
0: 4
1: 7
2: 10
3: 15
4: 20
I'm having a trouble for a long time in a problem related to array and loops.
Assume an array like:
int arr[] = {2, 3, 5, 3, 6, 8, 10, 1, 9};
The program should print the expected column as shown (note that the table is an idea for clarification of what I actually want to achieve):
max: expected arr[index] for max
------------------------------------
2 : 3 5 value of: arr[0]
3 : 6, 8, 10 value of: arr[3]
1 : 9 value of: arr[7]
This is what I've tried so far:
#include <iostream>
int main(void) {
int arr[] = {2, 3, 5, 3, 6, 8, 10, 1, 9};
int max = arr[0];
int i = 1, it = i;
for (; i <= max; i++) {
if (i == max) {
std::cout << arr[i] << std::endl;
max = arr[it + 1]; // when loop end has come, increment max to next element value
it = i + 2; // incrementing iterator by 2 next element position (after max)
} else {
std::cout << arr[i] << ' '; // when loop is executing
}
}
return 0;
}
What it actually prints which is unexpected V/S what it should print:
3 5 | 3, 5
3 6 8 | 6, 8, 10
10 1 9 | 1, 9
10 | <nothing>
The program is about to get max value and print the next elements until max value reaches the number of element position.
Where the problem's occurring and how to fix it? Please let me know.
So I rewrote your code, frankly I couldn't follow it, it seems a bit confused with variable names that seem a bit off.
Here's some working code. The two key concepts in the code are the place where each block starts (the variable start) and the size of each block (the variable count). Plus I use the size of the whole array sizeof(arr)/sizeof(arr[0]) to terminate the outer loop. Something that wasn't present in your code. If you are using C++17, you can use std::size(arr) instead of sizeof.
int main(void) {
int arr[] = {2, 3, 5, 3, 6, 8, 10, 1, 9};
size_t start = 0;
while (start < sizeof(arr)/sizeof(arr[0]))
{
int count = arr[start];
for (int i = 0; i < count; ++i)
{
std::cout << arr[start + i + 1] << ' ';
}
std::cout << std::endl;
start += count + 1;
}
}
The output is
3 5
6 8 10
9
I need to add either +0.25 or -0.25 to all elements within an array. Here is what I have so far. Any help would be appreciated.
int main() {
double i;
// Arrays
double x[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
double x2[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for(i=1; i<=10; i++) {
const double pM[2] = {-1, 1};
int randoid = rand() % 2;
for(i=1; i<=10; i++){
x2[i] = x[i] + pM[randoid]*0.25; //Error Line
}
}
cout << x;
cout << x2;
}
I get this error at the marked line: "invalid types 'double[10][double] for array subscript"
The problem is that i is a double. Then you write x2[i].
It's not a very good error message; however with the [] operator, one of the operands must be a pointer and the other must be an integer. There is no implicit conversion of floating-point to integer when using this operator.
To fix this change double i; to int i;
Another issue is that your code accesses out of bounds of the arrays. double x2[10] means that there are 10 elements whose indices are 0 through 9. But your loop tries to write to x2[10]. This causes undefined behaviour, which could explain your strange output.
There is also a potential logic error. Maybe you meant to use a different variable for the inner loop than the outer loop. As it stands, the inner loop will take i to 11 (or 10 if you fix the code) and then the outer loop will be complete and not execute any more iterations.
Based on your description though, perhaps you only meant to have one loop in the first place. If so, remove the outer loop and just leave the contents there.
Also you do not need two separate arrays, you could just perform the addition in-place.
Regarding the output, cout << x and cout << x2 will output the number of the memory address at which the array is located. To output the contents of the array instead you will need to write another loop, or use a standard library algorithm that iterates over containers.
I see 3 issues -
Change the type of i to int.
x and x2 are arrays of size 10. You need to loop from i =
0 to i = 9. But you are looping from i = 1 to i = 10. x[10]
is out of bounds since arrays are 0 indexed.
cout << x - This is a wrong way to print an array. You need
to loop through the array and print - e.g. -
for(i = 0; i < 10; i++)
cout << x[i] << " ";
Try this, it works, I converted to C
int main( )
{
int i = 0;
// Arrays
double x[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
double x2[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for ( i = 1; i < 10; i++ )
{
const double pM[2] = { -1, 1 };
int randoid = rand( ) % 2;
for ( i = 1; i <= 10; i++ )
{
x2[i] = x[i] + pM[randoid] * 0.25; //Error Line
printf( "\nx[%d]==%2.2f", i, x[i] );
printf( "\nx2[%d]==%2.2f", i, x2[i] );
}
}
}
I'm trying to make a recursive program that sums an array or a list of numbers.
Using visual studio 2013, C++ console application.
My 1st question is:
Now I know how many numbers I have and I know the size of my array. How can I program it the way that don't know the numbers in advance, like while it's calculating the numbers there are still new numbers adding up, with the least space usage?
My 2nd question is that:
How can i improve the program that still works recursively and its time and space usage be optimal?
Here is my code:
// summing a list of number.cpp
#include "stdafx.h"
#include "iostream"
int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0, i = 0;
int sumarray(int i){
if (i < 9){
sum += array[i];
i++;
sumarray(i);
}
else
return sum;
}
int main(){
std::cout << "sum is ::: " << sumarray(i);
getchar();
}
I hope you'll stop writing functions that depend on global variables to work when they can be easily made to work only with the input they have been provided.
Here's a version that works for me.
#include <iostream>
int sumarray(int array[], int i)
{
if ( i <= 0 )
{
return 0;
}
return sumarray(array, i-1) + array[i-1];
}
int main()
{
int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
std::cout << "sum is : " << sumarray(array, 0) << std::endl;
std::cout << "sum is : " << sumarray(array, 5) << std::endl;
std::cout << "sum is : " << sumarray(array, 10) << std::endl;
}
Output:
sum is : 0
sum is : 15
sum is : 55
If i >= 9, your function does a return sum;.
(that is fine and good)
Where does your function return if i < 9???
if (i < 9){
sum += array[i];
i++;
sumarray(i); // I see no return statement here!!
}
Basically, if you call sumarray(3), there is no return statement that gets hit.
In your program, there is a global variable called i.
There is also a local parameter to the function also called i.
The local variable shadows the global variable, so there is no clear purpose to the global i.
I'd do it like this:
int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Pass in the current index, and the size of the array
int sumarray(int i, int sz)
{
if (sz == 0)
{
return 0;
}
return array[i] + sumarray(i+1, sz-1);
}
int main(){
std::cout << "sum is ::: " << sumarray(0, 10);
// Start at the beginning (index 0)
// Run for 10 elements.
getchar();
}
The first recursive call will be to sumarray(1,9); then to sumarray(2,8);... when finally sumarray(10,0) is called, it will return 0.
A function to sum the elements of an array would normally accept the array as an argument. In that case, as a practical matter it must also accept the size of the array. Something like this:
int sumarray(int a[], size_t size) {
A signature like that furthermore gives you access to better recursive approaches. In particular, you could recursively compute the sum of the first and second halves of the array, and return their sum:
size_t midpoint = size / 2;
return sumarray(a, midpoint) + summaray(a + midpoint, size - midpoint);
That's not a complete solution: you need a termination condition (when size is less than 2). Putting that in and finishing off the function are left as an exercise for you, since you'll learn better if you have to put some work into it yourself.
That approach limits the recursion depth and thus stack size (memory overhead) to be proportional to the logarithm of the array size, though it still involves total numbers of function calls and integer additions proportional to the array size. I don't think you can achieve better asymptotic space or time complexity with a recursive algorithm. (A non-recursive algorithm for this task requires only a fixed number of function calls and and a fixed amount of memory overhead, however.)
here is a working C++ code in Qt, which i wrote - Good Luck
I added some debug points outputs to make its understanding clearer
#include <QCoreApplication>
#include <QDebug>
int sum=0;
int sumrec(int *array,int n)
{
if (n>=0)
{
int element=*(array+n); // note *(array+n) -> moving the pointer
// *array+n -> this is adding n to the pointer data (wrong)
// what is array ?
qDebug() << " element value " << *(array+n) << " at n=" << n << " array address = " << array;
n--;
sum=sum+element;
qDebug() << "sum = " << sum;
sumrec(array,n);
return sum;
}
else
{
return 0;
}
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
int A[10]={12,13,14,15,16,17,18,19,20,11};
int b=sumrec(&A[0],9);
qDebug() << "answer = " << b;
//return a.exec();
}
here is the output of the terminal
element value 11 at n= 9 array address = 0x7fff5fbffb78
sum = 11
element value 20 at n= 8 array address = 0x7fff5fbffb78
sum = 31
element value 19 at n= 7 array address = 0x7fff5fbffb78
sum = 50
element value 18 at n= 6 array address = 0x7fff5fbffb78
sum = 68
element value 17 at n= 5 array address = 0x7fff5fbffb78
sum = 85
element value 16 at n= 4 array address = 0x7fff5fbffb78
sum = 101
element value 15 at n= 3 array address = 0x7fff5fbffb78
sum = 116
element value 14 at n= 2 array address = 0x7fff5fbffb78
sum = 130
element value 13 at n= 1 array address = 0x7fff5fbffb78
sum = 143
element value 12 at n= 0 array address = 0x7fff5fbffb78
sum = 155
answer = 155
In C++ you have all the tools to do that in a very simple, readable and safe way. Check out the valarray container:
#include <iostream>
#include <valarray>
int main () {
std::valarray<int> array{1,2,3,4,5,6,7,8,9,10};
std::cout << array.sum() << '\n';
return 0;
}