How to make tri angle with blank inside using c++? - c++

I did try many modifications to my code to make like this, but i not get what i want :
example if i put 7 in variable N the result will show
*
**
* *
* *
* *
* *
*******
this my code
#include <iostream>
using namespace std;
int main() {
for (int x=1; x<=N; x++){
cout<<"*";
for (int y=1; y<x; y++){
cout<<"*";
}
cout<<"\n";
}
return 0;
}
what i must add to my code have to the result like above?

Since others have suggested that this might be homework, here are some tips:
Always make sure you have a valid main signature. int main() is sufficient and main() without a return type is invalid.
Enable warnings. -Wall -pedantic should be sufficient for most cases (i.e, it catches the above mistake) but -Wextra can be useful as well.
using namespace std; is considered bad practice because you may define functions or variable names that clash with imported names. Get into the habit of typing std::. (For example, an assignment may require you to have a distance function, which may conflict with std::distance.
Use descriptive variable names. For a trivial program, x, y and N are fine, but decrease readability. It also helps you visualize the problem you are trying to solve.
We know that y is always going to be at most x because the number of characters per line should equal the current line. For example, line 7 should contain 7 asterisks. We only print a space if y is not equal to zero or x - 1, because that should be our "border". Lastly, the final line should contain all asterisks.
// The amount of asterisks per line is [1, N]
for (int x = 1; x <= N; x++)
{
// x is the amount of characters we want to print per line
for (int y = 0; y < x; y++)
{
// If we at the beginning or end of a line, this is our "border".
// Print an asterisk.
if (y == 0 || (y + 1 == x))
std::cout << "*";
else
{
// Otherwise we are "inside" the triangle.
// If this is the last line, print all asterisks
if (x == N)
std::cout << "*";
else
std::cout << " ";
}
}
std::cout << "\n";
}
Also, as another answer suggested, you can eliminate the need for confusing if structures by putting your condition into a single variable.
bool space_or_asterisk = (y == 0 || (y + 1 == x) || x == N);
std::cout << (space_or_asterisk ? '*' : ' ');

While you've gotten a couple of answers that work, the logic can be quite a bit simpler if you eliminate the confusing if/then/else statements:
#include <iostream>
int main() {
static const char chars[] = "* ";
static const int size = 7;
for (int i=0; i<size; i++) {
for (int j=0; j<size; j++)
std::cout << chars[j!=0 && i!=j && bool(i+1-size)];
std::cout << "\n";
}
}
Although the logic is clearly simpler, you still want to be sure to study it enough to answer any questions about it if you turn this in as homework.

main() {
for (int x=1; x<=N; x++){
for (int y=1; y<=x; y++){
if(y==1||y==x||x==N){
cout<<"*";
}else{
cout<<"*";
}
}
cout<<"\n";
}
return 0;
}

Related

duplicate name checking function for an array

I am still a beginner in C++, so I'm sorry if the question is simple.
I am trying to build a program that asks you to input names and register them to an array. Then, I need to call a function to check if there are any duplicate names. If there are any, it asks the user to input another name.
The problem I'm having is that the function is called whether or not there are duplicates, and always replaces the first name that was entered.
int checking(string stringArray[5]) {
int i, z ;
for (i = 0; i < 5; i++) {
for (z = 0; z < 5; z++) {
if (z != i) { // Makes sure don't check number against itself
if (stringArray[z] == stringArray[i]) {
return i;
}
else {
return 0;
int main(){
for (i = 0; i < 5; i++) {
cin >> stringArray[i];
}
j = checking(stringArray);
if (j == 0) {
cout << "Please re-enter name " << ". Duplicate names are not allowed"
<<'\n';
cin >> stringArray[j];
}
Some observations (ignoring the syntax errors, I assume these are not present in your actual code):
z doesn't need to start at 0 every time, it can start at i + 1 because you dont need to check pairs you have already checked (makes it simpler and runs faster)
you don't want to return in your loop, it will prevent you from checking past the first repeated name. Instead move your reenter statement into the loop.
generally you dont want to use literals (5) in a loop, instead use a variable to store the length of the array and compare to that (this is just a general programming rule, it won't change how the code runs)
Your final checking() function should look closer to:
void checking(string stringArray[5]) {
int i, z ;
// consider replacing 5 with a variable
for (i = 0; i < 5; i++) {
for (z = i+1; z < 5; z++) {
if (stringArray[z] == stringArray[i]) {
cout << "Please re-enter name " <<
". Duplicate names are not allowed" <<'\n';
cin >> stringArray[z];
/* restart the loop user may have entered a */
/* second duplicate from previous entries */
i = 0;
z=i+1;
}
}
}
}

While loop task in c++

I am a beginner in c++ and I am having problems with making this code work the way I want it to. The task is to write a program that multiplies all the natural numbers up to the loaded number n.
To make it print the correct result, I divided x by n (see code below). How can I make it print x and not have to divide it by n to get the correct answer?
#include<iostream>
using namespace std;
int main(){
int n,x=1;
int i=0;
cout<<"Enter a number bigger than 0:"<<endl;
cin>>n;
while(i<n){
i++;
x=i*x;
};
cout<<"The result is: "<<x/n<<endl;
return 0;
}
At very first a principle you best get used to as quickly as possible: Always check user input for correctness!
cin >> n;
if(cin && n > 0)
{
// valid
}
else
{
// appropriate error handling
}
Not sure, why do you need a while loop? A for loop sure is nicer in this case:
int x = 1;
for(int i = 2; i < n; ++i)
x *= i;
If you still want the while loop: Start with i == 2 (1 is neutral anyway) and increment afterwards:
i = 2;
while(i < n)
{
x *= i;
++i;
}
In case of n == 1, the loop (either variant) simply won't be entered and you are fine...
You already have two very good options, but here is an other one you might want to take a look at when you are at ease enough in programming :
unsigned factorial(unsigned value)
{
if (value <= 1)
{
return 1;
}
else
{
return value * factorial(value - 1);
}
}
It's a recursive function, which is kind of neat when used in proper moments (which could not be the case here unfortunately because the execution stack might get so big you fill your memory before you're done. But you can check it out to learn more about recursive functions)
When your memory is full, you then crash your app with what is called actually a stack overflow.
How can I make it so that in the last cout I can only put x and not have to divide x by n to get the correct answer?
It will be better to use a for loop.
// This stops when i reaches n.
// That means, n is not multiplied to the result when the loop breaks.
for (int i = 1; i < n; ++i )
{
x *= i;
}
cout << "The result is: " << x <<endl;

Can't figure out why this output formatting loop is going infinite

My program is supposed to take in a number from user input, determine whether or not it is prime, and then if it is not, output the factors of the entered number, 5 to a line. The 5 to the line part is where everything goes haywire, the loop i wrote should work fine as far as i can tell, however no matter how much i change it around, it does one of two things, 1) goes infinite with either new lines or the first factor, or 2) outputs a line with 5 of each factor. Here's the code:
else
{
cout << "\nNumber is not prime, it's factors are:\n";
for (int x = 2; x < num; x++)
{
factor=num%x;
if (factor==0)
{
int t=0;
cout << x << "\t";
t++;
for (int t; t <= 5; t++) // THE TROUBLE LOOP
{
if(t>=5)
{
t=0;
cout << endl;
}
}
}
}
}
Replace the declaration of t in the loop since you've declared t prior to the loop:
for(; t <= 5; t++)
With int t in the loop declaration you are overriding t as an uninitialized variable that will have a garbage value.
Outside of this problem your loop is infinite since you will be resetting t to 0 whenever it equals 5.
In the for loop change the
int t
to
t=0
it is the
for(int t,t<=5,t++)
the int t part in particular that is causing the issue.
#GGW
Or this:
int t = 0;
//some code
for(t; t <= 5; t++)
//more code

Bubble Sort program does not output result

I am in a discrete mathematics class and one of the hw problems is to implement a bubble sort. Here's my futile attempt because it does not output the solution. Please advice. Thank you.
#include <iostream>
#include <cstdlib>
using namespace std;
void BubbleSort();
int array1[100] = {0};
int k;
int main()
{
cout << "Enter your numbers and when you are done, enter 0000:\n";
int x = 0;
int i;
while (i != 0000)
{
cin >> i;
array1[x] = i;
x++;
k = x;
}
BubbleSort();
system("pause");
return 0;
}
void BubbleSort(){
int temp;
for( int i = 0; i < k; i++ ){
if ( array1[i] > array1[i+1]){
temp = array1[i+1];
array1[i+1] = array1[i];
array1[i] = temp;
}
}
int x = 0;
while (x <= k)
{
cout << array1[x] << "\n";
x++;
}
}
Please only use basic programming techniques because this is my first programming class. Thank you.
Edit: fixed the relational operator. But now I get incorrect results.
while (x >! k)
This doesn't do what you think it does. If you want something that says "while x is not greater than k", you want <=. Since array1[k] isn't one of the elements you sorted, though, you probably want <.
while (x < k)
Note that for exists for loops like these:
for (int x = 0; x < k; x++) {
cout << array1[x] << "\n";
}
As for the new bug, you're only doing one round of bubbling in your bubble sort. You need another for loop. Also, i is never initialized in main, and i != 0000 isn't going to check whether the user literally entered 4 zeros. It'll only check whether the user's input was equal to the number 0.
The primary problem is here:
while (x >! k)
On the first iteration, the condition checks whether (0 > !k), and k is not 0, so !k is 0, so the condition is false and the loop never executes. Try using:
for (int x = 0; x < k; x++)
cout << array1[x] << "\n";
You also have a problem in the sort phase of your bubble sort; you only iterate through the data once, which is not enough to sort it, in general.
Finally, some design issues.
You should have one function to sort the data and a separate function to print it. Don't combine the two functions as you have done here.
Avoid global variables. Pass the array and its operational length to the sort function, and to the print function if you have one.

Why is my program not printing perfect integers?

I am new to C++ programming and have a problem with one of my programs
#include <iostream>
using namespace std;
bool IsPerfect(int n);
int main ()
{
for(int i=1; i<100; i++){
IsPerfect(i);
}
return 0;
}
bool IsPerfect(int n){
int sum;
for(int x=1; x<n; x++){
if(n%x==0){
sum+=x;
return true;
cout <<n;
}
else{
return false;
}
}
}
I am trying to create a program that will list perfect numbers but I can't find the bug as to why it would not print.
I see 3 issues:
Your algorithm is wrong. Your loop terminates on the first time a number is evenly divisible by any factor (including 1). See Wikipedia for an explanation of the algorithm.
You have an uninitialized variable with int sum; Also, you only ever write to it, you don't read it in a useful manner ever.
You have unreachable code. Your cout << n; in the loop will never be hit.
Try the following corrected code:
#include <iostream>
#include <cassert>
using namespace std;
bool IsPerfect(int n)
{
int sum = 1;
for(int x = 2; x < n; ++x)
{
if(n % x == 0)
sum += x;
}
return sum == n;
}
int main ()
{
for(int i=1; i<100; i++){
if (IsPerfect(i))
cout << i << endl;
}
assert(IsPerfect(6));
assert(IsPerfect(28));
assert(IsPerfect(496));
return 0;
}
You have a return statement before you output statement here:
return true;
cout <<n;
you need to swap the order of these statements, you also probably want to add a comma or some other separator:
std::cout << n << ", " ;
return true;
I am not sure that is where you want to return from since you will exit the first time you enter that if statement, which will happen when x is 1.
If you want to capture perfect numbers - numbers which are equal to the sum of their divisors, correct? - you need to allow the loop to proceed (and the sum to actually, well, sum) without returning. Take your print statement and your return statements and place them after the end of your loop; you should be checking then if the sum you have calculated is equal to n.
All these answers are telling you to write the number before returning. But that's ignoring the poor design here: you have a function that decides whether a number is perfect; it should not be that function that also decides what to do with this information (print it, store it, send it over the network, ...).
This will also make your code more readable, because the name IsPerfect is misleading - it tells the reader that this function just returns whether the number is perfect. Thus, the loop in the main function reads as, "for the integers 1 to 100, ask whether it is perfect and ignore the answer". This is not a useful program.
Remove the cout line from IsPerfect completely and put it in main instead:
for (int x = 1; x < 100; ++x) {
if (IsPerfect(x)) {
std::cout << x << '\n';
}
}
Try this
if(n%x==0){
sum+=x;
cout <<n;
return true;
}
The issue is in here:
if(n%x==0){
sum+=x;
return true;
cout <<n;
}
the keyword return immediately ends the function and returns the appropriate value (true). This means that all statements following it won't be executed. Try the following:
if(n%x==0){
sum+=x;
cout <<n;
return true;
}
In addition to the problems others have pointed out, you will never compute the right answer because you didn't initialize your sum variable.
Change
int sum;
to
int sum=0;