#include <iostream>
using namespace std;
int main(){
int x,y,z;
int a,b,c;
cout<<"Enter Values of first set: ";
cin>>x;
cin>>y;
cin>>z;
cout<<"Enter Values of first set: ";
cin>>a;
cin>>b;
cin>>c;
if(x!=a || y!=b || z!=c)
{
//some statements
}
else
{
}
}
when i run this code is transfer control to else but i don't know which one or two conditions getting false or may be all getting false
i want to know in return that which if condition was TRUE and which was FALSE but only with single if ,I don't wanna make multiple if and else.Thanks
What you can do is some pretty nasty if construct to set a state with each condition like this:
int s = 0; // state
if(x!=a && s=1 || y!=b && s=2 || z!=c && s=3)
so int s would be the state of the first condition that is true.. but I would not do that :) just use multiple if's if possible
if you want to know if multiple of those conditions are true, you can also do that with bit logic inside the if, if you really need that I can extent this answer.
Related
I'm learning at GCC and while I was trying various solutions to verify the entry of a certain word, IF Word = Word {do something;}
It seems that in C it cannot be done directly and so I tried this solution that seems to work:
#include <stdio.h>
#include <string.h>
int main(){
int CClose = 0;
int VerifyS = 0;
char PWord[30] ={'\0'};
do {
printf("\n Type a word: ");
scanf(" %s", &PWord);
VerifyS = strncmp(PWord, "exit", 4);
if (!VerifyS){ CClose = 1;}else{ printf("\n The Word is:%s", PWord);}
}while (CClose != 1);
return 0;
}
I wanted to know if there is another way to do the same thing.
Thank you.
What you've written is essentially the most common way to do this. There is indeed no way in C to compare two strings in a single expression without calling a function.
You can cut out the temporary variable VerifyS if you like, by writing
if (!strncmp(pWord, "exit", 4)) { /...
or, perhaps slightly clearer
if (strncmp(pWord, "exit", 4) == 0) { /...
I would like to test if all elements in an array (or list) satisfy a condition. But I would like to do it in the cleanest and most optimized way I can.
I used to do something like this (exemple in c++) :
vector<unsigned> vct; // put anything in it
bool verified = true;
for (unsigned elmt: vct) {
if (!mycondition) {
verified = false;
break;
}
} // then use verified to check if condition is satisfied for each element
But then someone told me that you usally want to initialize verified to false and then turn it to true. This made me do :
vector<unsigned> vct; // put anything in it
bool verified = false;
unsigned count = 0;
for (unsigned elmt: vct) {
if (mycondition) {
++count;
}
}
if(count == vct.size())
verified = true; // then use verified to check if condition is satisfied for each element
But this solution does not seem optimized at all because we use a counter and we have to loop through all the elements while the first solution stopped as soon as it finds a "bad" element.
So here is my question.
What is the cleaner and most optimized way to test if all elements in array satisfy a condition ?
I tried to solve Petersen Graph question without any success. What's wrong with this code? You may say that this is not an efficient solution, it's ok. Here I am, doing DFS for given graph.
sruct ss holds a graph. Each String is saved in a Set and whenever recursion terminates an output is produced. I'm not able find the test case where this approach is failing. Can you give me a test case where this approach will fail?
#include<bits/stdc++.h>
using namespace std;
struct ss{
int p;
int a[3];
char s[3];
};
string get(int k){
switch(k){
case 0:return "0";
case 1:return "1";
case 2:return "2";
case 3:return "3";
case 4:return "4";
case 5:return "5";
case 6:return "6";
case 7:return "7";
case 8:return "8";
case 9:return "9";
}
}
void traverse(string s,ss z[10],int index, set<string> &s1,string s2,int v){
int p = s[index]-'A',i,j;
if(v!=-1)s2 +=get(v);
if(!s[index]){
s1.insert(s2);
return;
}
if(v==-1){
traverse(s,z,index+1,s1,s2,z[2*p].p);
traverse(s,z,index+1,s1,s2,z[2*p+1].p);
}
else{
if(v>=5){v = v-5;v = 2*v+1;}
for(i=0;i<3;i++){
if(z[v].s[i]==s[index]){
traverse(s,z,index+1,s1,s2,z[v].a[i]);
break;
}
}
for(j=0;j<3;j++){
if(z[v].s[j]==s[index]){
traverse(s,z,index+1,s1,s2,z[v].a[j]);
break;
}
}
}
}
int main(){
string s;
set<string> s1;
int t;
ss z[ ]={
{0,{1,4,5},{'B','E','A'}},
{5,{0,7,8},{'A','C','D'}},
{1,{0,2,6},{'A','C','B'}},
{6,{1,8,9},{'B','D','E'}},
{2,{1,3,7},{'B','D','C'}},
{7,{2,5,9},{'C','A','E'}},
{3,{2,4,8},{'C','E','D'}},
{8,{3,5,6},{'D','A','B'}},
{4,{0,3,9},{'A','D','E'}},
{9,{4,6,7},{'E','B','C'}}
};
cin>>t;
while(t--){
s1.clear();
cin>>s;
traverse(s,z,0,s1,"",-1);
if(s1.end()==s1.begin()){
cout<<-1<<"\n";
}
else
cout<<*s1.begin()<<"\n";
}
}
The code fails almost every test case I tried. I think the problem is in traverse, in the if statement conditions within the for loops (lines 45 and 51).
if(z[v].s[i]==s[index])
Here, you want index x, such that z[x].p is equal to v. v is not always the correct index, so z[v] is incorrect. Likewise in the other line. Try test cases 'EE' and 'ABCD'.
It would be easiest to reorder the Z array in the order of Z[i].p values, I think.
UPDATE: Thank you for the help. Writing a demo that you could run did help me solve the issue but not in the way that I expected. I think this is a compiler optimization rather than a bug. When the code inside if ( z == true ) is commented out, the conditional statement is skipped entirely and the control returns to if (x). If I put actual code in, we hit the conditional statement when appropriate.
ORIGINAL QUESTION:
I have a std::string and I am iterating through it to determine whether it contains certain characters. If any of these characters are found, I want to exit the for loop and proceed with the next conditional statement. Here is an example:
#include <iostream>
using namespace std;
int main()
{
bool x = true;
bool y = true;
bool z = true;
std::string str;
cout << "Enter string: ";
cin >> str;
if ( x )
{
if ( y )
{
std::string::iterator i;
for ( i = str.begin(); i != str.end(); i++ )
{
cout << "Enter for" << endl;
if ( *i == 'a' || *i == 'b' || *i == 'c' )
{
z = false;
cout << "Exit for" << endl;
break;
}
}
if ( z == true )
{
//cout << "z == true" << endl;
}
}
}
}
The issue is that the program never hits if (z == true). When it breaks out of the loop, control returns to the first conditional statement ( if (x) ).
I tried removing the break and instead setting i = ( str.end() - 1 ). This resulted in the same behavior - it goes back to the for, determines that it's at the last character of the string, and then returns control to the first conditional statement again, skipping the if ( z == true ) as intended.
What am I doing wrong here?
"When it breaks out of the loop, control returns to the first conditional statement ( if (something) )."
When it breaks out of the loop, it has just set b to false, so the if (b == true) code won't run. What am I misunderstanding?
Edit: I think you have oversimplified your code. Clearly that's not the code you're actually running because str never has a value. You need to post an example that we can actually run (but once you have created such an example, you'll probably find the error for yourself. :-) )
The most egregiously redundant code construct I often see involves using the code sequence
if (condition)
return true;
else
return false;
instead of simply writing
return (condition);
I've seen this beginner error in all sorts of languages: from Pascal and C to PHP and Java. What other such constructs would you flag in a code review?
if (foo == true)
{
do stuff
}
I keep telling the developer that does that that it should be
if ((foo == true) == true)
{
do stuff
}
but he hasn't gotten the hint yet.
if (condition == true)
{
...
}
instead of
if (condition)
{
...
}
Edit:
or even worse and turning around the conditional test:
if (condition == false)
{
...
}
which is easily read as
if (condition) then ...
Using comments instead of source control:
-Commenting out or renaming functions instead of deleting them and trusting that source control can get them back for you if needed.
-Adding comments like "RWF Change" instead of just making the change and letting source control assign the blame.
Somewhere I’ve spotted this thing, which I find to be the pinnacle of boolean redundancy:
return (test == 1)? ((test == 0) ? 0 : 1) : ((test == 0) ? 0 : 1);
:-)
Redundant code is not in itself an error. But if you're really trying to save every character
return (condition);
is redundant too. You can write:
return condition;
Declaring separately from assignment in languages other than C:
int foo;
foo = GetFoo();
Returning uselessly at the end:
// stuff
return;
}
I once had a guy who repeatedly did this:
bool a;
bool b;
...
if (a == true)
b = true;
else
b = false;
void myfunction() {
if(condition) {
// Do some stuff
if(othercond) {
// Do more stuff
}
}
}
instead of
void myfunction() {
if(!condition)
return;
// Do some stuff
if(!othercond)
return;
// Do more stuff
}
Using .tostring on a string
Putting an exit statement as first statement in a function to disable the execution of that function, instead of one of the following options:
Completely removing the function
Commenting the function body
Keeping the function but deleting all the code
Using the exit as first statement makes it very hard to spot, you can easily read over it.
Fear of null (this also can lead to serious problems):
if (name != null)
person.Name = name;
Redundant if's (not using else):
if (!IsPostback)
{
// do something
}
if (IsPostback)
{
// do something else
}
Redundant checks (Split never returns null):
string[] words = sentence.Split(' ');
if (words != null)
More on checks (the second check is redundant if you are going to loop)
if (myArray != null && myArray.Length > 0)
foreach (string s in myArray)
And my favorite for ASP.NET: Scattered DataBinds all over the code in order to make the page render.
Copy paste redundancy:
if (x > 0)
{
// a lot of code to calculate z
y = x + z;
}
else
{
// a lot of code to calculate z
y = x - z;
}
instead of
if (x > 0)
y = x + CalcZ(x);
else
y = x - CalcZ(x);
or even better (or more obfuscated)
y = x + (x > 0 ? 1 : -1) * CalcZ(x)
Allocating elements on the heap instead of the stack.
{
char buff = malloc(1024);
/* ... */
free(buff);
}
instead of
{
char buff[1024];
/* ... */
}
or
{
struct foo *x = (struct foo *)malloc(sizeof(struct foo));
x->a = ...;
bar(x);
free(x);
}
instead of
{
struct foo x;
x.a = ...;
bar(&x);
}
The most common redundant code construct I see is code that is never called from anywhere in the program.
The other is design patterns used where there is no point in using them. For example, writing "new BobFactory().createBob()" everywhere, instead of just writing "new Bob()".
Deleting unused and unnecessary code can massively improve the quality of the system and the team's ability to maintain it. The benefits are often startling to teams who have never considered deleting unnecessary code from their system. I once performed a code review by sitting with a team and deleting over half the code in their project without changing the functionality of their system. I thought they'd be offended but they frequently asked me back for design advice and feedback after that.
I often run into the following:
function foo() {
if ( something ) {
return;
} else {
do_something();
}
}
But it doesn't help telling them that the else is useless here. It has to be either
function foo() {
if ( something ) {
return;
}
do_something();
}
or - depending on the length of checks that are done before do_something():
function foo() {
if ( !something ) {
do_something();
}
}
From nightmarish code reviews.....
char s[100];
followed by
memset(s,0,100);
followed by
s[strlen(s)] = 0;
with lots of nasty
if (strcmp(s, "1") == 0)
littered about the code.
Using an array when you want set behavior. You need to check everything to make sure its not in the array before you insert it, which makes your code longer and slower.
Redundant .ToString() invocations:
const int foo = 5;
Console.WriteLine("Number of Items: " + foo.ToString());
Unnecessary string formatting:
const int foo = 5;
Console.WriteLine("Number of Items: {0}", foo);