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
Related
I need to print centered string inside a frame of square stars pattern.
EXAMPLE:
const char tekst[]="This is example of string programming in C";
int width = 20;
OUTPUT:
********************
* This is example *
* of string progr- *
* amming in C *
********************
If number of spaces that need to be added is odd, excess space should be added to the right.
If the whole word cannot fit in the row, dash is added and word continues in the next row.
Auxiliary strings are not allowed.
Code:
#include <stdio.h>
#include <string.h>
void framed(const char *tekst, int width) {
int i, j = 0, count = 0;
for (i = 0; i < width; i++)
printf("*");
printf("\n");
while (tekst[j] != '\0') {
count++;
if (count == 1)
printf("* ");
printf("%c", tekst[j]);
j++;
if (count + 5 > width) {
printf(" *");
printf("\n");
count = 0;
}
if (j == strlen(tekst))
for (i = 0; i < width - count; i++)
printf(" ");
}
printf("*\n");
for (i = 0; i < width; i++)
printf("*");
}
int main() {
const char tekst[] = "This is example of string programming in C";
int width = 20;
framed(tekst, width);
return 0;
}
This is my output:
********************
* This is example *
* of string progra *
* mming in C *
********************
Could you help me to fix my code for correct output?
Here you take the additional character "* "" *" into account (with a little off-by-one because of >):
if (count + 5 > width)
Here you don't:
for (i = 0; i < width - count; i++)
If you do take them into account, it (the frame) works.
for (i = 0; i <= width - (count +5); i++)
assuming that you also output consistently a little later
printf(" *\n");
I recommend to replace the very magic number 5 with the less magic number of additional characters; 4 for "* *" and to adapt the conditions <= and >.
The other differences to required output (centering instead of left aligning and inserting the "-" correctly have not even been attempted by the shown code, so I assume that they are not part of what is asked about.
I thought long and hard before asking this in here but I've spent too much time now trying to figure this one out without cheating.
The CS50 mario ps1 (less comfortable) asks for a *simple left align (at first) pyramid, but my code is giving me it upside down and I can't figure why.
#include <cs50.h>
#include <stdio.h>
int main (void)
{
int n;
do
{
n = get_int("Pyramid Height: ");
}
while (n < 1 || n > 8);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n - i ; j++)
printf("#");
for (int j = 0; j < n - i; j++)
{
printf(" ");
}
printf("\n");
}
}
I'm sorry if this type of questioning shows up regularly here but I really do need your help.
Thanks in advance.
edit:
expected result:
........#
.......##
......###
.....####
....#####
...######
..#######
.########
I can change the dots to spaces afterwards, this is just for visualisation;
the restriction for height is 8, so I guess that each line has always eight characters;
I actually added trailing spaces so that the pyramid could be right aligned, I've metioned wrong before;
I'm going to check the How to debug small programs?;
Sorry, I'm new to this, I didn't know there was a difference between here and stack exchange, gonna look into that.
*Sorry for the "meh" english, it is not my native language.
See what is the difference between my and your code (especially how to count):
void draw(int n, int align, int dir)
{
for (int i = 1; i <= n; i++)
{
if(align)
{
for(int s = 0; s < (dir ? (n - i) : i - 1); s++)
{
printf(" ");
}
}
for (int j = 0; j < (dir ? i : (n - i + 1)) ; j++)
{
printf("#");
}
printf("\n");
}
}
int main (void)
{
draw(8,1,0);
printf("\n");
draw(8,1,1);
printf("\n");
draw(8,0,0);
printf("\n");
draw(8,0,1);
}
https://godbolt.org/z/7YT16j
my code is giving me it upside down and I can't figure why
Let's see what the code looks like
// There's a loop executed n times. The body prints a line, so n lines are printed.
// In case you have doubts, the characters are normally printed top to bottom and
// left to right.
for (int i = 0; i < n; i++)
{
// The following loop prints (n - i) characters '#' at the beginning
// of each line. That's NOT what you are supposed to do, kind the opposite.
for (int j = 0; j < n - i ; j++)
printf("#");
// You should first print the spaces, then the '#'s, starting from 1 '#' at
// the first line and increasing the number by one at each line (so you have
// to change the condition in the loop accordingly).
// This loop prints the right amount of spaces, but only after
// all the '#'s and just before the end of the line, so that you just
// can't see them (change the printed char to '.' to visualize those).
for (int j = 0; j < n - i; j++)
{
printf(" ");
}
// Note that you could use putchar('\n'), here and previously, to print
// only one char, instead of using printf() to print string literals.
printf("\n");
}
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
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');
}
Code1:
#include<stdio.h>
int main()
{
unsigned short i, j, k;
for (i = 0; i < 2; i++)
{
k = i * 4 + 4;
for (j = k - 4; j < k; j++)
printf("%hu ", j);
putchar('\n');
}
return 0;
}
Output of Code1:
0 1 2 3
4 5 6 7
Remarks of Code1:
Space after 3 and 7
Newline after 7 (Stackoverflow has removed it)
Code2:
#include<stdio.h>
int main()
{
unsigned short i, j, k;
for (i = 0; i < 2; i++)
{
k = i * 4 + 4;
for (j = k - 4; j < k; j++)
{
printf("%hu", j);
if (j + 1 != k) putchar(' ');
}
if (i + 1 != 2) putchar('\n');
}
return 0;
}
Output of Code2:
0 1 2 3
4 5 6 7
Remarks of Code2:
No space after 3 and 7
No newline after 7
Additional remark of Code2:
The problem of Code2 is that the algorithm always compares two values in the if blocks and so Code2 is not efficient. I want to use Code1 and change these:
Code3
#include<stdio.h>
int main()
{
unsigned short i, j, k;
for (i = 0; i < 2; i++)
{
k = i * 4 + 4;
for (j = k - 4; j < k; j++)
printf("%hu ", j);
printf("\b\n");
}
putchar('\b');
return 0;
}
These do not show the same output of Code2 because \b does not erase anything.
My question:
Is there any standard way to do so what I've tried in Code3?
Remark of my question:
I have searched the internet but have not determined the solution.
Edit the question if it is not clear.
Edit: I don't know why my question is not useful or constructive. Though the above is an arbitrary small example, but performance might be an issue when processing very large amount of data. I thought that the way of removing character from console output might improve performance and there might be a specific way to do so. That's why I've asked the question. I could write the following codes in the answers. Now I've known via comments that removing character from console output is not possible because it is implementation dependent.
The usual approach to this is to treat either the first or the last printf as a special case (outside of the loop):
for(ii=0; ii<2; ii++) {
jj = 0;
printf("%d", jj); // first number printed without space.
for(jj=1; jj<4; jj++) {
printf(" %d", jj); // include the space before the number printed
}
if(ii<2-1) printf("\n");
}
Obviously I simplified how the loops are constructed and what is printed - for simplicity. You could make the first printf statement
printf("\n%d", jj);
then you have a newline at the start of your output (often a good thing) and then you don't need the if statement later - you just don't have a newline printed at the end of the line (because it will be printed at the start...)
There are marginally more efficient ways of doing this that would involve no if statements at all - but these all come at the expense of less readable code. For example, here is a "no loop unrolling and no additional if statements" version of the code:
http://codepad.org/01qPPtee
#include <stdio.h>
int main(void) {
int ii, jj;
ii = 0;
while(1) {
jj = 0;
while(1) {
printf("%d", jj); // include the space before the number printed
jj++;
if(jj<4) printf("."); else break;
}
ii++;
if(ii<2) printf("*\n"); else break;
}
return 0;
}
Output:
0.1.2.3*
0.1.2.3
Basically I have taken the functionality of the for loop and made it explicit; I also use a . rather than a and "*\n" rather than "\n" to show in the printout that things behave as expected.
It does what you asked without extra evaluation of the condition. Is it more readable? Not really...
If it really bothers you, you can unroll your loops a little so that you treat the last item as a special case:
#include<stdio.h>
int main()
{
unsigned short i, j, k;
for (i = 0; i < 1; i++)
{
k = i * 4 + 4;
for (j = k - 4; j < k - 1; j++)
{
printf("%hu ", j);
}
printf("%hu\n", j);
}
k = i * 4 + 4;
for (j = k - 4; j < k - 1; j++)
{
printf("%hu ", j);
}
printf("%hu", j);
return 0;
}
#include <stdio.h>
int main(){
unsigned short num = 0, to=8;
while(num < to){
printf("%hu", num++);
if(num < to)
putchar(num % 4 == 0 ? '\n' : ' ');
}
#if 0
do{
printf("%hu", num++);
}while(num < to && putchar(num % 4 == 0 ? '\n' : ' '));
#endif
return 0 ;
}
Well, to try to answer your question, here's how I would do it:
for (i = k = 0; i < 2; i++){
if (i > 0) printf("\n");
for (j = 0; j < 4; j++, k++){
if (j > 0) printf(" ");
printf("%d", k);
}
}
I do it this way because I want to be sure every line but the first starts with a \n, and every item is separated by a space from the one before it.
Also, I do not want the row and column position to be intimately tied to the content of what is being printed.
In terms of performance, keep in mind that these if statements cost about 1 cycle, while each character printed costs at least hundreds if not thousands. printf goes through many layers of system calls to interpret its format string, build a buffer, send the buffer to the system I/O routines, which then cause repainting and scrolling of the console window. Get the idea?
DO NOT WORRY about performance unless you know you have a problem.
Then, don't guess. Use a diagnostic. Here's what I do.