Reputation: 9
How do I add a newline between two triangles and without a newline at the end of the triangle?
Sample Input
4↵
5↵
Sample Output
*******↵
*****↵
***↵
*↵
↵
*↵
***↵
*****↵
*******↵
*********↵
#include <stdio.h>
#include <stdlib.h>
void printDownT(int n){
for (int i = n; i >= 1; i--) {
for (int j = 1; j <= n - i; j++) {
printf(" ");
}
for (int k = 1; k <= 2 * i - 1; k++) {
printf("*");
}
printf("\n");
}
}
void printUpT(int n){
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n - i; j++) {
printf(" ");
}
for (int k = 1; k <= 2 * i - 1; k++) {
printf("*");
}
printf("\n");
}
}
int main(){
int num;
while (scanf("%d", &num) != EOF){
if (num % 2 == 0){
printDownT(num);
printf("\n");
}
else{
printUpT(num);
printf("\n");
}
}
return 0;
}
Upvotes: 0
Views: 63
Reputation: 1394
Please see this code and note its creation and usage of character array nlsym
(new line symbol). Whenever you do want the new line symbol, include the printing of the nlsym
array, and when you don't want it, you can omit the printing of the array as shown below.
Works nicely -- check the runnable code with output here.
#include <stdio.h>
int main()
{
char nlsym[]= {0xE2, 0x86, 0xB5, 0x0};
printf(" %s\n", nlsym);
printf(" *%s\n", nlsym);
printf(" ***%s\n", nlsym);
printf(" *****%s\n", nlsym);
printf(" *******%s\n", nlsym);
printf(" *********%s\n", nlsym);
printf("***********\n");
return 0;
}
Output:
↵
*↵
***↵
*****↵
*******↵
*********↵
***********
This second example borrows upon your code to illustrate exactly how to integrate the nlsym
array:
Runnable code here.
#include <stdio.h>
void printUpT(int n)
{
char nlsym[]= {0xE2, 0x86, 0xB5, 0x0};
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n - i; j++)
{
printf(" ");
}
for (int k = 1; k <= 2 * i - 1; k++)
{
printf("*");
}
if(i<n)
printf("%s\n",nlsym);
else
printf("\n");
}
}
int main()
{
printUpT(7);
return 0;
}
Output:
*↵
***↵
*****↵
*******↵
*********↵
***********↵
*************
Upvotes: 0