I have this code which intends to explain how "for loops" work.
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Input a positive integer: ";
cin >> n;
int factorial = 1;
for (int i = 1; i <= n; ++i)
factorial *= i;
cout << "factorial(" << n << ") is << factorial << "\n ";
return (0);
}
What does the line int factorial =1 do? Why is it needed?
int factorial = 1;
defines a variable with the identifier factorial and the type int. It is intended to hold the temporary results of the factorial calculation throughout all iterations of the for-loop and to hold the final result.
It is explicitly initialized with 1 because
It has to be initialized somehow; otherwise, undefined behavior will be the result as an uninitialized memory location will be accessed.
0 would be bad because 0 * x = 0 for all real numbers while 1 * x = x for all real numbers.
Related
Sorry for bad English.
So my problem is that i need to find all possible factorials starting from 1.
I need it to stop when Int have maximum memory used and print out maximum factorial value. My code is pretty simple, but i do not know how to get to stop loop when it reach maximum of Intiger values.
#include <iostream>
#include<climits>//
#include <cmath>
using namespace std;
int main() {
int k,n=0;
unsigned int factorial = 1;
unsigned int factorial2=1;
unsigned uval=INT_MAX;
cout << "Ievadi koeficentu k: ";
cin >> k;
for(int i = 1; i<=k; ++i) {
factorial *= i;
}
cout << "Ievadita koeficenta " << k << " faktorials " << " = " <<factorial;
cout << "\nVisi iespejamie faktoriali no 1 - n: ";
for(int s = 1; s<=uval; ++s) {
factorial2 *= s;
if( s < uval / factorial2 ){
cout <<" \nkoeficenta " << s << " faktorials ir ==> " <<factorial2;
}
}
return 0;
}
The problem is that the loop is going to calculate factorial to all UINT_MAX values, and most of the output will be 0 becouse memory is overloaded.
But it should stop before it goes bigger that UINT_MAX memory!
Hope you all understand my problem and will help me with this.
In a 32-bit signed integer, 12! is the largest possible.
You can check this by doing
if (INT_MAX / fact_so_far < n)
{
std::cout << "Max factorial " << n-1 << std::endl;
}
[This code STOPS when it reaches the "unable to calculate", because INT_MAX / fact_so_far will not multiply without overflow].
if (INT_MAX / fact_so_far >= n)
{
fact_so_far *= n;
}
else
{
std::cout << n << " is too large to calculate factorial" << std::endl;
}
would be the other way to do this. [Obviously with suitable loop to increment n]
Not that MAX_UINT is the max value for unsigned int, not for int [it's typically half that].
Edit to explain the logic:
The logic here is that if we divide INT_MAX with what our current factorial value is, it should produce a value larger than n [the current multiplier for the next factorial].
As a simple step through example, we pick a MAX_INT of 127:
Initial state:
factorial = 1, n = 1;
Steps:
n = 2, MAX_INT / factorial = 127 -> factorial *= n => 2
n = 3, MAX_INT / factorial = 63 -> factorial *= n => 6
n = 4, MAX_INT / factorial = 21 -> factorial *= n => 24
n = 5, MAX_INT / factorial = 5 -> factorial *= n = 120
n = 6, MAX_INT / factorial = 1 -> FAIL - will overflow.
Before calculating the next factorial in the list, see if the previous one is greater than UINT_MAX / i. If it is, you know that the next multiplication will go out of bounds.
If factorial2 > UINT_MAX / (s+1), the next factorial can't be calculated.
By the way, you should use unsigned int for factorial2
You are comparing the signed int with an unsigned one i.e. you are doing i < UINT_MAX (This is the maximum value of unsigned int) which is wrong and will result in overflow and wrong condition check.
so i finaly did this with my code. Now it works but its not realy good. Maybe someone someday will need something like this as a start for his own max factorial programm. First program will ask you to insert a random number and then it calculate its factorial (only in max int borders). Then it prints out all possible int factorials. Its show only 11! as max but the max is 12! I add factorial 12! manualy, becouse the if statment cannot print out excatly the number 12 as max it prints one before. And in the end the programm shows you what is maxium possible factorial for intiger.
#include <iostream>
#include<climits>//
#include <cmath>
using namespace std;
int main() {
int k, max,s;
unsigned int factorial = 1;
unsigned int factorial2 = 1;
unsigned uval=INT_MAX;
cout << "Ievadi koeficentu k: ";
cin >> k;
for(int i = 1; i<=k; ++i) {
factorial *= i;
}
cout << "Ievadita koeficenta " << k << " faktorials " << " = " <<factorial;
cout << "\nVisi iespejamie faktoriali no 1 - n: ";
for( s = 1; s<=uval; ++s) {
factorial2 *= s;
max=factorial2;
if( s <= uval / factorial2 ){
cout <<" \nkoeficenta " << s << " faktorials ir ==> " <<factorial2;
}
else {
break;
}
}
cout <<" \nkoeficenta " << s << " faktorials ir ==> " <<factorial2;
cout <<" \nMaksimalais faktorials ir skaitla " << s << " faktorials ==> " <<max;
return 0;
}
This is what the programm looks like!
![Programm][1]
This is a c++ program to convert decimal number to binary number. Well there are many possible ways to implement this but as I learned about the static variable I thought to make a use of it. So the program is
#include <iostream>
using namespace std;
int **binary(int num, int &k) {
static int *p;
int i = 0;
while (num > 0) {
*p = num % 2;
p++;
num = num / 2;
k++;
}
return &p;
}
int main() {
int n;
int k = 0;
cout << "\n Enter the number to be converted into binary : ";
cin >> n;
int **ptr;
ptr = binary(n, k);
cout << "\n The number of bytes in the binary number is : " << k << endl;
cout << "\n The binary code is : \n";
for (int i = 0; i < k; i++)
cout << **(ptr+i);
return 0;
}
Output:
Enter the number to be converted into binary : 33
Segmentation fault
After debugging this code I'm getting seg fault at line 9:9
i.e
*p = num % 2;
I don't know why this is leading me to access an unoccupied memory space in the stack.
The reason there is a crash is that p is initialized to nullptr. Dereferencing an uninitialized variable is undefined behavior, hence you get the crash.
Disclaimer: The following code is intended to fix your code. It is not intended to illustrate a proper way of doing this, or show a good way to code in general.
If you wish to play with function-static variables, and your function must return a pointer to pointer, initialize p by pointing it to another static variable which provides you with a buffer:
static int pVal[100];
static int * p;
p = pVal; // This should be done in an assignment, not in initializer
Note: Returning pointers to static storage makes your code non-reentrant, which is generally a very bad practice. This code is fine as a learning exercise, but it's not something one should use in production code.
static int * p; is never set. It is initialized to NULL, dereferencing it invokes undefined behavior. Using a static buffer is not recommended, it is better to pass an array to the function and return the number of bits. Furthermore, you should output these bits in the reverse order.
Since you are interested in static local variables, here is a corrected version of your code:
#include <iostream>
using namespace std;
int *binary(int num, int &k) {
static int bits[sizeof(int) * 8];
int *p = bits;
k = 0;
while (num > 0) {
*p = num % 2;
p++;
num = num / 2;
k++;
}
return p;
}
int main() {
int n;
int k = 0;
cout << "\n Enter the number to be converted into binary : ";
cin >> n;
int *ptr = binary(n, k);
cout << "\n The number of bits in the binary number is : " << k << endl;
cout << "\n The binary code is : \n";
for (int i = 0; i < k; i++)
cout << ptr[k - i];
return 0;
}
Here is a version that does not use a static buffer:
#include <iostream>
using namespace std;
int binary(unsigned int num, int *dest) {
for (int i = 0;;) {
dest[i++] = num & 1;
if ((num >>= 1) == 0)
return i;
}
}
int main() {
unsigned n;
int bits[sizeof(n) * 8];
cout << "\nEnter the number to be converted into binary: ";
cin >> n;
int k = binary(n, bits);
cout << "\nThe number of bits in the binary number is: " << k << endl;
cout << "\nThe binary code is: ";
for (int i = k; i-- > 0;)
cout << bits[i];
cout << endl;
return 0;
}
The code has numerous problems:
binary() does not initialise the pointer p to anything.
binary() dereferences the initialised p and modifies the value.
The conversion writes from LSB to MSB and the outputs writes in that order too.
You need to allocate a buffer to receive the conversion. This is safest done by the caller. Since ultimately you output the characters 1 or 0, your conversion may as well write those character values directly to a string.
#include <iostream>
using namespace std;
int main()
{
const int MAXNUM = 10; // this code creates 10 variables in fmax
int fmax[MAXNUM], maximum, i, l; // initialize fmax that contains 10 variables , maximum, i for the loop, and l for storing the location
cout << "enter 10 numbers: ";
maximum = fmax[0]; // this sets the maximum to 0
for(i = 0; i < MAXNUM; i++) // this is the code for finding the maximum numbers
{
cin >> fmax[i];
if(fmax[i] > maximum){
maximum = fmax[i];
l = i;
}
else{
maximum = maximum;
l = l;
}
}
cout << "the maximum number: " << maximum << endl; // outputs the results
cout << "the location of the number: " << l << endl;
return 0;
}
I have a problem on this exercise
the problem is the output of the program.
it doesn't displays
the maximum number and where it is located
it always shows like this
the maximum number is: 1987579782
the location of the number is: 26355764
I need to display the maximum number entered and its subscript I don't know how
there's something wrong with my code
here is the exercise problem
a.write, compile and run a c++ program to input 10 integer number into an array named fmax and determine the maximum value entered your program should contain only one loop and the maximum should determined as array element values are being input (hint. set the maximum equal to the first array element, which should be input before the loop used to input the remaining array values.) and keeping track both the maximum element in the array and the index number for the maximum.
You need to initialize the fmax[MAXNUM] array before you use it. Simply declaring a variable does not guarantee that it will be 0. At the moment the value of fmax[0] could be anything within the range of int as you have not initialized it to a value.
You also need to initialize the l variable to 0 (this is why you are getting the wrong location)
Try this:
#include <iostream>
using namespace std;
int main()
{
const int MAXNUM = 10; // this code creates 10 variables in fmax
int fmax[MAXNUM], maxinum, i, l = 0; // initialize fmax that contains 10 variables , maxinum, i for the loop, and l for storing the location
for(i = 0; i < MAXNUM; ++i)
{
fmax[i] = 0;
}
cout << "enter 10 numbers: ";
maxinum = fmax[0]; // this sets the maxinum to 0
for(i = 0; i < MAXNUM; i++) // this is the code for finding the maxinum numbers
{
cin >> fmax[i];
if(fmax[i] > maxinum){
maxinum = fmax[i];
l = i;
}
else{
maxinum = maxinum;
l = l;
}
}
cout << "the maxinum number: " << maxinum << endl; // outputs the results
cout << "the location of the number: " << l << endl;
return 0;
}
EDIT: Since it is a requirement that the code should only contain one loop, you might want to change the way you are doing this. The example I provided above is not a very elegant way to do it either. This is how I would do it (without using any potentially confusing C++ Standard Library functions)
#include <iostream>
int main()
{
std::cout << "Enter 10 numbers: ";
const int MAXNUM = 10;
int fmax[MAXNUM] = {0}; // this is an easy way to initialize the array elements to zero
int maxNum = 0, location;
for(int i = 0; i < MAXNUM; i++) {
std::cin >> fmax[i];
if(fmax[i] > maxNum) {
maxNum = fmax[i];
location = i;
}
}
std::cout << "The maximum number is " << maxNum << std::endl;
std::cout << "The location of the number is " << location << std::endl;
return 0;
}
Make sure you understand why this works - let me know if you have any questions.
You are initializing maximum with garbage value:
maxinum = fmax[0]; // this sets the maxinum to 0
Since you have not entered any elements yet.
I would suggest you use built-in function std::max_element from algorithm library: it will return pointer to the max element, so, you could output position of max element along with it's value:
#include <algorithm>
// Your code
// You should enter the whole array
auto max_element = std::max_element(std::begin(fmax), std::end(fmax));
std::cout << "Position: " << (max_element - std::begin(fmax)) << std::end;
std::cout << "Value: " << *max_element << std::endl;
Local variables (non-class) are not initialized to zero by default in C++. Your problem is that you initialize maxinum with the value of fmax[0] which in the beginning is garbage. If you then never enter any bigger number, the value of I is never changed and is also garbage. You need to explicitly initialize those variables to zero:
int fmax[MAXNUM] = { 0 };
into maxinum = 0, I = 0
maxinum = fmax[0]; // this sets the maxinum to 0
This does not set maxinum to 0 as you havent set fmax[0] to 0.
You can do this:
#include <iostream>
using namespace std;
int main()
{
const int MAXNUM = 10; // this code creates 10 variables in fmax
int fmax[MAXNUM], maxinum, i, l; // initialize fmax that contains 10 variables , maxinum, i for the loop, and l for storing the location
cout << "enter 10 numbers: ";
for(i = 0; i < MAXNUM; i++) // this is the code for finding the maxinum numbers
{
cin >> fmax[i];
if(i==0)
maxinum = fmax[i]; //....... this will do what you are trying to achieve
if(fmax[i] > maxinum){
maxinum = fmax[i];
l = i;
} // the else block you wrote is not necessary :)
}
cout << "the maxinum number: " << maxinum << endl; // outputs the results
cout << "the location of the number: " << l << endl;
return 0;
}
I am trying to write a program that will approximate e^x using taylor series as follows:
I created a function that will do the summation, taking in n (number of times to sum) and x (the exponent) and another function that takes in a number and returns its factorial. Pretty simple stuff I think. The problem I'm having is when I input a fractional x first (for instance, .5, 6) the program just hangs. If I first input something like (3, 6) and then after that calculation, I input (.5, 6)I will get an infinite loop. If the x I input is not a fraction, I can do the calculation as many times as I like.
I feel that it must have something to do with my call to the pow() function. I think I'm using it correctly (pow(double, int)) but does it not take fractions or something? I don't understand.
Here's my code:
double taylorSeries (double x, int n, double &error)
{
double sum = 0;
for (int i=0; i <= n; i++)
sum += (pow (x, i))/(factorial (i));
error = (fabs(exp(x) - sum));
return sum;
}
long factorial(int n)
{
long factorial=0;
for (int i = 0; i <= n; i++){
if (i == 0)
factorial = 1;
else
factorial = factorial * i;
}
return factorial;
}
And then the call to the taylorSeries function in main looks like this:
cout << "please enter x and n: ";
cin >> x >> n;
cout << "taylor series sum = " ;
cout << taylorSeries (x, n, error) << endl;
//cout << "error = " << error;
Can someone help me figure out why this isn't working?
Never mind some of the inefficiencies of your algorithm, the most likely cause for your function seemingly fail to return is a bad parsing of x and thus n not getting set at all, which means it could hold any random value.
Your line:
cin >> x >> n;
If it fails to parse into x properly then it will not attempt to parse the next number because the input stream will be in an error state.
If n has not been initialised it could hold any value which might in reality be an extremely big integer. Thus your algorithm appears not to ever return.
int main()
{
double x = 0.0;
int n = 0;
double error = 0;
cout << "please enter x and n: ";
cin >> x >> n;
if( cin )
{
cout << "taylor series sum, x=" << x << " n=" << n << " : ";
cout << taylorSeries (x, n, error) << endl;
cout << "error = " << error;
}
else
{
cerr << "invalid input" << endl;
}
}
For a more efficient algorithm:
double taylorSeries (double x, int n, double &error)
{
double sum = 1;
double xpow = x; // would start at 1 but we have implemented exponent of 0
double fact = 1;
for (int i=1; i <= n; i++)
{
fact *= i;
sum += xpow / fact;
xpow *= x;
}
error = fabs(exp(x) - sum);
return sum;
}
Your factorial function is technically correct until the point where it will overflow.
I'd like to request some help on my HW. I think I'm really close to figuring this out. Our CompSci class is currently shifting from learning Python to (introductory) C++. Since the two are vaguely similar, we've been advised, since we're beginners, to code the problem in Python (which we're very familiar with) and to translate it into C++ using the basics we just learned. The problem to solve is a simple "add the consecutive integers from 1 to that number, given a positive integer input." So an example would be:
>>Enter a positive integer: 10
>>1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
The Python code (this was successful) that I'm attempting to translate into C++ is:
num = int(raw_input("Enter a positive integer: "))
sum = 0
for i in range(1, num):
sum += i
print i, "+",
print num, "=", sum+num
And my unsuccessful C++ code:
#include <iostream>
using namespace std;
int main()
{
int num;
int sum;
int i;
sum = 0;
cout << "Please enter a positive integer: " << endl;
cin >> num;
for (i=0; 1 <= num; i++)
{
sum = sum + i;
cout << i << "+" << endl;
}
cout << num << "=" << sum + num << endl;
return 0;
}
But the output is simply an infinite, non-ending addition sequence from 0 to infinity, going top to bottom. Even worse is that it did not print in a straight line like I want it. As you can see, I quite literally tried to translate it word-for-word; I thought that'd be foolproof. Something must be wrong with my for loop. Since C++ doesn't have a class of its own for "range" like Python does, I thought the middle condition statement ("1 <= num;") would act as the range. Why didn't my "=" sign print out? And I don't understand why it won't terminate when it reaches "num." Think you can help? I thank you in advance for the replies.
Fixed code:
#include <iostream>
using namespace std;
int main()
{
int num;
int sum;
int i;
sum = 0;
cout << "Please enter a positive integer: " << endl;
cin >> num;
// Here you had 1 <= num which was always true for positive num
// and it did not depend on value of i.
for (i = 1; i < num; ++i)
{
sum = sum + i;
cout << i << "+"; // Here you had endl which produced newline characters.
}
cout << num << "=" << sum + num << endl;-
return 0;
}
This:
for (i=0; 1 <= num; i++)
should be:
for (i=0; i <= num; i++)
try this.
#include <iostream>
using namespace std;
int main()
{
int num;
int sum;
int i;
sum = 0;
cout << "Please enter a positive integer: ";
cin >> num;
for (i=0; i < num; i++)
{
sum = sum + i;
cout << i << " + ";
}
cout <<num << " = " << sum+num << endl;
return 0;
}
I don't really know Python, but the code
for i in range(1, num):
looks really similar to
for (int i=1; i <= num; ++i)
or is it possibly
for (int i=1; i != num; ++i)
which looks more like C++?
loop in c++ are most basic than python, the for loop is more simpler, it is based on the three expression: initializer expression, the loop test expression, and the counting expression. In particular what is wrong in your code is the test expression. Remember that the loop is executed if the test expression is true. You need to loop if the condition i<num is true. Your loop is never ending because num is always >= 1, or as you wrote 1 <= num always.
To print everythig on a line don't use endl