Output that looks like a triangle in C - c

I wrote this program,
include <stdio.h>
int main(){
int size = 5;
int row;
int col;
for (col=0; col<size; col++){
for (row=0; row<col;row++){
printf(" ");
}
for (row=0; row <(size-col) ; row++){
printf("*");
if(col<=size){
printf("*");
}
}
printf("\n");
}
return 0;
}
It should make a triangle like
*********
*******
*****
***
*
But instead there is one extra * on every line. What is the problem?
Thanks a lot!

Mystical has a solution to the way you're printing two asterisks an iteration. Using the identifiers row and col in your example also makes things more confusing than just i and j, especially since the outer loop is actually your current row.
An alternative to your mess is (I'm hoping this isn't homework since it's not tagged as such):
int main(void)
{
int size = 5;
int i, j;
for (i = size; i > 0; i--) {
for (j = i; j < size; j++)
putchar(' ');
for (j = 0; j < i*2 - 1; j++)
putchar('*');
putchar('\n');
}
return 0;
}
You could also put i*2 - 1 in a variable so that it's not calculated at each iteration of the loop (unless the compiler sees that you're not modifying i).

Changing
if(col<=size){
to
if((row % size) > 0){
will have the same effect too.

How about printing the *'s like this
for (row=0; row<(9-2*col); row++)
printf("*");
printf("\n");
This will print nine of the first row, seven on the second, etc.

Factor your problem into relevant variables and give them meaningful names. This will improve code readability and make bugs easier to fix, e.g.:
#include <stdio.h>
void triangle(int height)
{
int row, col;
int width = (2 * height) - 1;
for (row = 0 ; row < height ; row++)
{
for (col = 0 ; col < width ; col++)
{
if (row > col)
{
putchar(' ');
}
else if (col < width - row)
{
putchar('*');
}
}
puts("\r");
}
}
int main(void)
{
triangle(5);
return 0;
}

No one brought up recursion? It's not quite pure because you have to track depth. I called it a pyramid (pyr_) instead of a triangle:
#include <stdio.h>
#include <stdlib.h>
static void pyr_line(int depth, int nrows) {
int i;
if (nrows == 0) return;
for (i=0; i<depth; i++)
printf(" ");
for(i=0; i<(2*(nrows-1)+1); i++)
printf("*");
printf("\n");
pyr_line(depth+1, nrows-1);
}
int main(int argc, char ** argv)
{
pyr_line(0, atoi(argv[1]));
return 0;
}

Related

How do I put a 2d array of chars into a 2d grid array cells

I'm trying to make a 2048 game right now but I'm having trouble putting my 2d character array into the 2d grid array cells that I made. I'm a beginner programmer learning the basics of C. Here is the code I have so far with the output at the bottom.
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#define POSX 4
#define POSY 4
/* Makes a grid array */
void grid(){
int r, c, row, col;
row = col = 4;
for(r = 0; r < row; r++){
for(c = 0; c < col; c++){
printf("+---");
}
printf("+\n");
for(c = 0; c < col; c++){
printf("| ");
}
printf("|\n");
}
for(c = 0; c < col; c++){
printf("+---");
}
printf("+\n");
}
/* Main function */
int main(){
char array[POSX][POSY]; //character array
int x,y;
for(x = 0; x < POSX; x++){
for(y = 0; y < POSY; y++){
array[x][y] = 'A';
}
}
for(x = 0; x < POSX; x++){
for(y = 0; y < POSY; y++){
printf(" %c ", array[x][y]);
}
printf("\n");
}
grid(); //Printing out grid array
return 0;
}
Output:
I want the As to be within the grid cells
So I want it to look something like for each cell:
+---+
| A |
+---+
Any help is appreciated, thank you!
You need to merge loops into one set (printing grid and table content at the same time)
Do not use global variables only use function parameters to pass data to the function. The example below will print any size char array in the grid.
void printDiv(size_t cols)
{
for(size_t col = 0; col < cols; col++)
{
printf("+---");
}
printf("+\n");
}
void printInGrid(size_t rows, size_t cols, char (*array)[cols])
{
if(rows && cols && array)
{
for(size_t row = 0; row < rows; row++)
{
printDiv(cols);
for(size_t col = 0; col < cols; col++)
{
printf("| %c ", array[row][col]);
}
printf("|\n");
}
printDiv(cols);
}
}
int main(void)
{
char array[5][15];
memset(array, 'A', sizeof(array));
printInGrid(5, 15, array);
}
https://godbolt.org/z/3PWjsvz8e

CS50 coding exercise Mario less comfortable

I am new to any programming and new to computer science in general. This exercise was a real headache for me and I spent maybe two days reading stuff and trying to find how to write a solution for it.
I used a lot of information I found everywhere to make my "own" code. It's not mine really.
Now with all this job that I've done I still don't get why do I get one extra space printed at the beginning of every row. When there is let's say 5 rows and the height is 5 there is one extra space at the beginning. Could anyone explain to me what am I doing wrong, please? Thank you
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int height;
do
{
height = get_int("Height: ");
}
while (height < 1 || height > 9);
for (int row = 1; row <= height; row++)
{
{
printf(" ");
}
for (int k = 1; k <= height - row; k++)
{
printf(" ");
}
for (int j = 1; j <= row; j++)
{
printf("#");
}
printf("\n");
}
return 0;
}
Let's trace you for loop
for (int row = 1; row <= height; row++)
{
// print space at first of row
{
printf(" ");
}
// print space as how many rows left
for (int k = 1; k <= height - row; k++)
{
printf(" ");
}
// print # for each row
for (int j = 1; j <= row; j++)
{
printf("#");
}
// new line
printf("\n");
}
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int height=10;
for (int i= 1; i <= height; i++)
{
for(int j=height-1;j>=i;j--)
{
printf(" ");//print a space : ' '
}
for(int k=1;k<=i;k++)
{
printf("#");//print this caracter :'#'
}
printf("\n");
}
return 0;
}
You have 3 for loops.
Inside the outermost loop, there are two for loops. Your code first prints a space, and then runs the two inner for loops.
The second for loop also prints a space.
The third for loop prints a number of # characters depending on the height of the tower.
If you're asking why there's an extra space, it's that first statement in the for loop.
I'm no C expert but i believe the braces are unnecessary. Remove that and your code should not have extra spaces.
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int height;
do
{
height = get_int("Height: ");
}
while (height < 1 || height > 9);
for (int row = 1; row <= height; row++)
{
for (int k = 1; k <= height - row; k++)
{
printf(" ");
}
for (int j = 1; j <= row; j++)
{
printf("#");
}
printf("\n");
}
return 0;
}

Simple I/O Function w/ C

I've just recently started trying to learn C through the tutorials on Wikibooks. I've read the beginning C pages listed here and am attempting to do the exercises. I'm having a problem with the second question on loops: wherein I'm trying to make a function to output a triangle made up of lines of * characters, where the height is 2n-1 if the width is n. My first thought was to make a nested loop, the outer of which would create a variable for the line number, and compare it to the max height. The inner loop would create a variable that would essentially serve as the index of the * character within that particular line. My problem is I don't know how to deal with making the lines after the max width decrease in size. Can anyone point me in the right direction? Here is my code:
#include <stdio.h>
void triangle(int);
int main() {
int width;
printf("%s", "Please enter a width for your triangle: ");
scanf("%d", & width);
triangle(width);
return 0;
}
void triangle(int width) {
for (int line = 1; line <= (2 * width) - 1; line++) {
for (int i = 0; i < line && i < width; i++) {
printf("%s", "*");
}
printf("%s", "\n");
}
}
Try this:
void triangle(int width) {
int line, i, rev = 0;
for (line = 1; line < width; ++line) {
for (i = 0; i < line && i < width; i++) {
printf("*");
}
printf("\n");
}
for (; line; --line) {
for (i = 0; i < line && i < width; i++) {
printf("*");
}
printf("\n");
}
}
if you want to do it in one pair of nested for loops try this:
void triangle(int width) {
int i, j, height, tmp;
height = 2 * width - 1;
tmp = 1;
for (i = 0; i < height; i++) {
for (j = 0; j < tmp; j++) {
putchar('*');
}
putchar('\n');
if (i < height / 2) {
tmp++;
} else {
tmp--;
}
}
}

I want to print out the following to the console

I want to print out the following to the console:
+++++
++++*
+++**
++***
+****
*****
I am a new learner of programming, so encountering some difficulties. Can anyone help me, please? I have tried this, but is incorrect. What do I need to change?
#include<stdio.h>
int main(){
int i, j, k;
for(i=0; i<5; i++){
for(j=i; j<5; j++){
for(k=0; k<j; k++){
printf("*");
}
printf("+");
}
printf("\n");
}
return 0;
}
You have the right idea: Use three for loops.
#include <stdio.h>
int main() {
for (int i = 0; i < 6; i++) {
for (int k = i; k < 5; k++) {
printf("+");
}
for (int j = 0; j < i; j++) {
printf("*");
}
printf("\n");
}
return 0;
}
Test
+++++
++++*
+++**
++***
+****
*****
Online demo
First, generalise it and wrap it in a function. You want a square with a diagonal. It has to be an even number of characters to look right. But + and * could be any character, and the size could be 6 or all the way up to screen maximum width.
so
/* print a square with a diagonal
N - the size of the sides of the square
cha - character a (eg '+')
chb - character b (eg '*')
*/
void printdiagsquare(int N, char cha, char chb);
That's our prototype, and that's half the battle.
Now we need to check N is even and positive, then write the loops.
Let's get the test away first.
if(N < 2 || (N % 2) == 1)
printf(N must be even\n");
Now the main loop for each line
for(i=0;i<N;i++)
{
//printline code here
printf("\n");
}
Now test it. Is it printing N blank lines?
main(void)
{
printdiagsquare(6, '+', '*');
}
Now to get the lines printed.
to print N-1 '+'s is easy. We need j as the counter since i is the outer
for(j=0;j<N-1;j++)
printf("%c", cha);
But we need to generalise, we need to print 6,, 5, 4, 3 and so on as i increases.
So
for(j=0;j<N-i-1;j++)
printf("%c", cha);
I'll leave the last little bit for you to do. No point just typing ina function blindly.
You could try more optimized code for m-rows and n-columns
in 2 for loop only :-
#include <stdio.h>
int main(void) {
int m = 6; // Rows
int n = 5; // Cols
int i,j,k;
for (i = 0; i < m; i++) {
k = i;
for (j = n; j >= 0; j--) {
if(k>=j)
printf("*");
else
printf("+");
}
printf("\n");
}
return 0;
}

Writing values in a 2 dimensional array in c

Being new to C, and this website, I'm unfamiliar with this problem I'm having. I have a 2 dimensional array with [8][8] elements. I'm trying to get the user to enter numbers into the array until finished. The program is far from finished, but I'm stuck on this problem before I can move on. Basically I use a for loop to let the user enter into each element. However, when the first row is complete, it overwrites it's last value onto the first column second row element spot. How can I prevent this from happening: Here's my code:
#include <stdio.h>
#include <string.h>
int Check_rules();
void Print_Array(int array[][8], int size)
{
int i, j;
for (i = 0; i <= size; i++)
{
printf("\n");
for (j = 0; j <= size; j++)
{
printf("%d ",array[i][j]);
}
}
printf("\n\n");
}
int main()
{
int size = 8;
int i, j;
int fullArray[size][size];
int grid1[3][3];
int grid2[3][3];
int grid3[3][3];
int grid4[3][3];
int grid5[3][3];
int grid6[3][3];
int grid7[3][3];
int grid8[3][3];
int grid9[3][3];
for (i = 0; i <= size; i++)
{
for (j = 0; j <= size; j++)
fullArray[i][j] = 0;
}
printf("Want to play a game? Enter values 1-9 starting in row 1 column 1, \nand we will work our way from there. Here's the playing board.\nIt's Sudoku, so follow the rules of the game.\n\n");
for (i = 0; i <= size; i++)
{
printf("\n");
for (j = 0; j <= size; j++)
printf("%d ",fullArray[i][j]);
}
printf("\n\n");
int tmp;
char *keeper = (" ");//space for marker
for (i = 0; i <= size; i++)
{
for (j = 0; j <= size; j++)
{
printf("Enter first value(press 0 and ENTER to skip a box, \nand -1 to cancel game): ");
scanf("%d", &tmp);
if(tmp == -1)
return 0;
fullArray[i][j] = tmp;
Print_Array(fullArray,size);
}
}
return 0;
}
If you run this you'll see my problem when you enter the last value in row 1. It overwrites the second row first column element spot?
Everywhere you have <= size, you actually want < size. This is because C uses 0-based indexes. That means if you have an array with 5 elements, the indexes are 0, 1, 2, 3, 4. In a loop like for (int i = 0; i <= 5; i++), i would get the values 0, 1, 2, 3, 4, 5. That last one is an invalid index into the array. Using i < 5 fixes the problem (ensures i stops before it reaches 5).
Fixed and cleaned up version of your code:
#include <stdio.h>
#include <string.h>
void printArray(int size, int array[][size]) {
for (int i = 0; i < size; i++) {
printf("\n");
for (int j = 0; j < size; j++) {
printf("%d ", array[i][j]);
}
}
printf("\n\n");
}
int main() {
int size = 8;
int fullArray[size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
fullArray[i][j] = 0;
}
}
printf("Enter values in row 1 column 1, and we will work our way from there. Here's the playing board. \n\n");
printArray(size, fullArray);
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
printf("Enter first value (press 0 and ENTER to skip a box, or -1 to cancel game): ");
int number;
scanf("%d", &number);
if(number == -1) {
return 0;
}
fullArray[i][j] = number;
printArray(size, fullArray);
}
}
return 0;
}
EDIT
To clarify, this is fixed version of the original code in the question. The new code is a bit different, but I think the issue is the same.

Resources