The Problem of the Solution is that first line will contain total no. of Input and the next line will take three integer and then we have to calculate the result based on the input.So the Problem with my Solution is that the While Loop is Not Terminating.
I have Checked the code several times and thinks that this is happening because of the conditional statement and because of if-else the --t statement is not getting executed.So,what modifications should i do to make the program terminate after t input.
#include<iostream>
using namespace std;
int main()
{
int t{0};
cin>>t;
while(t)
{
double h{0},c{0},t(0);
cin>>h>>c>>t;
if(h>50 and c<0.7 and t>5600)
cout<<"10\n";
else if(h>50 and c<0.7)
cout<<"9\n";
else if(c<0.7 and t>5600)
cout<<"8\n";
else if(h>50 and t>5600)
cout<<"7\n";
else if(h>50 or c<0.7 or t>5600)
cout<<"6\n";
else
cout<<"5\n";
--t;
}
return 0;
}
I expect the Program to terminate after t input but it is not happening.
Outside the loop you have
int t{0};
And inside the loop you have
double h{0},c{0},t(0);
You have two different and distinctive variables t that shadows each other. And inside the loop when you do --t you decrement the variable inside the loop, not the one you use for the looping condition.
You solve this by using descriptive names for your variables, instead of short one-letter names.
Related
I was doing some coding on C++ just to get used to its syntax (I'm Java developer). However, I've written the code below and it takes up the entire RAM in seconds, the more free RAM you have, the faster program takes it up. When I uncomment the cout method to print current string at the end of every loop, it starts to take RAM up drastically slower (10-15mb in a minute). Does printing operation slows the cycle that much, or is there another reason?
#include <iostream>
#include <list>
using namespace std;
int main() {
string inf;
list<string> myList;
for(;;){
inf += "___ ";
myList.push_back(inf);
//cout << inf;
}
}
for(;;) is an infenite loop.
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
Since your statement 2 is empty it defaults to true, so this loop keeps on running.
The reason why this is happening is simply fact that i/o operations are really slow compared to appending list. Therefore this seemed to be work "okay". This loop is just infinite, never stops.
you for(;;) loop is infinite and as such mylist is continually expanded until it has filled your entire RAM. The execution time of appending simple symbol into the list is extremely low, so your RAM is filled extremely fast. When cout is added to the loop, the loop has to output before it can append more to mylist. The execution time of outputting takes significantly longer than appending and as such the time between loops is slowed. This in turn means your RAM will be filled more slowly.
#include <iostream>
using namespace std;
int main()
{
int sqdnumber;
int sqdNumber_result=0;
cout<<"Enter a number:";
cin>>sqdnumber;
cout<<"\n";
while(sqdnumber==0)
{
int remainder=sqdnumber%10;
sqdNumber_result=(remainder*remainder)+sqdNumber_result;
sqdnumber=sqdnumber/10;
}
cout<<sqdNumber_result;
}
I am trying to print sum of square of individual digit but the variable sqdNumber_result is not accessible outside loop. Could you tell me how to solve this? Thank you.
sqdNumber_result is perfectly accessible outside of the loop, and your code compiles fine.
I suspect that you got strange ideas about variable shadowing because your code outputs 0 for any (nonzero) input; that's because you got the while condition wrong: while(sqdnumber==0) won't make you even enter the loop whatever input you provide, and will get you stuck forever in the loop for zero input.
You want while(sqdnumber!=0).
ideone:https://ideone.com/Ba3Nw7
#include <iostream>
using namespace std;
int main() {
int i,n,b25,b50,temp;
cin>>n;
for(i=0;i<n;i++)
{
cin>>temp;
if(temp==25)
b25++;
else if(temp==50)
{
if(b25>0)
{
b25--;
b50++;
}
else
{
cout<<"NO";
return 0;
}
}
else if(temp==100)
{
if(b25>0 && b50>0)
{
b25--;
b50--;
}
else if(b25>2)
b25-=3;
else
{
cout<<"NO";
return 0;
}
}
}
cout<<"YES";
return 0;
}
the test case tried is:
2
25 100
the output on ideone is "NO" which is the correct answer but on the codeforces custom test it gives a "YES",why is that?
One very glaring mistake I can see is not initialising variables b25 and b50.
In your code, you are continuously incrementing and decrementing the two variables, and therefore, your answer goes wrong every time.
I would suggest:
int i,n,b25=0,b50=0,temp=0;
You might be getting a right or a wrong answer because arbitrarily any value can get stored in b25 and b50. Sometimes it may satisfy the NO condition, and at other times, a YES condition.
Had your variables been static or within file scope, they would have been initialised as 0. However, your variable is locally defined, hence its value will be indeterminate, invoking undefined behaviour.
You are using the variables b25, b50 uninitialised, but guessing from your code you assume them to be initially zero.
Their initial value can currently differ from run to run, so putting it a second time on one of those platforms may give more different results. (Unless ideone uses BSD or something where memory is initially zero by default)
hi guys can anyone tell me what's wrong with my 3-way mergesort code?the code I wrote can only sort 4 numbers if you give it more than 4 numbers(by changing size) it ends up with stack overflow error,here is the code:
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
const int size=4;
vector <int> s(size);
void merge(int,int,int);
void mergesort(int,int);
int main(){
for(int i=0;i<size;i++){
cout<<"enter number "<<i+1<<":";
cin>>s.at(i);
}
system("CLS");
cout<<"here are the unsorted numbers:\n";//prints the input values so U can see'em
for(int j=0;j<size;j++)
cout<<s.at(j)<<".";
mergesort(0,size-1);//calls mergesort
cout<<"\nhere are the sorted numbers:\n";
for(int j=0;j<size;j++)
cout<<s.at(j)<<".";
cin.get();
cin.get();
return 0;
}
void merge(int low,int one_third,int high){
int i=low;
int j=one_third+1;
int k=0;
int length=(high-low)+1;
vector <int> u(length,0);
if(k<length){
while((i<=one_third)&&(j<=high)){
if(s.at(i)<=s.at(j)){
u.at(k)=s.at(i);
i++;
k++;
}//end for
else{
u.at(k)=s.at(j);
j++;
k++;
}//end elseif
}//end while
if(j>high)
while(i<=one_third)
{
u.at(k)=s.at(i);
i++;
k++;
}
if(i>one_third)
while(j<=high)
{
u.at(k)=s.at(j);
j++;
k++;
}
for(int n=low;n<k;n++)
s.at(n)=u.at(n);
}
}//end if
void mergesort(int low,int high){
if(low<high){
int one_third=(high-low)/3;//division,it's 3-way mergesort so obviously it's divided by 3
int two_third=2*one_third;
mergesort(low,one_third);
mergesort(one_third+1,two_third);
mergesort(two_third+1,high);
merge(low,one_third,two_third);
merge(low,two_third,high);
}//end if
}
at this point I guess I'm done thinking,Any answer/idea would be appreciated.
Here's a partial inspection of your code. I believe there is an issue debugging a 3 way merge sort with 4 values. You should use more values, such as 6 or 7.
Spaces not tabs for StackOverflow
I'll take a guess that the indentation is because you use tab characters in your code and pasted directly. You'll want to expand the tabs in your next post.
Precompiled Headers
Is your project huge? Does it significantly reduce the build time when you change a header or modify the source code?
I find that stdafx usually is more of a hassle and the time spent resolve defects it causes negates any potential savings by having a precompiled header.
Function prototypes should use named parameters
Can you tell the purpose of the different parameters in your declaration of merge and mergeSort?
Ambiguity breeds defects. 'nuff said.
Main function declared wrong.
The main function always returns an int to the operating system, always. The OS can ignore it.
This mechanism is so that script files can execute your program and test for errors.
Readability prevents defects
Invest in spaces around operators. The time saved by sacrificing spaces is negligible. The debugging time saved by having easy to read code is tremendous, especially when having other people review or inspect your code.
Use intermediate variables
Intermediate variables help clarify your program. They don't cost memory when you tell the compiler to optimize. During debugging, they can help show values during calculations.
The typical idiom for reading into a vector is:
int value;
cin >> value;
s.push_back(value);
The at method may have an overflow issue (or at least your not checking for out of bounds issues). The push_back method will cause the vector to expand as necessary.
Meaningful variable names reduces defects
The variable s has no meaning. Something like original_values or number_container are more descriptive. And again, variable name lengths have nothing to do with improving performance. Readable names help reduce the defects injected.
Not checking state of cin
If I enter "Lion" in response to your 2nd prompt, what will be in the 2nd slot of the array?
Don't trust the Users, they aren't perfect.
Don't clear the screen
It may contain useful data, such as the actual numbers entered. So when you are debugging, and want to know what the User actually typed in, it will be lost and gone forever.
Why cin.get twice?
You are asking the User for input without prompting. And twice. Bad Karma between your program and the User.
See cin.ignore if you want to ignore characters until a specific one is received. Something like this perhaps:
cout << "Paused. Press Enter to continue.\n";
cin.ignore(100000, '\n');
Magic numbers
In function mergesort, you use the numbers 2 and 3. Why? What's their purpose?
Redundant comments
Most programmers realize that the '/' character in a math expression is division. The comment is redundant.
Also, why divide by 3? It's a nasty number. Do you realize you are performing integer division and your product will be truncated? For example: 1/3 == 2/3 == 0.
USE A DEBUGGER
Lastly, a lot of your program's functionality can be verified easier and quicker by using a debugger. A debugger allows you to execute a statement and see the variable values. You can set breakpoints to stop execution at different places. It's a worthwhile educational investment, start now.
A "classic" 3 way merge sort merges runs 3 at a time, alternating between a source and destination array (or vector or list). The code needs to perform up to 3 compares in order to determine the "smallest" of 3 values from each of the 3 runs, then move the smallest value from it's corresponding run to the destination array. The code also has to handle the case where the end of a run is reached, leaving only 2 runs to merge, then the case where the end of the second run is reached, in which case the rest of the third run is moved to the destination array.
For a ram based sort, I'm not sure this is any faster than a normal 2 way merge. For an external sort, with multiple devices or very large read and writes, then a k way merge with k up to 12 or 16 will be faster.
I have following code to divide one number recursively by another number:
#include <iostream>
using namespace std;
int divide(int number,int dividend){
int answer=0;
if (number>dividend || number==dividend ){
answer+=1;
return divide(number-dividend,dividend);
}
return answer;
}
int main(){
cout<<divide(20,5)<<endl;
return 0;
}
but unfortunately I get zero as answer. Do you see what is wrong?
Answer is a local variable. When you run this code, the first call to divide creates an instance of the answer variable, sets it to 0, and then increments it to 1. Then, when you recursively call divide again, it creates a brand new instance of the answer variable, sets that instance to 0, and then increments that instance to 1.
In your final call to divide, it creates a brand new instance of the answer variable, sets that instance to 0, but since now number<=dividend it doesn't increment it, and it returns that instance of answer which is 0.
In the if branch you are incrementing answer but returning something unrelated (the result of the recursive call). I am sure, this is not what you want. Go from there.
You are recursively running the following code:
if (number>dividend || number==dividend ){
answer+=1;
return divide(number-dividend,dividend);
}
But once the recursive calling ends (which is number < dividend), you will ignore the if statement and return 0;
You do int answer=0; in the start of function call, so when the if statement is wrong, it returns 0 so you should define it as input parameter (by reference call) or make it global (not recommended) and do not set it to zero, just set it before your recursive function call.