Test case not passed using while loop in C++ - c++

My Need:
Using a while loop greet as many names as that are available on the stdin. Stop when you read the string '42' as a name.
My Coding:
#include<iostream>
using namespace std;
int main()
{
int input=1;
int i= 0;
string name;
while(input<=i)
{
cin>>name;
if(name=="42")
{
break;
}
else
{
cout<<"Hello "<<name<<"!";
i++;
}
}
return 0;
}
Result:
For input 42, test case is passed. For other input, test case failed. Please post your answer.
Answer After ~1 Year:
Very sorry for this question . This is I asked when I have 0 knowledge about C++. This may be useful for the freshers.

Your loop is flawed
int input=1;
int i= 0;
string name;
while(input<=i)
as input is greater than i to start with
You think the test case works for 42 but actually the logic inside your loop is never executed. It is simply the case that the console output is the same (i.e. there is none) but your code never gets as far as the cin to check the input is 42

Your code doesn't ever enter while since the condition is always false.
Just use,
....
while(1)
{
....
This will run your loop indefinitely, and break whenever 42 is encountered.

Your code does not even run when you pass 42, because input is greater than i.
while(input<=i) // input = 1, i = 0, 1 > 0
What you probably want is an infinite loop:
while (true)

Your Code has these Problems:
It won't enter the while loop as input is initialized to 1 and i is initialized to 0.While checking the condition *while(input<=i)*i.e., while(1<=0) which is false it won't execute the statements below.
-
My Solution:
#include<iostream>
using namespace std;
int main()
{
int input=0;
int i= 1;
string name;
while(input<=i)
{
cin>>name;
if(name=="42")
{
break;
}
else
{
cout<<"Hello "<<name<<"!";
i++;
}
}
return 0;
}
Initializing input with 0 and i with 1 will give you the desired output.

First of all, Sorry for my basic question. The loop is not initiated. Because the input is 1 and i is 0. But the condition I given is input<=i. Because of the false condition, the control is not entering in loop

Related

While loop and do while loop only running once in a calculator program. C++

Was trying to run a simple calculator using a while loop and internal class. My issue is that I used a while loop that had the condition that when a boolean called flag is equal to true it would continually run the program over and over. To exit the while loop I included a section to ask the user if it wanted to continue and allowed them to input a value to the flag. No matter how many different versions of the conditions I use the loop only runs with once. I currently have a do while loop that checks if an int called loop is less than 2 which is initialized to have the value of 1. After presenting the value it increments int loop so that it is 2 and doesn't meet the loop requirements. Then asks the user if they want to continue, which if true resets the value to 1. Still hasn't worked and nothing online has shown the same issue or a solution, even in different languages. Thank you to any additions.
Code: (C++)
// main.cpp
// Calculator
//
// Created by yared yohannes on 12/10/21.
//
class calculation{
public:
calculation(){
}
int add(int first, int second){
int result= first+second;
return result;
}
int minus(int first, int second){
int result= first-second;
return result;
}
int multi(int first, int second){
int result= first*second;
return result;
}
int divide(int first, int second){
int result= first/second;
return result;
}
};
#include <iostream>
using namespace std;
int main(){
int first=0,second=0;
bool flag=true;
char sign;
int loop=1;
calculation calc;
cout<<"Welcome to the calculator program.\n";
do{
cout<<"Please enter the first value: ";
cin>>first;
cout<<"Please enter the desired operation(+,-,*,/): ";
cin>>sign;
cout<<"Please enter the second value: ";
cin>>second;
if(sign=='+'){
cout<<calc.add(first, second)<<"\n";
}
else if(sign=='-'){
cout<<calc.minus(first, second)<<"\n";
}
else if(sign=='*'){
cout<<calc.multi(first, second)<<"\n";
}
else if(sign=='/'){
cout<<calc.divide(first, second)<<"\n";
}
cout<<"Do you want to continue(true or false): ";
cin >> flag;
loop++;
if(flag==true){
loop=1;
}
}while(loop<2);
}
In C++ bools are stored as 0 or 1 values. 0 is false and 1 is true. If you're putting in "true" for the cin statement it won't work so loop will always increase. What you have to do is put in 0 or 1 into the console. You could also store the input as a string and use if statements to check if it is "true" or "false" and set the boolean value based on that. Like this:
#include <string>
/*
The code you have
*/
int main() {
string booleanInput;
//Code you have
cin >> booleanInput;
if(booleanInput == "true") {
flag = true;
} else if(booleanInput == "false") {
flag = false;
}
//Other code you have
}

infinity while loop when have recursive function

I'm solving a problem. I want a function that returns all ways to make different positive int number plus equal to that number, for example 6 will be 1+5 ,2+3+1,2+4 so will be 3
but my solution return infinity loop
#include <iostream>
using namespace std;
int find(int num,int before)
{
int first=1;
int count=1;
int end =num-1;
if(end-first==0) return count;
while(end-first!=1&&end-first!=0)
{
if(end==before||first==before) continue;
first++;
end--;
}
before=first;
return count+find(end,before);
}
int main()
{
int a;
cin>>a;
int x=find(a,1);
cout<<x;
}
i try cout "a" in loop and repeat forever. Please help me.
EDIT: My code just solve a piece of problem, so it not solution, i'll try to close topic, thanks all
In this concept first will always be 1 and before will always be 1 because the first is never incremented here as the instruction is not reached.
first is initialized by 1 and before by 1, that means before==first is true and the loop will ignore all other instructions after continue.
and since you are comparing end==before||first==before this will always be true, because even when end==before is false the second test will be true. The test logic of false||true is true.

Programming Principles and Practice using C++ while-loop drill. Can't find a way to exit the loop

I'm going through Bjarne Stroustrup's 'Programming : Principles and Practice using C++" and I've got a drill which tells me to write a program that consists of a while-loop that (each time around the loop) reads in two ints and then prints them and that it should exit when "|" is entered. I've written the program(I'm sure there's a easier way of writing it, but I've got the "gift" of overcomplicating things), but I can't find a way of exiting the loop. Here's the code:
#include <iostream>
#include <vector>
int main()
{
std::vector<int> answers;
int answer;
int intCounter=0;
while(answers.size()<=2 )
{
if(answer=='|')
{
return 0;
}
std::cin>>answer;
answers.push_back(answer);
++intCounter;
if(intCounter==2)
{
for(int x : answers)
{
std::cout<<x<<'\n';
}
answers.clear();
intCounter=0;
}
}
return 0;
}
Basically if I write an if statement to check if answer is equal to '|', the compiler thinks i meant the int value of it(124 or something like that) and terminates the loop when I write 124, and that's clearly not what I want. I've tried to look over the internet for a way of converting an int into a char, but I haven't understood anything from there. The simplest solution would be the best.
cin >> answer will fail when the next non-whitespace character to be read is not a number. You can use that behavior to end the loop.
// Break inside the loop.
while( true )
{
std::cin>>answer;
// If there was an error in reading, break out of the loop.
if ( !std::cin )
break;
answers.push_back(answer);
++intCounter;
if(intCounter==2)
{
for(int x : answers)
{
std::cout<<x<<'\n';
}
answers.clear();
intCounter=0;
}
}
Two changes:
If your task is to just print numbers you could just use string.
You are checking value of answer to | before its even been input.
So
#include<iostream>
#include <vector>
#include<string>
using namespace std;
int main(){
std::vector<string> answers;
string answer;
int intCounter=0;
while(answers.size()<=2 ){
std::cin>>answer;
//after input
if(answer=="|"){
return 0;
}
answers.push_back(answer);
++intCounter;
if(intCounter==2){
for(int x=0;x< answers.size();x++){
std::cout<<answers[x]<<'\n';
}
answers.clear();
intCounter=0;
}
}
return 0;
}

Issue with scanf("%s")

include <iostream>
#include <stdio.h>
using namespace std;
int main() {
int n;
scanf("%d",&n);
int l,k;
for(int i=0;i<n;i++)
{
scanf("%d %d",&l,&k);
char ch[l+1];
/****/ scanf("%s",ch);
printf("Are we here");
char ci=ch[0];
int flips=0;
int count=0;
for(int j=0;j<l;j++)
{
if(ch[j]==ci)
{
count++;
if(count>k)
{
flips++;
count=1;
if(ci=='1')
{
ci='0';
ch[j]='0';
}
else if(ci=='0')
{
ci='1';
ch[j]='1';
}
}
}
else if(ch[j]!=ci)
{
if(ci=='1')
ci='0';
else if(ci=='0')
ci='1';
count=1;
}
}
printf("\n%d",flips);
printf("\n%s",ch);
}
return 0;
}
An input with 3 test cases and each test case having two lines of input.
3
2 1
11
2 2
11
4 1
1001
should give the output
1
10
0
11
2
1010
This is basically a code that does some standard programming contest stuff. It takes in the number of test cases, and for each of the test cases prints out the required answer in two lines .Now when I type all the inputs line by line it works fine and I get all the outputs. But when I just copy paste all the inputs together I only get everything but the last output and I have to press the enter key to get the last output. Now I did some basic debugging and found out that it has something to do with the scanf("%s",ch) line of code. Any help.. Also I felt the logic of the program doesnt matter. I'm missing something far more basic here...
I think "\r\n" are not copied when you copy paste the text

My C++ Program isn't executing my cout code

I am learning C++, and I am trying to make a simple program which prints 5 variables, as my book said to do this, but it is not executing my code.
#include<iostream>
using namespace std;
int main()
{
//Program Code below
return 0;
char letter; letter = 'A'; //Declared, then initialized
int number; number = 100; //Declared, then initialized
float decimal = 7.5; //Declared AND initialized
double pi = 3.14159; //Declared AND initialized
bool isTrue = false; //Declared AND initialized
cout<<"Char letter: "<<letter<<endl;
cout<<"Int number: "<<number<<endl;
cout<<"Float decimal: "<<decimal<<endl;
cout<<"Double pi: "<<pi<<endl;
cout<<"Bool isTrue: "<<isTrue<<endl;
}
As soon as your code executes this line
return 0;
no other lines of your code will be executed - from a practical point of view, your program will have ended. Move this line down so that it is the last line of code executed by your main() function.
Your problem is that you are returning from main before doing anything:
int main()
{
return 0; // HERE!!
// no code after return gets executed
}
Your return 0; should be at the end of main, not the start
Please re-position the "return 0;" statement
Since main is a function that returns an integer, the execution of the main function is primarily to return some integral value. As soon as the value is returned, the function assumes its job is complete and hence does no longer hold the control of the program.
Your code:
#include<iostream>
using namespace std;
int main()
{
return 0; // Function thinks its job is done hence it ignores everything after it.
...some other code
}
Actually what you wish to do:
#include<iostream>
using namespace std;
int main()
{
... useful code
return 0; // Okay. Returning is alright, as the useful job is done.
}