I am writing a simple program to calculate 6^5 using a function. Here's my code
#include <iostream>
using namespace std;
int raiseToPower(int &base, int exponent){
for (int i = 1; i < exponent; i = i + 1){
base= base * base;
}
return base;
}
int main() {
int base = 6;
cout << "6^5 is " << raiseToPower(base, 5)<< endl;
return 0;
}
The result is
6^5 is -683606016
instead of 7776
Can you guys explain to me why I got this result?
I am not looking for another way to write this code. I know there are simpler ways but I am trying to understand what went wrong
Why are you using pass by reference. Setting as much const as possible reduces the odd of making mistakes:
#include <iostream>
using namespace std;
int raiseToPower(const int base, const int exponent) {
int result = base;
for (int i = 1; i < exponent; i = i + 1){
result = result * base;
}
return result;
}
int main() {
int base = 6;
cout << "6^5 is " << raiseToPower(base, 5)<< endl;
return 0;
}
If it has to be pass by reference you could do this:
#include <iostream>
using namespace std;
void raiseToPower(const int base,
const int exponent,
int &result)
{
result = base;
for (int i = 1; i < exponent; i = i + 1){
result = result * base;
}
}
int main() {
int base = 6;
int result;
raiseToPower(base, 5, result);
cout << "6^5 is " << result << endl;
return 0;
}
Your calculation is incorrect. The value of variable base should not change. Try this:
int raiseToPower(int &base, int exponent){
int result = 1;
for (int i = 1; i <= exponent; i = i + 1){
result = result * base;
}
return result;
}
You probably want your loop like this:
int result = 1;
for (int i = 0; i < exponent; i = i + 1) {
result = result * base;
}
return result;
Also, you are taking your base parameter to raiseToPower by reference - which means you are changing the base variable in main - probably not what you want to do.
Let's consider this loop
for (int i = 1; i < exponent; i = i + 1){
base= base * base;
}
After the first iteration when i is equal to 1 you have
base= base * base;
that is the result is base ^ 2.
When i = 2 you have
base= base^2 * base^2;
that is the result is base^4.
When i is equal to 3 you have
base= base^4 * base^4;
that is the result is base^8.
When i is equal to 4 you have
base= base^8 * base^8;
that is the result is base^16.
It seems the resulted value is too big to be accomodated in an object of the type int.
Also it is not a good idea when an argument is passed by reference. And the second parameter should have the type unsigned int.
Here is a demonstrative program that shows how the function can be implemented.
#include <iostream>
long long int raiseToPower( int base, unsigned int exponent )
{
long long int result = 1;
while ( exponent-- )
{
result *= base;
}
return result;
}
int main()
{
int base = 6;
std::cout << "6^5 is " << raiseToPower(base, 5) << std::endl;
return 0;
}
Its output is
6^5 is 7776
Related
I want to write a method in C++ which creates an array of monotonically increasing values. It has the inputs of int begin, int end, int interval.
In this example; method should return the array of [0,1,2,3,4,5,6,7,8,9,10]. When I print the results it should print out the first two indexes and get 0 and 1. However, when I print it, it gives 0 for the first one and 9829656 for the second one.
When I only print one index it is always correct, but when I print more than one index, every value except for the first printed one gives a different result. I think the other results are related to memory address since I used pointers.
#include <iostream>
using namespace std;
int* getIntervalArray(int begin, int end, int interval){
int len = (end - begin) / interval + 1;
int result[11] = {};
for (int i = 0; i <= len - 1; i++) {
result[i] = begin + interval * i;
}
return result;
}
int main(){
int begin = 0;
int end = 10;
int interval = 1;
int* newResult = getIntervalArray(begin, end, interval);
cout << newResult[0] << endl;
cout << newResult[1] << endl;
return 0;
}
You are returning a pointer to a local variable. You can instead return a std::vector by value as shown below:
#include <iostream>
#include <vector>
//return a vector by value
std::vector<int> getIntervalArray(int begin, int end, int interval){
int len = (end - begin) / interval + 1;
std::vector<int> result(len); //create a vector of size len
for (int i = 0; i <= len - 1; i++) {
result.at(i) = begin + interval * i;
}
return result;
}
int main(){
int begin = 0;
int end = 10;
int interval = 1;
std::vector<int> newResult = getIntervalArray(begin, end, interval);
//print out elements of returned vector
for(int i = 0; i < newResult.size(); ++i)
{
std::cout << newResult.at(i) << std::endl;
}
return 0;
}
The output of the above program can be seen here.
A possible solution dynamically allocating the local array, and returning it via a smart pointer:
#include <array>
#include <iostream>
#include <memory> // make_unique
auto getIntervalArray(int begin, int end, int interval)
{
int len = (end - begin) / interval + 1;
auto result{ std::make_unique<std::array<int, 11>>() };
for (int i = 0; i <= len - 1; i++) {
(*result)[i] = begin + interval * i;
}
return result;
}
int main()
{
int begin = 0;
int end = 10;
int interval = 1;
auto newResult{ getIntervalArray(begin, end, interval) };
std::cout << (*newResult)[0] << std::endl;
std::cout << (*newResult)[1] << std::endl;
std::cout << (*newResult)[2] << std::endl;
return 0;
}
Demo
Set the array variable in your function as static. This is because C++ does not support returning the address of a local variable.
static int result[11];
try this. also add deletion of the newResult
#include <iostream>
using namespace std;
int* getIntervalArray(int begin, int end, int interval){
int len = (end - begin) / interval + 1;
int* result = new int[len];
int lastValue = begin;
for (int i = 0; i <= len - 1; i++) {
result[i] = lastValue;
lastValue += interval;
}
return result;
}
int main(){
int begin = 0;
int end = 10;
int interval = 1;
int* newResult = getIntervalArray(begin, end, interval);
cout << newResult[0] << endl;
cout << newResult[1] << endl;
// add delete here.
return 0;
}
Adding two integer array elements
if array1 = {0,0,0,0,9,9,9,9}—————> 00009999
and
array2 = {0,0,0,0,0,0,0,1}————————> 00000001
adding the two arrays together should result in 10000 being in array1, since 9999 + 1 = 10000
therefore, the result should be
array1 = {0,0,0,1,0,0,0,0}
Does anyone know how to write a code for this? I was trying to use a while loop which didn't work effectively within another for loop. Fairly new to coding and stack overflow, any help will be appreciated!
CODE THAT I TRIED
Note: both arrays will have the same number of elements, they were initialized with the same size
int length = sizeof(array1)/sizeof(array1[0]);
for(int i = length; i>0; i--){
if(array1[i-1] + array2[i-1] < 10){
array1[i-1] += array2[i-1];
}else{
array1[i-1] = array1[i-1] + array2[i-1] - 10;
if(array1[i-2]!=9){
array1[i-2]++;
} else{
int j = i-2;
while(j == 9){
array1[j] = 0;
j--;
}
array1[j-1]++;
}
}
}
Code below performs base10 arithmetic: you need to iterate the arrays in reverse, do the addition of i-th digit by modulo 10, then carry over any excess digits to the next array element:
#include <iostream>
#include <iterator>
using namespace std;
int main()
{
int a1[] = { 0,0,0,0,9,9,9,9 };
int a2[] = { 0,0,0,0,0,0,0,1 };
const int b = 10;
int s = 0;
for (int i = size(a1) - 1; i >= 0; --i)
{
a1[i] += a2[i] + s;
s = a1[i] / b;
a1[i] %= b;
}
std::copy(a1, a1 + size(a1), ostream_iterator<int>(cout, " "));
cout << endl;
}
Alternative with C arrays and transform algorithm + make_reverse_iterator looks too heavy. Variant with std::arrays looks better:
#include <algorithm>
#include <array>
#include <iterator>
#include <iostream>
using namespace std;
int main()
{
std::array<int, 8> a1 = { 0,0,0,0,9,9,9,9 };
std::array<int, 8> a2 = { 0,0,0,0,0,0,0,1 };
const int b = 10;
int s = 0;
transform(a1.rbegin(), a1.rend(), a2.rbegin(), a1.rbegin(), [b, &s](int &i, int &j)
{
i += j + s;
s = i / b;
return i % b;
});
copy(a1.begin(), a1.end(), ostream_iterator<int>(cout, " "));
cout << endl;
}
It looks like you've overcomplicated the problem a bit. Your task is to perform base 10 addition on two arrays, carrying excess digits. You can simply iterate both arrays in reverse, perform addition on the individual elements, and ensure you carry over a digit when you exceed 10.
Here is an example based on the requirements you've described. You can further abstract this as needed.
I updated this code such that the result is now in array1.
#include <iostream>
int main(int argc, char *argv[], char *argp[]){
/* Initialize arrays and calculate array size */
int array1[] = {0,0,0,0,9,9,9,9};
int array2[] = {0,0,0,0,0,0,0,1};
int array_size = sizeof(array1) / sizeof(int);
/* Iterate the arrays in reverse */
int carry = 0;
for (int i = array_size - 1; i >= 0; i--) {
/* Perform addition on the current elements, remembering to include the carry digit */
int result = array1[i] + array2[i] + carry;
/* Determine if the addition should result in another carry */
if (result >= 10) {
carry = 1;
} else {
carry = 0;
}
/* Store the non-carried addition result */
array1[i] = result % 10;
}
/* View result */
for (int i = 0; i < array_size; i++) {
std::cout << array1[i];
}
std::cout << std::endl;
return 0;
}
uint32_t decode(int array[8]){
uint32_t multiple_of_ten=10000000;
uint32_t result = 0;
for(int i=0;i<8;i++){
result += (array[i] * multiple_of_ten);
multiple_of_ten = multiple_of_ten / 10;
}
return result;
}
int* encode(uint32_t number){
int result[8]={0,0,0,0,0,0,0,0};
uint32_t multiple_of_ten=10000000;
uint32_t recent = number;
for(int i=0;i<8;i++){
if(recent>0 && recent / multiple_of_ten > 0)
{
result[i] = recent / multiple_of_ten;
recent %= multiple_of_ten;
}
multiple_of_ten /= 10;
}
return result;
}
in your case , use encode(decode(array1) + decode(array2))
I have a problem with assigning variables to an array from different functions. I have two functions that produce different numbers. I then want to assign those numbers to a private array in the same class. When I do this the array returns large negative numbers.
// Array.h
class Array {
private:
int W = A;
int Q = B;
int sum[2] = {W, Q};
public:
int A;
int B;
int num1();
int num2();
int add();
};
// Array.cpp
#include<iostream>
using namespace std;
#include "Array.h"
int Array::num1()
{
int x = 3;
int y = 4;
A = x + y;
cout << A << endl;
return A;
}
int Array::num2()
{
int x = 2;
int y = 5;
B = x + y;
cout << B << endl;
return B;
}
int Array::add()
{
for(int i = 0; i < 2; i++)
{
cout << sum[i] << endl;
}
return 0;
}
// main.cpp
#include <iostream>
#include "Array.h"
int main() {
Array sumTotal;
sumTotal.num1();
sumTotal.num2();
sumTotal.add();
return 0;
}
Problem is here:
int W = A;
int Q = B;
int sum[2] = { W, Q };
You are just coping value from A and B to W and Q.
And later when you set A and B, those changes are not reflected to W or Q.
Thus leaving W and Q uninitialized.
Note: consider researching more about C++ topic in field of arrays, pointers and references.
This is modified code that works ok:
#include <iostream>
using namespace std;
class Array {
private:
int sum[2];
public:
int num1();
int num2();
int add();
};
int Array::num1()
{
int x = 3;
int y = 4;
sum[0] = x + y;
cout << sum[0] << endl;
return sum[0];
}
int Array::num2()
{
int x = 2;
int y = 5;
sum[1] = x + y;
cout << sum[1] << endl;
return sum[1];
}
int Array::add()
{
for (int i = 0; i < 2; i++)
{
cout << sum[i] << endl;
}
return 0;
}
int main(int argc, char** argv)
{
Array sumTotal;
sumTotal.num1();
sumTotal.num2();
sumTotal.add();
return 0;
}
The reason you are getting garbage values (large negative numbers, in your case) is that you are not initializing A or B to any meaningful values, and then you are not updating sum when you call num1, or num2.
You should initialize A and B to something meaningful in the class, or at least default initialize it.
Then you need to update sum in num1, like this:
int Array::num1()
{
int x = 3;
int y = 4;
A = x + y;
sum[0] = A; // <- add this
cout << A << endl;
return A;
}
and do a similar thing inside num2.
You also have 2 variables W, and Q inside your class which don't seem to serve any purpose. Apart from the issue with initializing them incorrectly with garbage values, you don't even need them; you could just use A, and B instead.
I'm wanting to print an int array with 8 bytes and convert it to bin & hex with the output as such:
0 00000000 00
1 00000001 07
...
I've finished creating the binary convert function. I want to use the same function as the binary conversion -with an array, but check the left half with the right half and solve each different sided of the 8 bytes; left most -3 and right most is -7.
What am I doing wrong? I cannot figure out how to implement it and I know my hex function is all out of wack.
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
const int num = 8; //may not be needed -added for hex
void Generatebinary(int arr[]);
void GeneratehexDec(int arr[]);
void print_binary(int arr[]); //haven't created yet
int main()
{
int arr[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
int i = 1;
while (i < 256)
{
Generatebinary(arr);
print_binary(arr); //not created yet
GeneratehexDec(arr);
i++;
}
}
void Generatebinary(int arr[])
{
for (int i = 7; i > 0; i--)
{
if (arr[i] == 1)
arr[i] = 0;
else if (arr[i] == 0)
{
arr[i] = 1;
break;
}
}
}
void GereatehexDec(int num)
{ //improper use
int a;
int i;
int answer[] = { };
a = num % 16;
i++;
answer[i] = num;
for (int i = num; i > 0; i--)
{
cout << answer[i];
}
cout << a;
}
First of all, you can't do int answer[] = { }; an array has to be pre-allocated (indicating how many elements it will store) or has to be dynamically allocated during run-time, then be freed, you have to manage your memory, not forget to deallocate... It's for this reason that Stroustrup tells you to not use arrays unless necessary. Use std::vector
void GereatehexDec(int num)
{ //improper use
int a = 0; // always initialize your variables
int i = 0; // is this i supposed to be the same as the i in the for loop below?
std::vector<int> answer;
a = num % 16;
i++; // this doesn't make sense
answer.at(i) = num;
for (int i = num; i > 0; i--) // what about the i variable you declared previously?
{
cout << answer.at(i);
}
cout << a;
}
Here's a template function that could help you (converts numbers into string hex)
template <typename I> std::string n2hexstr(I w, size_t hex_len = sizeof(I) << 1) {
static const char* digits = "0123456789ABCDEF";
std::string rc(hex_len, '0');
for (size_t i = 0, j = (hex_len - 1) * 4; i<hex_len; ++i, j -= 4)
rc[i] = digits[(w >> j) & 0x0f];
return "0x" + rc;
}
int main() {
std::cout << n2hexstr(127);
}
Can someone please help me understand why this code isn't working properly? I know it's very close and I think that I'm just overlooking something. Any help is appreciated. Here is what I have so far:
#include <iostream>
#define TEST_ARRAY_SIZE 4
long int factorial(int num);
long int factorial(int num){
for(unsigned int i = 1; i <= num; i++) {
num *= i;
}
return num;
}
int main() {
int test[TEST_ARRAY_SIZE] = {1, 2, 5, 7};
for (unsigned int i = 0; i < TEST_ARRAY_SIZE; i++) {
std::cout << "Factorial of " << test[i] << " is " << factorial(test[i]) << std::endl;
}
return 0;
}
You should move return num; outside the loop. As it is now, control always return after the first number is multiplied.
-- the correct code --
long int factorial(int num){
long int res = 1;
for(unsigned int i = 1; i <= num; i++) {
res *= i;
}
return res;
}
The body of the factorial function is not correct. You can use a recursive method to compute the factorial of a specific number. The corrected program of your version is below:
#include <iostream>
#define TEST_ARRAY_SIZE 4
long int factorial(int num);
int main() {
int test[TEST_ARRAY_SIZE] = {1, 2, 5, 7};
for (unsigned int i = 0; i < TEST_ARRAY_SIZE; i++) {
std::cout << "Factorial of " << test[i] << " is " << factorial(test[i]) << std::endl;
}
return 0;
}
long int factorial(int num){
if (num == 1)
return num;
else
return num * factorial(num-1);
}
That's only part of the problem; it's a case in which proper indentation would make the bug apparent in an instant.
In addition to that, why are you using num inside the loop? You should leave it as-is and declare a new variable to compound and return the result.
long int factorial(unsigned int num) {
int x = 1;
for(unsigned int i = 1; i <= num; i++) {
x *= i;
}
return x;
}
Other things to note:
You shouldn't be using a #define; you should declare a const instead.
You're comparing an unsigned against a signed in the factorial() for loop.