Error printing a pyramid pattern with asterisks in C [duplicate] - c

This question already has answers here:
What is a null statement in C?
(6 answers)
Closed 2 years ago.
The program asks the user for the pyramid hight i.e: rows number, and prints out a pyramid.
for input of 5, the result should look like this:
*
***
*****
*******
*********
the code I wrote is:
#include <stdio.h>
void main()
{
int i, j, n = 0;
printf("enter pyramid hight: \t");
scanf("%d", &n);
// FOR EACH ROW:
for (i = 0; i < n; i++)
{
// print spaces till middle:
for (j = 0; j < (n - 1 - i); j++)
{
printf(" ");
}
// print stars:
for (j = 0; j < 2 * n + 1; j++)
;
{
printf("*");
// go to new row
printf("\n");
}
}
}
but the result is:
*
*
*
*
*
what could be going wrong exactly, I think the second loop may be the problem but I can't put my hand on the reason.

You got a logic errors for the second for loop which does not do what you want:
// print stars:
for (j = 0; j < 2 * n + 1; j++) //<-- error #1 - n should be i as it's specific for this row
; //<-- error #2 - this termination is completely wrong, it means this `for` loop doing nothing
{
printf("*");
// go to new row
printf("\n");
}
which should be:
// print stars:
for (j = 0; j < 2 * i + 1; j++)
{
printf("*");
}
// go to new row
printf("\n");

Related

VSS C coding to print out a Christmas tree

This is my current code
void printer(int input)
{
int star;
int space;
for (int i = 1; i <= input; i++)
{
star = i;
space = i + input - star - 1;
for (int j = 0; j < space; j++)
{
printf(" ");
}
for (int s = 0; s < star; s++)
{
printf("*");
}
printf("\n");
}
}
I'm trying to print it out like
How tall 3?
*
* *
* * *
_| |_
\___/
and this is what i get. What is wrong with my code? and how will I fix the code?
How Tall? 3
*
**
***
Essentially, this snippet of code here that you use:
star = i;
space = i + input - star - 1; // or, space = input - 1 + i - star;
is the same as writing:
star = i;
space = input - 1;
This is because i and star have the same value (quoth star = i), and therefore, negate each other.
Now, can you see a constant here? Yes, the value of input is never changed anywhere, and therefore your code is always what 1 less than the input is. (In this case, its always preceded by 2 (=3-1) spaces) like this:
*
**
***
^^ mark two spaces
And you also forgot to add a trailing space after the asterix and hence there is no spacing between them.
Therefore, to solve your problem, you could store the value of input temporarily and reduce it by 1 in every iteration so it appears like a pyramid.
Example:
void printer(int input)
{
int star;
int space;
// Store the original length of the space
int space_length = input;
for (int i = 1; i <= input; i++)
{
star = i;
// Get the number of spaces for the current iteration
space = space_length - 1;
for (int j = 0; j < space; j++) {
printf(" ");
}
for (int s = 0; s < star; s++) {
printf("* ");
// ^ note this space after the asterisk
}
// Decrease the length of the space every step
// So that it appears like a slope
// Note how we are using 'space_length' instead of input
// This is because if we decrement 'input', this loop
// will get affected, which is not what we want
space_length--;
printf("\n");
}
///////// bottom part of the tree /////////
// number of spaces needed = input - length of "_| |_" - 1
for (int i = 1; i <= input - (4 - 1); i++)
printf(" ");
printf("_| |_\n");
// number of spaces needed = input - length of "\\___/" - 1
for (int i = 1; i <= input - (4 - 1); i++)
printf(" ");
printf("\\___/\n");
}
which gives the output:
*
* *
* * *
_| |_
\___/
your format is the issue. as you already know the size of the tree, you can deduct the size of the first set of whitespace (the first spaces on each lines), being spaces = (size - 1) - i. it should be, for each i:
i1 = 2
i2 = 1
i3 = 0
which seems to be what the result gives. additionally, between all asterix, just insert one space until the last character, and that's the idea
There are too many things gone wrong with this. I'll not post the correct code, but can guide you through it.
Since you want space after stars, print "* " instead of "*"
You have to use decremental space in beginning, before printing star, there's some logical fault in that, which is, you are adding and subtracting i and star, which are same thing. You need to give (input - star) spaces for the loop.
For the trunk, you have to develop some symmetrical logic.
I hope it helps you.
You can do it like this:
#include <stdio.h>
void printer(int input)
{
// for stars
for (int i = 1; i <= input; i++) {
for (int j = 1; j <= input - i; j++) {
printf(" ");
}
for (int k = 1; k <= i; k++) {
if (k == 1) printf("*");
else printf(" *");
}
printf("\n");
}
// for base
int base_half_len = input - 1;
for (int i = 1; i < base_half_len; i++) {
printf("_");
}
printf("| |");
for (int i = 1; i < base_half_len; i++) {
printf("_");
}
printf("\n\\");
for (int i = 1; i < 2 * input - 2; i++) {
printf("_");
}
printf("/\n");
}
int main(void) {
// your code goes here
printer(10);
return 0;
}
Here's the link where I tested it: https://ideone.com/7zpNeW

Need to do a half of a christmas tree with "*"

The output desired from the half of Christmas tree is:
*
**
***
****
*****
I could get a output like this:
*
**
***
****
*****
By using only cycles and conditions (arrays, can't be used), how can I get a solution like the first one?
main()
{
int n;
printf("Introduza o nĂºmero de ramos: ");
scanf_s("%d", &n);
for (int i = 1; i <= n; i++)
{
for (int j = 1 ; j <= i; j++)
{
putchar('*');
}
putchar('\n');
}
}
You obviously understand how to put a number of same characters next to each other.
The only thing left to do for you is to notice that the only difference between the first half-tree and the second is some spaces in front of the stars.
Also notice that the number of spaces is quite predictable, given the number of stars: the total width of spaces and stars is constant.
You just need to give a condition in inner loop. you should run the inner loop from 1 to n and print a " "(space) if j is less then i else print '*'
for (int i = 1; i <= n; i++)
{
for (int j = 1 ; j <= n; j++)
{
if(j < i)
putchar(' ');
else
putchar('*');
}
putchar('\n');
}

Is it possible to output the numpad's pattern using loops?

I just started learning C (coding in general) a few months ago. Earlier today when I was in class, I looked at the numpad and wondered whether I would be able to replicate the pattern using nested loops in C.
7 8 9
4 5 6
1 2 3 // This pattern.
I tried to do it myself for a bit, using for loops primarily. Thanks for any help.
#include<stdio.h>
int main()
{
int row, col, i;
printf("Up to what integer? ");
scanf("%d", &row);
for(i=1; i<=row; i++)
{
for(col=1; col<=10; col++)
{
printf(" %d ", i*col);
}
printf("\n");
}
}
Edit: Added supplementary code. Something like this, except to print 3 rows and 3 columns.
The numpad pattern has the equation 3*i + j with i going from 2 to 0 and j going from 1 to 3.
So use these values as upper and lower limits of i and j in nested for loops.
#include <stdio.h>
int main(){
for(int i = 2; i >= 0; i--){
for(int j = 1; j <= 3; j++)
printf("%d ", 3 * i + j);
printf("\n");
}
return 0;
}
See it live here.
Here's how you can do it:
for(int i = 0; i < 3; ++i){
for(int j = 3; j > 0; --j)
printf("%d ", (10 - j) - i * 3);
printf("\n");
}

Input to Multi-Array in C

I am trying to assign user input into an array; however, the program below only picks up on the first element in each line of input. The ultimate goal of this program is to find the diagonal sums of integers and return the absolute value of their difference.
Example input (note that the first number gives the number of rows and columns (square array):
Input:
3
11 2 4
4 5 6
10 8 -12
Output:
Expected = 15
Actual = 10
I realize that the issue lies in the way that the array is setup. If I print the array out I get: 111555999
Any hints/help would be very appreciated.
int main() {
int n, i, c, multi_array[200][200], sum1 = 0, sum2 = 0;
scanf("%i", &n); //N = number of rows and number of columns (square 2D array)
for (i = 0; i < n; i++) {
for (c = 0; c < n; c++) {
scanf("%d ", &multi_array[c][i]); //enter integers to store in array
}
}
for (i = 0; i != n; i++) {
sum1 += multi_array[i][i]; //add up top left to bottom right diagonal
}
for (i = 0; i != n; i++) {
sum2 += multi_array[i][n-i]; //add up top right to bottom left diagonal
}
printf("%i", abs(sum1 - sum2)); //print absolute value of the difference between diagonals
return 0;
}
Your major problem is here, where you go out of bounds:
for (i = 0; i != n; i++) {
sum2 += multi_array[i][n - i]; // when i is 0, th
}
When i = 0, you are accessing multi_array[0][3], which is out of bounds when N = 3.
So change it to this:
multi_array[i][n - i - 1]
You should read your array like this:
for (i = 0; i < n; i++) {
for (c = 0; c < n; c++) {
scanf(" %d ", &multi_array[i][c]);
}
}
since C stored its arrays in row-major order. What you have stores the array in column-major order. It's not wrong, but it's something you do only if you really have to.
Finally, change again the input part of your code to this:
scanf("%d", &n);
for (i = 0; i < n; i++) {
for (c = 0; c < n; c++) {
scanf("%d", &multi_array[i][c]);
}
}
so that you have to input exactly what you need to. With your initial code I have to type an extra random number when I had completed the input process.
Last but not least, I am posting the whole code, where I have wrote some extra printf()'s, which are actually for the programmer, so that he can see step-by-step if his code is acting as expected or not.
#include <stdio.h>
#include <stdlib.h> /* abs */
int main() {
int n, i, c, multi_array[200][200], sum1 = 0, sum2 = 0;
scanf("%d", &n);
for (i = 0; i < n; i++) {
for (c = 0; c < n; c++) {
scanf("%d", &multi_array[i][c]);
}
}
for (i = 0; i < n; i++) {
for (c = 0; c < n; c++) {
printf("|%d|", multi_array[i][c]);
}
printf("\n");
}
for (i = 0; i != n; i++) {
sum1 += multi_array[i][i];
}
printf("sum1 is %d\n", sum1);
for (i = 0; i != n; i++) {
sum2 += multi_array[i][n - i - 1];
}
printf("sum2 is %d\n", sum2);
printf("%i", abs(sum1 - sum2));
return 0;
}
Output:
3
11 2 4
4 5 6
10 8 -12
|11||2||4|
|4||5||6|
|10||8||-12|
sum1 is 4
sum2 is 19
15
You are clearly going out of bounds here:
for (i = 0; i != n; i++) {
sum2 += multi_array[i][n-i]; //add up top right to bottom left diagonal
}
When i is equal to 0 the expression n-i will be equal to n, but the range of the array is from 0 to n-1. The code will read uninitialized values and cause undefined behavior.
The second array index should be 1 less.

How do I print out this 2D array?

Novice programmer here trying to print out a 2D array of asterisks. The output I'm trying to achieve is:
*******
*******
*******
*******
That's 7 asterisks with a leading space increment by 1 every row with row 1 starting with 0 leading spaces and row 4 starting with 3 leading spaces.
Only the <stdio.h> library can be used and I'd like to keep using nested for loops. Here's my attempt:
#include <stdio.h>
int main(void)
{
int i, j;
char star[1] = {'*'};
for(i = 0; i < 4; i++)
{
for(j = 0; j < 8; j++)
{
printf("%*c", i, star[0]);
}
printf("\n");
}
return 0;
}
Here's what I'm getting:
********
********
* * * * * * * *
* * * * * * * *
I'd also like for this question to be an opportunity for me to learn good general programming practices and habits from this community so if you could critique my implementation, I'd greatly appreciate it.
Firstly, this does not really have anything to do with multidemensional arrays. Secondly you are using the width format specifier in your printf call
printf("%*c", i, star[0]);
and setting that width to be i. Therefore each time you call
printf("%*c", i, star[0]);
you are specifying the minimum width of the printed output to be i characters. As your output is a single * character this results in whitespace padding.
Thus in your final iteration of your i based loop (i = 3) you are causing the string
' *'
to be printed each time, penultimate iteration (i = 2)
' *'
and so on.
As you don't really need a char array of length 1, you could get your desired output with
for(i = 0; i < 4; i++)
{
if (i > 0)
{
printf("%*c",i,' ');
}
for(j = 0; j < 8; j++)
{
printf("%c", '*');
}
printf("\n");
}
The program you wrote prints space before every star, and that's space length is tied to the 'i' variable'.
You should make it print (spaces * i) before the loop that prints line of 8 stars even starts.
Here is how i would write it.
#include
int main() {
for(int i = 0; i < 4; i++ ) {
for( int p = 0; p < i; p++ ) {
printf(" ");
}
for( int j = 0; j < 8; j++ ) {
printf("*");
}
printf("\n");
}
return 0;
}
Here it is in Python, if you're interested:
for x in range(4):
print ((x * " ") + ("*" * 7))
Apply this same idea of padding the beginning with spaces based on the iteration, and then adding the asterisks

Resources