Nested loops and modulus c++ [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am learning C++ and I have a problem with my program. It should print out following if n=11:
*---------*
-*-------*-
--*-----*--
---*---*---
----*-*----
-----*-----
----*-*----
---*---*---
--*-----*--
-*-------*-
*---------*
This is my code, which works correctly with n=5, but not with greater numbers:
#include <iostream>
using namespace std;
int main ()
{
int n;
cout << "Enter size (n x n): " << endl;
cin >> n;
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
if (i%n==j%n) cout << '*';
else if (i%(n-i)==j%(n-j)) cout << '*';
else cout << '-';
}
cout << endl;
}
return 0;
}
This is being printed out if n=11:
*---------*
-*----*--*-
--*-----*--
---*---*---
----*------
-----*-----
-*----*--*-
---*---*---
--*-----*--
-*----*--*-
*---------*
I see that I have successfully wrote how to print out one of '*' diagnoles. But something isn't working with other one, which is going backwards.
Unfortunately, I am not being able to resolve this problem and need your advice. What am I doing wrong? How to debug such problems?

This problem is really simple to debug.
Take a look at the first erroneous *. It appears at the position with i=1, j=6. With n=11, your condition i%(n-i)==j%(n-j) becomes 1%(11-1) == 6%(11-6) which is effectively true because the expression evaluates to 1 on both sides.
What is behind this expression? Why do you use this kind of if to determine whether the cell belongs to the second diagonal? Try to write down each pair i, j which should be printed on the second diagonal, and you should notice a more simple pattern.
P.S. In the expression if (i%n==j%n) you don't have to take operands modulo n, because both of them are less than n, so it is redundant and may be rewritten simply as if (i == j).

Related

C++ sentence palindrome [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Hi there I have attached my code below and it is not working. I want to eliminate all possibles except number or character. Also no upper and lower case problem. But I don't know why it's not working even after I've tried this far. Please any help would be appreciated.
// C++ program to find if a sentence is
// palindrome
//#include <bits/stdc++.h>
#include <iostream>
#include <string>
#include <ctype.h>
using namespace std;
// To check sentence is palindrome or not
bool sentencePalindrome(string sentence)
{
int j = 0;
int l = sentence.length() - 1;
// Compares character until they are equal
while (j < l) {
//removing spaces and special characters
while(j<l&& isalnum(sentence[j])==0)
j++;
while(j<l && isalnum(sentence[l])==0)
l--;
//Checking if not palindrome
if(toupper(sentence[j])!=toupper(sentence[l]))
{
return false;
}
else
{
j++;
l--;
}
}
return true;
}
// Driver program to test sentencePalindrome()
int main()
{
string sentence;
cout << "enter sentence!" << endl;
cin >> sentence;
int result = sentencePalindrome(sentence);
if (result==1)
cout << "Sentence is palindrome.";
else
cout << "Sentence is not palindrome.";
return 0;
}
Your main issue appears to be the way you are reading in you input in your Main function. Using >> in C++ will only read in one word at a time, so you are not working with the full sentence in the function sentencePalindrome().
You should look at using getline() instead to be able to read an entire sentence in as input.
If you use the debugger, it is much easier to spot the problem. I took your code above and set a breakpoint right as the variable l is being declared on line 13 (you can see the orange dot to the left of the code for it).
When you reach that breakpoint when running the code, you can see that the value of sentence = "Test" down at the bottom, even though my input at the command line was Test the sentence.
Once you fix how you get input, you can check the logic of your program and see if it functions correctly. If you are unfamiliar with debugging, putting in a little time to learn GDB now will save you hours of frustration while coding in the future!

If statement not excepting line of text? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
This code should ask for in put with "What is If (selection)?"
and this part it does. but once you input the answer as "Provides the ability to either do a block of code or skip that block of code." the out come should be "Correct!" but instead it either asks to press key to end or re asks the question. does anyone have and advice as to how i could fix this?
srand((unsigned)time(0));
int random_interger;
int lowest = 2, highest = 18;
int range = (highest - lowest) + 1;
for (int index = 0; index < 20; index++) {
random_interger = lowest + int(range*rand() / (RAND_MAX + 1.0));
if (random_interger == IF) {
cout << " What is If (selection)?" << endl;
cin >> IFs;
if (IFs == "Provides the ability to either do a block of code or
skip that block of code.") {
cout << "Correct!" << endl;
}
string IFs;
cin >> IFs;
Even if the user types exactly the long line you expect (he won't), this wouldn't work. cin >> into a string will read just one word. You would get only "Provides".
Look up the getline API. But even then, I doubt anyone would type those lines exactly.

From the user's input total the odd and even numbers. input numbers in between 0 to 99 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
#include <iostream>
using namespace std;
int main()
{
int i,t,x[20], even, odd, prime;
cout << "Enter 20 integer numbers from 0 to 99: "<<endl;
for (i=1;i<=20;i++)
{
cout << "Input " << i <<":";
cin >> x[i];
}
cout << "\nPrime numbers are: " << endl ;
prime=1;
for (i=2; i<=20 ; i++)
{
for(t=2;t<x[i];t++)
{
if(x[i]%t==0)
{
prime=0;
}
}
if(prime==1)
{
cout << x[i] << endl;
}
prime=1;
}
for(i=1; i<=20; i++) // this is where i have problem.
{
if(x[i]% 2 == 0)
{
even++;
}
else
{
odd++;
}
}
cout << "Number of odd numbers: " << odd << "\n";
cout << "Number of even numbers: " << even << "\n";
return 0 ;
}
When i compile it shows even (40) and odd (10) for input of 0 till 19. Where it should show even 10(including the 0) and odd (10). Im not sure where am i doing it wrongly. I hope someone can help me improve the code.
Variables even and odd are never set to a known value, so you are not formally allowed to read from them. Doing so invokes that most infamous Standardese concept: undefined behaviour. So the values of these variables could be right or could be wrong; the variables and all code trying to read them could be optimised entirely out of your program; or anything can happen. You cannot rely on these variables doing anything right. All attempts to read them make your program ill-formed, so now it can do anything, including things you would never have imagined.
You should search for the abundant background info about these concepts, but I like to think I made a fairly decent summary here: https://stackoverflow.com/a/38150162/2757035
Also, as Thomas points out in the comments, you appear not to understand how array indexing works: Indexes are 0-based. So, int i[20] declares 20 elements numbered from 0 to 19. You try to access index 20, which is not part of the array and hence is more undefined behaviour.

an error i can't seem to find [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am a beginner and still learning C++ I was playing with vectors to see what will happen.whenever I start it gives me a debug error.
here is the code
int main()
{
vector<int> num;
int i = 0;
while (i != 1000)
{
++i;
num.push_back(i);
cout <<num[i]<<"\t"<< sqrt(num[i]) << "\n";
}
}
Problem lies in the order of operations inside while() loop:
while (i != 1000)
{
++i;
num.push_back(i);
cout <<num[i]<<"\t"<< sqrt(num[i]) << "\n";
}
i starts from 0. In each iteration, you push_back an element and then print it using counter i - after its incrementation. So, num[i] refers to a non-yet-existing element.
Change your code to:
while (i < 1000)
{
num.push_back(i + 1);
cout <<num[i]<<"\t"<< sqrt(num[i]) << "\n";
++i;
}
The index of a vector starts from zero. In your code you were always accessing 1 index ahead of what you were updating(or pushing).
When I incremented i after the two statements it worked fine.
I dont know how but it worked fine.
Thanks everyone.
int main()
{
vector<int> num;
int i = 0;
while (i != 1000)
{
num.push_back(i);
cout <<num[i]<<"\t"<< sqrt(num[i]) << "\n";
++i;
}
}
Make sure that you are using
#include<vector>
#include<iostream>
using namespace std;

C++ for loops "Statement has no effect" warning? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
so I just started learning programming with C++ and I'm currently messing with basic console programs. I wanted to make a little spam program. here's the code :
#include <iostream>
#include <string>
using namespace std;
string a;
int b;
void repetition(){
cout << "Please enter the number of time you want the text to be spammed" << endl;
cin >> b;
}
void text(){
cout << "Please enter the text you want to spam." << endl;
cin >> a;
for(;b == 0;){
cout << a << endl;
b - 1;
}
}
int main()
{
cout << "Welcome to your auto-spammer!!" << endl;
repetition();
text();
return 0;
}
I'm getting a warning saying "statement has no effect" for my for statement at line 20. I wanted to know why and how I could fix this. Thank you.
The for loop executes while the second statement is true. So unless you enter 0, it will never execute.
The warning is for b - 1; . This reads the value of b, subtracts 1, and does nothing with the result. You probably meant b = b - 1; (which can also be written as b -= 1;, or --b;).
I'm guessing this is line 20:
b - 1;
That line by itself does nothing. The result of b-1 is never assigned to anything.
Try --b, which will decrement b by 1 and re-assign the result of that operation to b.
In text(), b-1 indeed does nothing, you probably meant --b. The first returns an rvalue which is then discarded, while the second decrements b by one and results in b (though you should look up the difference between --b and b-- to understand how that statement actually works). That said, the more colliquial way to do it is like this:
for(; b > 0; --b) //Also keep in mind that the second section of a for statement
//is the continue condition, not exit
cout << a << endl;
You want to do print the text N number of times, so the proper loop to use is:
for (int i=0; i < b; i++)
cout<<a<<endl;
Modifying b is generally not a good idea, you might need the value the user entered later on.