using while loop for determining square roots of numbers c++ - c++

I am running a c++ program, using while loop for determining square roots of numbers, here i have defined variables, tried but nothings seems to work for me, any hand would be great to assist me.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int n=10, N=0, i=0;
while(i<5)
N=i*n;
cout<<"numbers ="<<"\t Square root="<<sqrt(N)<<endl;
return 0;
}
The program execute successfully but nothing display (emptyb line). thanks.

while(i<5)
N=i*n;
Because you didn't indent or use brackets, you may have missed this and is equal to:
while (i < 5) {
N = i * n;
}
because the language specifies that no brackets means you just apply it to the next statement only and keep looping on that.
So this just loops forever as i never grows beyond 5 to exit the loop.

Just add fancy brackets to your loop and check where you want to change i and n.

Related

time complexity of (A[i]^x)>(A[i]&x)

'Is it possible to further optimize the time complexity this piece of calculation "(y^x)>(y&x)" in c++?(you are allowed to change the Boolean operation into other forms, for example this can also be written as log2(y)!=log2(x) and this gives the same Boolean output but this has a higher time complexity with c++ compiler)'enter code here
#include <bits/stdc++.h>
using namespace std;
int main() {
// your code goes here
int t;cin>>t;
while(t--){
int n;cin>>n;int A[n];
for(int i=0;i<n;i++){cin>>A[i];}
int q;cin>>q;
while(q--){
int l,r,x;
cin>>l>>r>>x;int count=0;
for(int i=l-1;i<r;i++){
if((A[i]^x)>(A[i]&x)){count++;}
}
cout<<count<<endl;
}
}
return 0;
}
'This is the code im trying to optimize.... Please help in any way possible (number of inputs cant be changed)'
(y^x)>(y&x) is equivalent to nlz(y) != nlz(x) where nlz is a function that returns the number of leading zeroes of its input.
Therefore in order to count how often (A[i]^x)>(A[i]&x) is true for items in the array A, we could make a small array N where N[j] is the number of elements with nlz(A[i]) == j in array A. Then the number of times that (A[i]^x)>(A[i]&x) is true is equivalent to n - N[nlz(x)].
That way there is no loop over A where it really matters. Creating the array N still requires a loop over A, but only once for each iteration of the outer loop, not for each individual x.
C++20 has the nlz function built in under the name std::countl_zero.

My program doesn't end

I'm new too c++ and I had to design a program that determines the first four triangular square numbers and the output is exactly how I want it to be, but it wont quit after its printed the first four. I can't figure out what it could be. I can't CTRL C because I will get points taken off. What is the issue here?
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
//Prints name line
cout<<"*********** BY: ********"<<endl;
//Initializing
const int HOW_MANY=4;
int num=1;
int tsn=0;
int z=1;
int x=0;
//How many TSN it will find and be printed
while (x<=HOW_MANY)
{
//
int sum=0;
for (int y=0;y<512;y++)
{
sum+=y;
tsn=pow(num,2);
//Tests if the numbers are TSN
if ((sum==tsn) || (num+1)/sqrt(num)==sqrt(num))
{
//Prints 1-HOW_MANY TSN and what they are
cout<<"Square Triangular Number "<< z <<" is: "<< tsn <<endl;
z++;
x++;
}
}
num++;
}
return 0;
}
If x = 0 then instead of while (x<=HOW_MANY) you need write while (x<HOW_MANY).
x begins at 0. Every time you find and print a number it gets incremented. You'll continue this, so long as x<=HOW_MANY.
You say your program finds 4 numbers but keeps running. After 4 hits, x will be 4. Is 4 <= 4? The answer is yes, so your program keeps running.
Either change the condition to x < HOW_MANY, or initialize x to 1.
EDIT
Did a little leg work, it turns out the sum of all the numbers in the range [1,512] is 131328. The 5th square triangle number is 1413721.
This means after you find the fourth triangle number, you will never sum high enough to find the next one. This will result in the infinite loop you're seeing.
The answer above is still the correct fix, but this is the reason you end up with an infinite loop.
for should be used for iteration and while should be used for condition testing.
The problem, as has been noted, is that your x condition variable is never being incremented to get you out of the outer loop. That's a logic error that can be avoided by using the appropriate control structure for the job.

Error "'=' : left operand must be l-value" when writing an if-statement

I'm having to make this code to run a dice game, it's my first game program and I've encountered some errors I've never seen before so I've done my best to fix them. So the only errors I have left are these:
'=' : left operand must be l-value
for the last three if statements. I know that's probably only the beginning of my problems but I'm new to all this so any advice is GREATLY appreciated.
#include <iostream>
#include <ctime> //Include Header file for time functions
#include <cstdlib> //Include Header file for random number generators
#include "graph1.h"
using namespace std;
int main()
{
//Variable Declaration
int rv1 = 0; //Random number for the 1st dice
int rv2 = 0; //Random number for the 2nd dice
int seed=0;
int wager=0;
//Display graphics
displayGraphics();
cout<< "Wager";
cin>>wager;
//Initialize random number generator
srand(time(0));
//Generate two random numbers between 1 and 6 inclusive
rv1 = (rand()%6)+1; /* Function rand() generate a random number,
(rand()%6+1) generate a random number between 1&6 */
rv2 = (rand()%6)+1;
//rv1
if(rv1=1)
{cout<<displayBMP("1.bmp",200,150);}
else
{ if (rv1=2)
cout<<displayBMP("2.bmp",200,150);}
if (rv1=3)
{cout<<displayBMP("3.bmp",200,150);}
if (rv1=4)
{cout<<displayBMP("4.bmp",200,150);}
if (rv1=5)
{cout<<displayBMP("5.bmp",200,150);}
if (rv1=6)
{cout<<displayBMP("6.bmp",200,150);}
//rv2
if(rv2=1)
{cout<<displayBMP("1.bmp",200,250);}
if (rv2=2)
{cout<<displayBMP("2.bmp",200,250);}
if (rv2=3)
{cout<<displayBMP("3.bmp",200,250);}
if (rv2=4)
{cout<<displayBMP("4.bmp",200,250);}
if (rv2=5)
{cout<<displayBMP("5.bmp",200,250);}
if (rv2=6)
{cout<<displayBMP("6.bmp",200,250);}
if (wager<5)
{
cout<<displayBMP("smiley.bmp",250,100);
gout<<setPos(150,280)<<"Your wager of"<<wager<<"is less than required $5/";
gout<<setPos(150,295)<<"Please re-run program and enter larger amount!/n";
return-1;
}
if (((rv1+rv2)%2)=0)
{ gout<<setPos(200,280)<<"Dice total"<<(rv1+rv2)<<endg;
cout<<"You win $2 extra for even roll!/n";
cout<<"Your winnings:$2+Original Wager:$"<<wager<<"=$"<<wager+2<<endg;
}
if(rv1+rv2=7)
{gout<<setPos(200,280)<<"Dice total"<<(rv1+rv2)<<endg;
cout<<"Youre lucky today!/n";
cout<<"You double your wager/n";
cout<<"Your winnings:$10+Original Wager=$"<<wager<<"=$"<<wager*2<<endg;
}
if(((rv1+rv2)%2)=1)
{gout<<setPos(200,280)<<"Dice total"<<(rv1+rv2)<<endg;
cout<<"You lose $2 for odd roll!/n";
cout<<"Original Wager:$"<<wager<<"Losses:$2=$"<<wager-2<<endg;
}
return 0;
}
= is used for variable assignment in C++. You need to use == for comparison tests:
if (((rv1+rv2)%2)==0)
Note too that if-statement conditions written like this:
if(rv1=1)
will always evaluate to true because rv1=1 returns the result of the assignment which is 1. This is why some C++ programmers write conditions like this:
if(1==rv1)
which prevents you from accidentally forgetting the second = because:
if(1=rv1)
is a compile-time error. Of course, writing conditions like this is primarily a matter of style. I personally do not use this method because it doesn't read very well in my opinion.
You are using the assignment operator = everywhere in the if statements instead of the comparison operator == starting from here
if(rv1=1)
{cout<<displayBMP("1.bmp",200,150);}
There must be
if(rv1 == 1)
{cout<<displayBMP("1.bmp",200,150);}
and so on.
.

C++ program to compute lcm of numbers between 1 to 20 (project euler )

as the title explains this is a program to find lcm of numbers between 1 to 20. i found an algorithm to do this, here's the link
http://www.cut-the-knot.org/Curriculum/Arithmetic/LCM.shtml
there is a java applet on the webpage that might explain the algorithm better
Problem: i wrote the code compiler shows no error but when i run the code the program goes berserk, i guess may be some infinite loopig but i can't figure it out for the life of me. i use turbo c++ 4.5 so basically if anyone can look at the code and help me out it would be great . thanks in advance
Algorithm:
say we need to find lcm of 2,6,8
first we find the least of the series and add to it the number above it, i.e the series become
4,6,8
now we find the least value again and add to it the intitial value in the column i.e 2
6,6,8
so the next iteration becomes
8,6,8
8,12,8
10,12,8
10,12,16
12,12,16
14,12,16
14,18,16
16,18,16
18,18,16
18,18,24
20,18,24
20,24,24
22,24,24
24,24,24
as you can see at one point all numbers become equal which is our lcm
#include<iostream.h>
/*function to check if all the elements of an array are equal*/
int equl(int a[20], int n)
{
int i=0;
while(n==1&&i<20)
{
if (a[i]==a[i+1])
n=1;
else
n=0;
i++;
}
return n;
}
/*function to calculate lcm and return that value to main function*/
int lcm()
{
int i,k,j,check=1,a[20],b[20];
/*loading both arrays with numbers from 1 to 20*/
for(i=0;i<20;i++)
{
a[i]=i+1;
b[i]=i+1;
}
check= equl(a,1);
/*actual implementation of the algorith*/
while(check==0)
{
k=a[0]; /*looks for the least value in the array*/
for(i=0;i<20;i++)
{
if(a[i+1]<k)
{
k=a[i+1]; /*find the least value*/
j=i+1; /*mark the position in array */
}
else
continue;
}
a[j]=k+b[j]; /*adding the least value with its corresponding number*/
check= equl(a,1);
}
return (a[0]);
/*at this point all numbers in the array must be same thus any value gives us the lcm*/
}
void main()
{
int l;
l=lcm();
cout<<l;
}
In this line:
a[j]=k+b[j];
You use j but it is unitialized so it's some huge value and you are outside of the array bounds and thus you get a segmentation fault.
You also have some weird things going on in your code. void main() and you use cout without either saying std::cout or using namespace std; or something similar. An odd practice.
Also don't you think you should pass the arrays as arguments if you're going to make lcm() a function? That is int lcm(int a[], int b[]);.
You might look into using a debugger also and improving your coding practices. I found this error within 30 seconds of pasting your code into the compiler with the help of the debugger.
Your loop condition is:
while(n==1&&i<20)
So your equl function will never return 1 because if n happens to be 1 then the loop will just keep going and never return a 1.
However, your program still does not appear to return the correct result. You can split the piece of your code that finds the minimum element and replace it with this for cleanliness:
int least(int a[], int size){
int minPos = 0;
for(int i=0; i<size ;i++){
if (a[i] < a[minPos] ){
minPos = i;
}
}
return minPos;
}
Then you can call it by saying j = least(a, 20);. I will leave further work on your program to you. Consider calling your variables something meaningful instead of i,j,k,a,b.
Your equl function is using array indices from 0-20, but the arrays only have 1-19
j in lcm() is uninitialized if the first element is the smallest. It should be set to 0 at the top of the while loop
In the following code, when i=19, you are accessing a[20], which is out of the bounds of the array. Should be for(i=0;i<19;i++)
for(i=0;i<20;i++) {
if(a[i+1]<k)
You are not actually using the std namespace for the cout. this should be std::cout<<l
Your are including iostream.h. The standard is iostream without the .h, this may not work on such an old compiler tho
instead of hard-coding 20 everywhere, you should use a #define. This is not an error, just a style thing.
The following code does nothing. This is the default behavior
else
continue;

trying to sort a simple string in c++

#include "stdio.h"
#include "conio.h"
#include <iostream>
using namespace std;
int main (void)
{
char my_char[] = "happy birthday";
int i;
bool j=false;
char my_char_temp[1];
do
{
for (i=0;i<sizeof(my_char)-2;i++)
{
j=false;
if (my_char[i+1] < my_char[i])
{
my_char_temp[0]=my_char[i+1];
my_char[i+1] = my_char[i];
my_char[i] = my_char_temp[0];
j=true;
}
}
}while (j);
cout << my_char;
}
What am I doing wrong?
I'm just trying to sort the letters within the char.
The output I get is completely wrong.
You want to use strlen() rather than sizeof.
You are resetting j to false each and every time you compare two characters.
This means that, if you swap two characters, and you are NOT at the end of your array, you will forget that you have swapped them.
Move the j=false; from inside the for-loop to just inside the do-loop.
And you owe me a bottle of Jack for saving your ass on a homework assignment on Sunday afternoon.
I don't know what are you trying to implement with your sizeof(...) - 2 and etc, but what you probably want to get can be done this way:
#include <iostream>
#include <algorithm>
int main() {
std::string s("happy birthday");
std::sort(s.begin(), s.end());
}
Consider what happens inside this loop:
for (i=0;i<sizeof(my_char)-2;i++)
If you find a pair of values to swap, setting j to true, you'll continue iterating through that loop, and set j back to false on the next iteration. As a result, the program is going to exit as soon as the last two characters in the string are in sorted order, regardless of whether the rest of the string is sorted.
Instead, as soon as you find a pair of characters to swap, you want to start over again at i=0. The simplest way to do that is add a break; statement after your j = true line. With that fix, this works correctly.
Alternately, you could move the initial j = false line outside the loop, which would solve the problem in a slightly different way.
You are actually very close. The only problem is that
j=false;
needs to be in the outer loop. As is, j is cleared every time the inner loop executes.
With this fix, your program works fine for me.
Stylistic errors, however, are another story.
I could be mistaken but it looks like you're trying to do a bubble sort?
And it's i < sizeof(my_char)-2 because he's using a 0-based, null terminated string, and he doesn't want to sort the null terminator.
Try just repeating the condition of the inner loop, using j instead of i, and see if that works? Note that this has a run time of O(n^2) and you can get sorts down much much faster than that if you need to. Alternately you can move the boolean out of the for and into the do loop.
for (i=0;i < sizeof(my_char)-2;i++)
for (i=0;i<sizeof(my_char)-2;i++)
{
if (my_char[i+1] < my_char[i])
{
my_char_temp[0]=my_char[i+1];
my_char[i+1] = my_char[i];
my_char[i] = my_char_temp[0];
}
}