Exponents in C++ by using loops [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need some help. I want to compute ax given real value a and positive value integer x.
My program:
#include <iostream>
using namespace std;
int main()
{
int a, x;
cout << "Input a: ";
cin >> a;
cout << "Input x: ";
cin >> x;
for (int i=0; i<=x; i++)
a= a*a;
cout << "The answer is: " << a;
}

Take a look at this loop:
for (int i=0; i<=x; i++)
a= a*a;
cout << "The answer is: " << a;
}
Every time you go through this loop, you multiply a by itself. Let's suppose the user enters number a0. Then:
After 0 iterations, a has value a0.
After 1 iteration, a has value a02
After 2 iterations, a has value a04
After 3 iterations, a has value a08
...
For example, if a = 2 and x = 4, the values will be 2, 4, 16, and 256, which are way bigger than you want them to be.
To fix this, try changing your loop so that you have a secondary variable, initially set to 1, that you keep multiplying by a. That way, you don't change what value you're multiplying by on each iteration.
Next, note that your loop is running too many times. Since you loop up to and including x, your loop runs x + 1 times, so if you want to compute ax you will get the wrong value. Try changing this to loop exactly x times.
Finally, your print statement runs on each iteration, so you'll see all the intermediary values. Change the code so that the print statement is outside the loop.
After doing all that, do look up the pow function. If this is for an assignment you might not be able to use this function, but it's the easiest way to solve this problem.
Hope this helps!

There are a couple of errors:
for (int i=0; i<=x; i++)
this will loop for x+1 times, not what you intended.
a= a*a;
every time you do this, a is the value that is already multiplied, so you need another variable to store the result.
int result = 1;
for (int i=0; i<x; i++)
result *= a;
}
cout << "The answer is: " << result;
One last note, to calculate a^x, int may be too small for many practical cases, consider a bigger type like long long.

int result = 1;
for (int i=1; i<=x; i++)
{
result= result*a;
}
cout << "The answer is: " << result;
}
Hope This will work for you

A more "fun" method would be to use a template:
template<unsigned int E>
unsigned int power(unsigned int i)
{
return i * power<E - 1>(i); // template "loop"
}
template<>
unsigned int power<0>(unsigned int i) // break the "loop"
{
return 1;
}
To get the result:
unsigned int result = power<5>(3);
I thought it obvious, but just for clarification: This method requires that you know the exponent at compile-time.
Since std::pow exists, it is a bit silly to use a loop, but it can be done:
unsigned int base = SOME_BASE;
unsigned int exponent = SOME_EXPONENT;
unsigned int result = 1;
for (int i = 0; i < exponent; result *= base, ++i);

Related

How to find the sum of numbers that have digits higher than 5 [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
so I want to write a function that returns the sum of all numbers in an array who's digits are higher then 5 so for example if the array is [12, 66, 23, 67] the answer would be 66+67
This code summs all the numbers in the array and I can'\t figure out why
using namespace std;
int func(int n[], int size){
int digit, S=0, a;
for(int i=0; i<size; i++){
a= n[i];
while( n[i]!=0){
digit= n[i]%10;
if(digit>=5){
n[i]= n[i]/10;
}
else break;
}
S=S+a;
}
return S;
}
int main()
{
int n[3], i;
for(int i=0; i<3; i++){
cin>>n[i];
}
cout<<func(n, 3)<<endl;
return 0;
}```
S=S+a This piece of code is out of your while loop and inside for loop, this will add all the elements in the array
The main problem is that you are not checking when you should add a to S.
These lines are causing the problem:
int func(int n[], int size){
int digit, S=0, a;
for(int i=0; i<size; i++){
a= n[i];
while( n[i]!=0){
digit= n[i]%10;
if(digit>=5){ // Wrong. Do "digit > 5"
n[i]= n[i]/10;
}
else break; <--- exiting this while loop
}
S=S+a; <--- ...but still adding?
}
return S;
}
You are breaking the loop, but still adding to the sum.
You should use a flag. Your inner loop would look something like this:
// We need to check if each digit is valid
bool each_digit_greater_than_5 = true;
// As long as we have digits left and all previous digits were valid
while(n[i] != 0 && each_digit_greater_than_5)
{
// Extract a digit
digit = n[i] % 10;
// If valid, get next digit to extract
if(digit > 5)
{
n[i] /= 10;
}
// Else, exit the loop
else
{
each_digit_greater_than_5 = false;
}
}
And then, simply check if each_digit_greater_than_5:
// If number was valid
if(each_digit_greater_than_5)
{
// Add to sum
S = S + a;
}
Extra Notes:
How you write the code is often more important than what you write.
Here are (some) food for thoughts.
Use better formatting: The whole block of code should be uniformly indented. This:
...
for(int i=0; i<size; i++){
a= n[i];
while( n[i]!=0){
digit= n[i]%10;
...
is both confusing and unclear. Use same indentation for each separate block:
...
for(int i=0; i<size; i++){ // The base block
a= n[i]; // new block start, add indent
while( n[i]!=0){ // same block, same indent
digit= n[i]%10; // new block, add indent
...
Use better naming: Don't use S, a and n unless they are very clear.
digit is a good choice, so credits for that!
Here, it is better to use:
sum_of_special_numbers
and
array
and
current_number
instead of S, n and a.
Comment!: Another very important part of programming (Note: not coding).
Are you coding?
Don't care if anyone understands it or not, just doing it cause they said so.
Or programming?
Making a clear, maintainable and debuggable code.
You decide!
Since this question is tagged with C++, I want to give an additional answer that uses C++ and especially modern C++ algorithms. I added also comments to the code and used meaningful variable names. I recommend that you try to do the same in the future.
What is the example code doing?
First, it informs the user about the software and asks, how many values should be checked and added. The values will be stored in a std::vector. With std::copy_n and the std::istream_iterator we read the values given by the user. The std::istream_iterator simply calls the extractor operator >> in the copy loop.
Then we call the subfunction to calculate the sum and show it to the user.
The subfunction consists of one Lampda definition and one std::accumulate statement. That's all.
The lambda converts the int to a std::string and then checks if any of the characters in the number is lower than '5'. Then it returns an inverted result.
So, you see, with C++, the implementation get's very simple:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string>
#include <numeric>
int sumOfNumbersWithDigitsGreaterThan5(const std::vector<int>& v) {
// Create a lambda that checks, if all digits are greater than 5
auto check5 = [](const int i) -> bool { std::string s{ std::to_string(i) };
return !std::any_of(s.begin(), s.end(), [](const char c) { return c <= '5'; }); };
// Calculate the sume of all given values in the vector with all digits greater than 5
return std::accumulate(v.begin(), v.end(), 0,
[&](const int init, const int i) { return init + (check5(i) ? i : 0); });
}
int main() {
// Inform the user, what to do
std::cout << "Sum of all numbers having all digits greater than 5\n\nHow many numbers to you want to sum?: ";
// Get the number of values that we want to sum up. Check plausibility
if (int numberOfValuesToCheck{}; (std::cin >> numberOfValuesToCheck) && (numberOfValuesToCheck > 0)) {
// Create a std::vector for our values having the requested number of elements
std::vector<int> values(numberOfValuesToCheck);
// Read the requested number of elements from std::cin to the values vector
std::copy_n(std::istream_iterator<int>(std::cin), numberOfValuesToCheck, values.begin());
// Show result
std::cout << "\n\nThe sum for all numbers with all digits greater 5 is: " <<
sumOfNumbersWithDigitsGreaterThan5(values) << "\n";
}
else {
std::cerr << "\n\n*** Error: Wrong input\n";
}
return 0;
}
Of course there are many many other possible solutions . . .

C++ - Printing prime numbers till N [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Question says:
You are given an integer N. You need to print the series of all prime numbers till N.
I want to know what's wrong with my code and suggestions will also be of great help.
#include<iostream>
using namespace std;
int main()
{
int N;
cin >> N;
int u;
for(int i = N; i > 0; i--)
{
u = 0;
for(int j = 2; j < N-1; j++)
{
if(i % j == 0)
{
u = 1;
}
}
if(u == 0)
{
cout << i << " ";
}
}
return 0;
}
First for future reference you should probably post that on code review, unless there is a specific problem then you should create a Minimal, Complete, and Verifiable post.
There is nothing inherently wrong other than you do not check that N>0 which could lead to an infinite loop, j should be going to i not N, and I think this would print 1 as a prime number which it is not. Here are some pointers:
Why are you going from N to 0? That seems a little counter intuitive compared from going from 2 to N (you can skip 1 since it is not prime)
If you are going to use a flag (u) then you should make it a bool which forces it to be either true or false
You do not need to do a flag, instead as soon as you find a divisor print the number and then break the inner loop like
for(j=2; j< N-1; j++){
if(i%j==0){
cout << i << " ";
break;
}
}
You do not need to have j go all the way to i, just the sqrt(i) since anything greater then the sqrt(i) that divides i must must be multiplied by some number smaller then the sqrt(i). So if i is not prime, then there must be a divisor below sqrt(i)

I am unable to assign difference of two elements of 2 dimensional array to element of other array in C++? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Below is the code, which is breaking my head since two days.
#include <iostream>
using namespace std;
int main()
{
int N;
int A[1][N-1];
int B[1][N-1];
std::cout << "ENTER NO OF ROUND" << '\n';
std::cin >> N;
for (int j=0; j<N; j++)
{
int i =0;
std::cout << "enter the scores" << '\n';
std::cin >> A[i][j]>>A[i+1][j];
if (A[i][j] > A[i+1][j])
{
B[i][j] = A[i][j] - A[i+1][j];
B[i+1][j] = 1;
}
if (A[i][j] < A[i+1][j])
{
B[i][j] = A[i+1][j] - A[i][j];
B[i+1][j] = 2;
}
}
std::cout << A[0][0]<<A[1][0] << '\n';
return 0;
}
Here in line 18 line 19 and line23 line24i should get difference of two elements of array A[1][N-1] Which is then assigned to a element in array B[1][N-1],but am unable get the correct result ,rather am getting a random number.
help me getting through this
You use uninitialized data, so anything can happen.
You declare the N variable:
int N;
And then, in the very next line, without assigning any value, you use it to create two arrays using N as a size:
int A[1][N-1];
int B[1][N-1];
This already is a starting point for disaster. Moreover, declaring an array with size [N - 1] is not technically correct - N is a variable, so cannot be used to declare array in this manner. It's a compiler extension (are you using Visual Studio?). If value of N is known, declare it as:
static constexpr size_t N = value;
If it is read at runtime, create your arrays with new or, much better, use std::vector to make your code robust and less error-prone.
The second thing is, that A array is declared as int A[1][N-1];, but you do the following:
int i = 0;
....
if (A[i][j] > A[i+1][j])
Which results in reading A[1][j], which does not exist - in C++ we start indexing from 0! You also modify those non-existing elements:
std::cin >> A[i][j] >> A[i+1][j];
which most likely will result in writing to memory that belongs to B array.
Small notes:
using namespace std seems redundant, as you write std:: everywhere
what is the point of two-dimensional array [M][N] if M = 1?
Use std::vectors if you need arrays with size determined at run-time. The C Variable-length arrays you use are not supported in C++.
std::cout << "ENTER NO OF ROUND" << '\n';
int N = 0;
std::cin >> N;
std::vector<std::vector<int>> A(2, std::vector<int>(N));
std::vector<std::vector<int>> B(2, std::vector<int>(N));
And note that you need 2 x N array because you read both A[i][j] and A[i+1][j] and your for loop is from [0 to N-1] -- N times.

Wrong value output [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm trying to make the program give me the lowest and the highest value in the array.
Here's my code :
int z=10;
int a[z]={1,2,3,4,5,6,7,8,9,10};
for (int x=1;x<=10;x++) {
cout << "How many pancakes were eaten by P"<<x<<endl;
cin >> a[x];}
int maxPancakes = a[0];
int glutton;
int minPancakes = a[0];
int mN;
for (int x = 0; x <= z; x++) {
if (a[x] >= maxPancakes) {
maxPancakes = a[x];
glutton = x;
}
else if (a[x] <= minPancakes) {
minPancakes = a[x];
mN = x;
}
}
The code for the highest value is working, but the code for the lowest value keeps on giving me wrong values (random big numbers)
i'd appreciate any help,thank you.
First of all use standard library. It will make your life easier and code safer (and most of the time also faster).
For the array since C++11 you can use std::array, if you are working with the older C++ standard you can use std::vector.
Please note that in your code you are creating array with 10 elements but in the second loop you are iterating 11 times. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and... 10.
The value of the a[10] is undefined, it can be anything (random value).
In the first for loop you are setting the values for a[1] (second element), a[2] (third element), ... , a[10] (eleventh element, bad!).
Fix this loops and check what will happen. You can also start "debugging" with something easier than gdb (which is awesome btw. and you should learn it). You can simply print the values (read about std::cout) in every iteration to see when exactly this "random big numbers" are found.
EDIT
for (int x = 0; x < 10; x++)
{
cout << "How many pancakes were eaten by P" << x << endl;
cin >> a[x];
}
int maxPancakes = a[0];
int glutton;
int minPancakes = a[0];
int mN;
for (int x = 0; x < z; x++)
{
if (a[x] > maxPancakes)
{
maxPancakes = a[x];
glutton = x;
}
else if (a[x] < minPancakes)
{
minPancakes = a[x];
mN = x;
}
}

Program returning garbage after array formed in function [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
This program is supposed to use a function to gather 4 grades into an array, use another function to average the grades, and another function to display the average and 4 original grades.
The 4 grades have to be between 0 and 100.
I have this program printing out grade[2] just to test it, but it always outputs garbage.
What is it that I'm doing wrong here?
Also, if I try to call getGrades(grade, 5) without the "float grade[5]" line in there first, it tells me that "grade" is an undeclared identifier. Which leads me to believe i've done something wrong in writing that function.
Thanks
#include <iostream>
using namespace std;
float computeAverage(float exam1, float exam2, float exam3, float exam4)
{
float average;
average = exam1*.2 + exam2*.2 + exam3*.2 + exam4*.4;
return average;
}
void getGrades(float a[], int size)
{
int i;
float num;
for (i=0; i<4; i++)
{
cin >> num;
if (num>=0 && num <=100)
num = a[i];
else
{
cout << "That number is out of range.";
i--;
}
}
}
int main()
{
float grade[5];
getGrades(grade,5);
grade[4] = computeAverage(grade[0], grade[1], grade[2], grade[3]);
cout << grade[2];
return 0;
}
You are not storing the values in grade array in getGrades function that is the reason you are getting garbage value.
Change this:-
num = a[i];
to
a[i] = num;
num = a[i];
should be
a[i] = num;
Welcome to computer science :-)