How to Count decimal points using for loop? - c++

It's my first time to deal with Decimal points in C++ and i was wondering if i want the for loop to increase 0.01 by 0.01 instead of 1.0 by 1.0 what can i do.
I tried this but obviously it didn't work.
#include <iostream>
using namespace std;
int main(){
double i;
for (i=1.5;i<1.68;i++);
cout<<i;
system("pause");
return 0;
}
How can i get this done?
Thank you in advance.

for (i = 1.5;i < 1.68;i = i + 0.1)
cout << i << endl;
there will be no ; after for loop otherwise it will become a statement and not work correctly..
floating points nature is unexpected so it sometimes becomes headache because of precision loss..so try to avoid them using in loop..always try to use integer in a loop..
so here is another answer and it is better than above and is less prone to any unexpected results
int i;
for (i = 150;i < 168;i += 10) {
cout << i / 100.0 << endl;
}

Try this:
#include <iostream>
using namespace std;
int main(){
int i;
for (i=150;i<168;i+=10)
{
double d=i/100.0;
cout<<d;
}
system("pause");
return 0;
}
One of mistakes in your code for (i=1.5;i<1.68;i++); is ";" after ")". It means, that this loop does nothing. I.e. next line cout<<i; is not inside body of loop.

Related

Code is returning zero from a mathematical expression [duplicate]

This question already has answers here:
Why is my double or int value is always 0 after division?
(5 answers)
Closed last year.
#include <iostream>
#include <cmath>
using namespace std;
int Factorial_of(int n)
{
int fact = 1, i;
for(i=1; i<=n; i++)
fact = fact * i;
return fact;
}
int main()
{
cout << Factorial_of(4) / (Factorial_of(10) * Factorial_of(abs(4-10))) << endl;
}
Does anyone know why this is printing 0?
Update:
After changing the code based on #M. Twarog's answer, it is outputting "9.18577e-009" now, Does anyone know why?
#include <iostream>
#include <cmath>
using namespace std;
double Factorial_of(int n)
{
double fact = 1;
int i;
for(i=1; i<=n; i++)
fact = fact * i;
return fact;
}
int main()
{
double res=Factorial_of(4) / (Factorial_of(10) * Factorial_of(abs(4-10)));
cout<<res;
}
There are some errors/mistakes . First for division always go with double variable. And Your code is returning value in point so return type should be double. Also you miss << in cout statement before endl.
I can explain the output you get after fixing things: its the right answer

Sum in loop not displaying actual result?

I am suppossed to sum the squares of the all the natural numbers until it reaches some input, but the result becomes larger than it should. As I set 3 as input, the outcome becomes 3*10⁹ or so, could you please tell if I am missing a mistake with data types or operations?
BTW, when does using functions become more efficient than writing whatever in the main code? I have quite a few doubts on when I should or should not use them.
Thanks to whomever might read it.
#include <iostream>
using namespace std;
int main(){
int input, sum;
cin >> input;
for(int i = 1; i <= input; i++){
sum += i*i;
}
cout << sum << endl;
}
You should initialize the variable sum with 0 and then the program will be run successfully. When you use sum without initializing it, the behaviour of your program is undefined.
Also you can use below formula instead of the for loop:
sum = n * (n + 1) * (2 * n + 1) / 6
You never initialize sum, so there is no guarantee that the value starts at 0. In fact, it's initial value is essentially undefined. You should simply add the line sum = 0; before your for loop.
#include <iostream>
using namespace std;
int main(){
int input, sum;
sum = 0;
cin >> input;
for(int i = 1; i <= input; i++){
sum += i*i;
}
cout << sum << endl;
}
"BTW, when does using functions become more efficient than writing whatever in the main code"
It isn't necessarily more efficient, but for larger projects it is easier to read code when common functionality has been grouped into reusable functions. As a general rule of thumb, if you are writing the same code/algorithm more than once, you should write a function for that code/algorithm.
NOTE - As pointed out by others there happens to be a formula for calculating the sum of squares without a loop.
sum = n * (n + 1) * (2 * n + 1) / 6
This is what is known as an order of 1, or O(1), solution because a single atomic operation can be performed to achieve the results you are looking for. On the other hand, the loop solution is considered order of n, or O(n), since n iterations of the loop must be performed to achieve the results of the routine. The O(1) solution is considered optimal. If you use large values as your input then you will see why. However, if you are new to programming then your teachers will not expect you to know much about algorithm analysis and the original solution above should be fine.
There are two approaches to resolve your problem.
The first one is to place the declaration of the variable sum before main. For example
#include <iostream>
using namespace std;
int sum;
int main(){
int input;
cin >> input;
for(int i = 1; i <= input; i++){
sum += i*i;
}
cout << sum << endl;
}
In this case the variable will have the static storage duration and will be initislized by the compiler with 0.
Otherwise the variable have the automatic storage duration and must be initialized explicitly like
#include <iostream>
using namespace std;
int main(){
int input, sum = 0;
cin >> input;
for(int i = 1; i <= input; i++){
sum += i*i;
}
cout << sum << endl;
}
Pay attention to that it is better to declare the variable as having the type long long int because the sum of squares can be too big and will not fit into an object of the type int. For example
#include <iostream>
using namespace std;
int main(){
int input;
long long int sum =0;
cin >> input;
for(int i = 1; i <= input; i++){
sum += ( long long int )i*i;
}
cout << sum << endl;
}
You do not initialize sum. So whenever you do sum += i * i, you are adding numbers to a trash value.
This is the reason you get incorrect results.
To fix this, simply replace int input, sum; with int input, sum(0);.

Weird 'string' declared here error. Trying to program pyramid of asterisks

I'm new to C++, so I'm still trying to figure out how to do basic debugging from errors printed on the terminal. I'm trying to print a pyramid of asterisks (*), but I keep getting this error that says "'string' declared here". /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/iosfwd:194:65: note:
'string' declared here
typedef basic_string, allocator > string;
^
1 error generated.
I've tried looking up how to read some of these errors in C++, but haven't been able to find a useful guide that isn't written in some alien technical gibberish. So if you could dumb down the explanation a little that would be great.
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
using namespace std;
String printAst(int number){
for(int i = 0; i < number; i++){
cout << "* ";
}
}
int main(){
printAst(3);
//***
//**
//*
return 0;
}
I have the expected print out listed in //
Here is a corrected version of your code. The immediate cause of your current errors appears to have been the String return type of the printAst() function. If you wanted to return a string, then you probably intended to use std::string, not String. But, even after fixing this, I noticed that your logic for printing the pyramid also had a problem, so I fixed that too.
void printAst (int number) {
for (int i=0; i < number; ++i) {
for (int j=0; j < number-i; ++j) {
cout << "* ";
}
cout << "\n";
}
}
int main() {
printAst(3);
return 0;
}
* * *
* *
*
The major changes I made include using a double for loop to print the inverse pyramid. The logic is that there are number levels to the pyramid, and at each level we print number count of asterisks.
Also, since printAst does not return anything, I changed the return type to void.

Trying to run a code but terminal does not read the program

This is probably a very easy problem, but I am studying while loops and I am trying to write a program that sums numbers from 50 to 100. This is my code that I wrote
#include <iostream>
using namespace std;
int main() {
int sum=0;
int val=1;
while(50 <= val <= 100) {
sum = sum + val;
val = val + 1;
}
cout << "Sum is: " << sum << endl;
return 0;
}
I was to compile the code and get a program, but each time I am trying to run the program on terminal is just goes idle. Is there something wrond with my code? Thanks!
All the comments are valid. Please look at the C++ reference for syntax and how to use operators and loop.
I believe looking at some correct code is also a way to learn and hence posting this :
#include <iostream>
using namespace std;
int main ()
{
int sum = 0;
int i = 50; // Why not start from 50 itself, when you want sum(50-100)
while (i <=100)
{
sum += i; // Same as sum = sum + i
i++; // Same as i = i + 1
}
cout<<sum<<"\n";
return 0;
}

Trying to make a table that converts decimal to binary and ASCII C++

I have to make a table that shows the values 1 through 127 converted to binary and decimal like this:
Hexadecimal and Octal are optional.
Here's what I have so far:
using namespace std;
int main() {
int dec;
int binary_array [128];
for (dec = 0; dec<128; dec++){
for (int I =0; I < 7; i++){
binary_array[i]= dec % 2;
cout<<binary_array[i];
dec = dec / 2;
}
}
}
You can use bitset to convert decimal to binary and then print out the results.
#include <iostream>
#include <bitset>
using namespace std;
int main() {
for(int i = 0; i <= 127; i++)
{
cout << i << " " << bitset<8>(i) << endl;
}
return 0;
}
EDIT:
Since using bitset is not an option, lets dissect your code and understand whats wrong with it.
using namespace std;
int main()
{
int dec;
int binary_array [128];
for (dec = 0; dec<128; dec++)
{
for (int I =0; I < 7; i++)
{
binary_array[i]= dec % 2; <--OK
cout<<binary_array[i]; <-- NOT OK, think carefully
dec = dec / 2; <-- OK
}
//now you have exited for loop, what is the value of dec?
//think what happened to dec in the second for loop
//your current logic will create a infinite loop
}
}
Your logic is on the right path and if you think carefully, you will be able to do it yourself and feel good about it instead of copying available solution without trying to learn what went wrong. I would suggest you to try to think hard and implement. If you still cannot solve it, feel free to post updated code and let us know.