Can we add an integer to an array in c++ - c++

#include <bits/stdc++.h>
using namespace std;
/*Prototype for utility functions */
void printArray(int arr[], int size);
void swap(int arr[], int fi, int si, int d);
void leftRotate(int arr[], int d, int n)
{
/* Return If number of elements to be rotated
is zero or equal to array size */
if(d == 0 || d == n)
return;
/*If number of elements to be rotated
is exactly half of array size */
if(n - d == d)
{
swap(arr, 0, n - d, d);
return;
}
/* If A is shorter*/
if(d < n - d)
{
swap(arr, 0, n - d, d);
leftRotate(arr, d, n - d);
}
else /* If B is shorter*/
{
swap(arr, 0, d, n - d);
leftRotate(arr + n - d, 2 * d - n, d); /*This is tricky*/
}
}
/*UTILITY FUNCTIONS*/
/* function to print an array */
void printArray(int arr[], int size)
{
int i;
for(i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
/*This function swaps d elements starting at index fi
with d elements starting at index si */
void swap(int arr[], int fi, int si, int d)
{
int i, temp;
for(i = 0; i < d; i++)
{
temp = arr[fi + i];
arr[fi + i] = arr[si + i];
arr[si + i] = temp;
}
}
// Driver Code
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7};
leftRotate(arr, 2, 7);
printArray(arr, 7);
return 0;
}
// This code is contributed by Rath Bhupendra
I found this code on the geek for geeks website. The code is used to rotate the elements of an array. It is mentioned as block swap algorithm in the website, my questions are:
Can we add integers to an array in c++ as given in the else part of the left rotate function while passing the arguments (arr+n-d)?
How can we add integers to an array?
I tried adding an integer to an array in an online compiler and it didn't work. But the above code works perfectly giving the desired output 34567.
The link to the website is https://www.geeksforgeeks.org/block-swap-algorithm-for-array-rotation/.

Can we add integers to an array in c++ as given in the else part of the left rotate function while passing the arguments (arr+n-d)?
How can we add integers to an array?
The answer is you can't, and that's not what's happening here.
int arr[] argument decays to a pointer to the first element of the array. It's the same as having int* arr so what you are doing in arr + n - d is simple pointer arithmetic.
The pointer will be moved n - d positions relative to the position it's at before the expression is evaluated.
Supposing the result of n - d is 4, and arr is pointing to the beginning of the array passed as an argument, that is to &arr[0] (in array notation) or arr + 0 (in pointer notation), which is where it's pointing to in its inicial state, you'll have arr + 4 or &arr[4], after the evaluation, the expression provides access to the address of index 4 (the 5th element of the array). To access the value within that address you'd use *(arr + 4) or arr[4].
On a side note I wouldn't advise the use of geeksforgeeks.com to learn C++, or any other language, for that matter, this should be done by reading a good book.

A function parameter having an array type is adjusted by the compiler to pointer to the array element type. That is these two function declarations are equivalent and declare the same one function.
void leftRotate(int arr[], int d, int n);
and
void leftRotate(int *arr, int d, int n);
You even may write for example
void leftRotate(int arr[100], int d, int n);
void leftRotate(int arr[10], int d, int n);
void leftRotate(int arr[1], int d, int n);
Again these declarations declare the function
void leftRotate(int *arr, int d, int n);
So within the function this expression
arr + n - d
uses the pointer arithmetic applied to the pointer arr.
For example the expression arr + 0 is equivalent to arr and points to the first element of the array. The expression arr + n points to the n-th element of the array.
Here is a demonstrative program where there is used the pointer arithmetic to output elements of an array in a loop.
#include <iostream>
int main()
{
int a[] = { 1, 2, 3, 4, 5 };
for ( size_t i = 0; i < sizeof( a ) / sizeof( *a ); i++ )
{
std::cout << *( a + i ) << ' ';
}
std::cout << '\n';
return 0;
}
The program output is
1 2 3 4 5
In the expression *( a + i ) the array designator a is implicitly converted to pointer to its first element.
Here is one more demonstrative program that shows that a function parameter having an array type is adjusted by the compiler to pointer to the array element type.
#include <iostream>
#include <iomanip>
#include <type_traits>
const size_t N = 100;
void f( int a[N] )
{
std::cout << "\nin function\n";
std::cout << "sizeof( a ) = " << sizeof( a ) << '\n';
std::cout << "a is a pointer " << std::boolalpha <<std:: is_same<decltype( a ), int *>::value << '\n';
}
int main()
{
int a[N];
std::cout << "In main\n";
std::cout << "sizeof( a ) = " << sizeof( a ) << '\n';
std::cout << "a is an array " << std::boolalpha <<std:: is_same<decltype( a ), int [N]>::value << '\n';
f( a );
return 0;
}
The program output is
In main
sizeof( a ) = 400
a is an array true
in function
sizeof( a ) = 8
a is a pointer true

Related

Garbage value getting displayed on printing 2d array using row order

I am using gcc compiler on ubuntu 16 , when I am printing value garbage value is getting displayed
#include <bits/stdc++.h>
int Arrayprint(int r, int l, unsigned int* q)
{
r = 3;
l = 4;
for (int i = 0; i < r; i++) {
for (int j = 0; j < l; j++) {
cout << *(q + sizeof(unsigned int) * (i * l + j)); //Garbage getting diplay
cout << *(q + i + j); //this working
cout << "\t";
}
}
cout << "size of unsigned int : " << sizeof(unsigned int); //4
cout << "size of int : " << sizeof(int); //4
}
int main()
{
unsigned int image[R][L] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 } };
unsigned int* q = (unsigned int*)image;
Arrayprint(R, L, q);
}
From what I can tell, you understand at a low level that the address of the ith element of an array of T is base + sizeof(T) * i. That's correct, and it's good that you know that.
However, C and C++ handle this for you already. When you say q + i or q[i], it's actually compiling that into q + sizeof(T)*i anyway (with the latter also dereferencing the result).
So when you say q[sizeof(int)*i], that's actually compiling into *(q + sizeof(int)*sizeof(int)*i), which is clearly not what you wanted.
Thus, the index in the array you actually access is off by a factor of sizeof(int) and results in an out of bounds error, which is where your strange numbers are coming from.
I am using gcc compiler on ubuntu 16 , when I am printing value
garbage value is getting displayed
Instead of trying to fix what's broken in your raw array arimethics, consider using the standard containers:
#include <iostream>
#include <array>
constexpr size_t R = 3;
constexpr size_t L = 4;
using image_t = std::array<std::array<unsigned int, L>, R>;
void Arrayprint(const image_t& q) {
// range based for loops for convenience
for(auto& row : q) { // get references to each row
for(unsigned int colval : row) { // get the column values
std::cout << colval << "\t"; // print the values
}
std::cout << "\n";
}
}
int main() {
image_t image = {{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}};
Arrayprint(image);
}
Output:
1 2 3 4
5 6 7 8
9 10 11 12

Recursively counting a number of values that satisfies a condition and return that number

I need to count how many cubes of values between a and b (2 and 9 in this example) end with numbers between 2 and 5. Everything has to be done with recursion.
The output of this code is
part c = recc = 4
32767
0
It does not make sense to me. It calculates the value of n correctly, but then once asked to return it, returns either 0 or 32767, as if it was not defined.
Can anyone pinpoint the issue?
#include <iostream>
#include <string>
using namespace std;
void partb(int a, int b){
if(a<=b){
int p = (a*a*a)%10;
else if(p>=2 && p<=5){
cout<<a*a*a<<" ";
}
partb(a+1, b);
}
}
int recc(int n, int a, int b){
int p = (a*a*a)%10;
if(a>b){
cout<<"recc = " << n << endl;
return n;
}
else if(a<=b){
if(p>=2 && p<=5){
n++;
}
recc(n, a+1, b);
}
}
int partc(int a, int b){
int n = recc(0, a, b);
cout<<endl<< "part c = " << recc(0, a, b) << endl;
return n;
}
int main(){
int n=partc(2,9);
cout << n << endl;
return 0;
}
Not all control paths in your function return a value, so you were getting undefined behaviour when using the return value.
Now, this wasn't helped by the fact that the function itself is needlessly complicated. Let's rewrite it to use common practice for recursion:
int recc(int a, int b)
{
if (a > b) return 0;
int p = (a*a*a)%10;
int n = (p>=2 && p<=5) ? 1 : 0;
return n + recc(a+1, b);
}
Now your function is simpler. The recursion termination condition is right at the top. The function then decides whether a will contribute 1 or 0 to the count. And finally you return that value plus the count for a smaller range.
Notice how return n + recc(a+1, b); has broken the problem into a simple local solution combined with the recursive result of a reduced scope.
The invocation becomes simpler too, because you no longer have to pass in a redundant argument:
int partc(int a, int b)
{
int n = recc(a, b);
cout << endl << "part c = " << n << endl;
return n;
}

candidate function not viable: expects an l-value for 3rd argument

Calculate nth power of P (both p and n are positive integer) using a recursive function myPowerFunction(int p, int n, int &currentCallNumber). currentCallNumber is a reference parameter and stores the number of function calls made so far. myPowerFunction returns the nth power of p.
int myPowerFunction(int p, int n, int &z)
{
z++;
if(n==1)return p;
else if(n==0)return 1;
else if(n%2==0)return myPowerFunction(p,n/2,z)*myPowerFunction(p,n/2,z);
else return myPowerFunction(p,n/2,z)*myPowerFunction(p,n/2,z)*p;
}
int main()
{
cout << myPowerFunction(3,4,1);
}
You need a variable to pass as the third argument in main_program. You can't pass a constant as a non-const reference.
int count = 0;
std::cout << myPowerFunction(3, 4, count) << 'n';
std::cout << count << '\n';
Third parameter expects a lvalue, so you cannot pass numeric constant there, so possible solution can be:
int z = 1;
cout<< myPowerFunction(3,4,z);
or better to create a function that calls recursive one:
int myPowerFunction(int p, int n)
{
int z = 1;
return myPowerFunction(p,n,z);
}
In myPowerFunction(3,4,1) the literal 1 cannot be passed to a non const reference as it is a prvalue [basic.lval]. You need to store the value into a variable and then use that variable when calling the function.
int z = 0;
std::cout << myPowerFunction(3, 4, z);
You don't have to give a reference as parameter as many here state.
But yes, your input for z cannot be modified as it comes from read-only memory. Treat the input for z as const, copy z internally and give the copy as reference. Then your desired usage works:
int myPowerFunction(int p, int n, const int &z) // z is now const !
{
int _z = z + 1; // copy !
if (n == 1) return p;
else if (n == 0) return 1;
else if (n % 2 == 0) return myPowerFunction(p, n /2 , _z) * myPowerFunction(p, n / 2, _z);
else return myPowerFunction(p, n / 2, _z) * myPowerFunction(p, n / 2, _z) * p;
}
int main()
{
std::cout << myPowerFunction(3, 4, 1);
}

How to return multiple values from a function in c++?

I know this has been asked before but I still don't know how to do it. I Have to write a function which returns the number of times 2, 5 and 9 appear in an array.
include <iostream>
int twofivenine(int array[], int n)
{
int i = 0;
int num_2 = 0;
int num_5 = 0;
int num_9 = 0;
for ( i = 0; i < n; i++ ){
switch(){
case (array[i] == 2):
num_2++;
case (array[i] == 5):
num_5++;
case (array[i] == 9):
num_9++;
}
}
return ;
}
int main()
{
int array[6] = {2,2,3,5,9,9};
std::cout << "2: 5: 9:" << twofivenine(array, 6) << std::endl;
}
I'm just not sure how to return (num_2, num_5, and num_9)
Can use std::tuple
std::tuple<int, int, int > twofivenine( int array[], int n)
{
//
return make_tuple( num_2, num_5, num_9 );
}
auto x = twofivenine( array, 6 );
std::cout << std::get<0>( x ) << '\n'
<< std::get<1>( x ) << '\n'
<< std::get<2>( x ) << '\n' ;
There are a number of ways to approach this problem.
Pass the values by reference. You can call a function such as the following:
Example:
void foo(int &a, int &b, int &c)
{
// modify a, b, and c here
a = 3
b = 38
c = 18
}
int first = 12;
int second = 3;
int third = 27;
foo(first, second, third);
// after calling the function above, first = 3, second = 38, third = 18
Store the values to return in a data type. Use a data type from the standard library such as std::vector, std::set, std::tuple, etc. to hold your values then return that entire data member.
Example:
std::vector<int> foo()
{
std::vector<int> myData;
myData.pushBack(3);
myData.pushBack(14);
myData.pushBack(6);
return myData;
}
// this function returns a vector that contains 3, 14, and 6
Create an object to hold your values. Create an object such as a struct or a class to hold your values and return the object in your function.
Example:
struct myStruct
{
int a;
int b;
int c;
};
myStruct foo()
{
// code here that modifies elements of myStruct
myStruct.a = 13;
myStruct.b = 2;
myStruct.c = 29;
return myStruct;
}
// this function returns a struct with data members a = 13, b = 2, and c = 29
The method you choose will ultimately depend on the situation.
Pass objects in by reference, ie
void twofivenine(int array[], int n, int &num_2, int &num_5, int &num_9)
{
//Don't redeclare num_2...
}
Call like so:
int num_2, num_5, num_9;
twofivenine(array, 6, num_2, num_5, num_9);
Return a struct by value which has the counts as the data members:
struct Result {
int num_3;
int num_5;
int num_9;
};
Result twofivenine(int array[], int n)
{
.
.
.
return Result{num_2, num_5, num_9};
}
and in main:
Result result(twofivenine(array, 6));
std::cout << "2: " << result.num_2 << "5: " << result.num_5 << "9: " << result.num_9 << std::endl;
Most compilers will do RVO (return-value-optimization) where the twofivenine function will directly write to the result struct avoiding a struct copy.

multiplying two large numbers in C / C++

I was trying to come up with the solution for that ... two large numbers, a and b are represented by char[] or char* and the goal is to multiply them into a third pointer, char* c:
void multiply( const char* a, const char* b ){
int len_a = strlen( a );
int len_b = strlen( b );
int* c = new int[ len_a + len_b];
memset( c, 0, sizeof(int) * ( len_a + len_b ));
for( int i = len_a - 1; i >= 0; i-- ){
for( int j = len_b - 1; j >= 0; j-- ){
c[ i + j + 1 ] += ( b[ j ] - '0') * ( a[ i ] - '0' );
}
}
for( int i = len_a + len_b; i >= 0; i-- ){
if( c[ i ] >= 10 ){
c[ i - 1 ] += c[ i ] / 10;
c[ i ] %= 10;
}
}
cout << a << " * " << b << " = " << c << endl;
delete[] c;
}
I wrote the above function to do this operation for me ... however, when I use the inputs:
int main( void ){
const char* a = "999";
const char* b = "99999";
multiply( a, b );
// I expect the answer to be 1 and 6
// profit = 0.92
return 0;
}
I got:
999 * 99999 = 0x100100080
Why am I getting the memory address and not the actual number?
Thanks!
Because c is an int pointer and the stream operator for cout will print a memory address if passed such a pointer. To get the value you need to dereference the pointers with e.g. *c. You'll probably need to write a loop to print the whole "string" of integers.
cout << a << " * " << b << " = ";
for( int i = 0; i < len_a + len_b; i++ ){
cout << c[ i ];
}
cout << endl;
will yield the desired result ...
Your logic is correct.
Just a quick reminder: When you create an integer pointer and want to use it as an array, it points to "the first element of the array" therefore when you print it, you see the address of the first element of the array c, which is "0x100100080" in your case.
To print the number (characters) stored in c you need to de-reference the pointer, i.e., print the elements in the array one after another. Or alternatively you can convert your array into a number and print it at once. For the latter, please refer to: How to convert array of integers into an integer in C?.
For printing the characters one by one you could replace
std::cout<<c;
with the following code:
int n=strlen(c);
for(int i=0; i<n; i++) {
std::cout<<c[i];
}
This will print the number.
std::ostream (of which type std::cout is) doesn't have any overloaded operators specifically for int*, thus it falls back to the void* overload which simply outputs the pointer value in an implementation-defined manner.
Furthermore, it wouldn't be possible for an int* overload to determine that the pointer points to an array, and further still, how many elements such an array would have.
for(c++14)
we can use boost libarary..
#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
namespace mp = boost::multiprecision;
int main()
{
mp::cpp_int s1("12368123681263817263863821638126328136218362182");
mp::cpp_int s2("345897937325785470923092923709887329092470423707534025");
mp::cpp_int S=s1*s2;
std::cout << S << '\n';
}