Printing alphabet pyramid in C - c

I'm trying to write a program in C that gives a 13 row pyramid with the following output (notice the pattern of the letters i.e BCB):
A
BCB
DEFED
GHIJIHG
KLMNONMLK
PQRSTUTSRQP
VWXYZABAZYXWV
CDEFGHIJIHGFEDC
KLMNOPQRSRQPONMLK
TUVWXYZABCBAZYXWVUT
DEFGHIJKLMNMLKJIHGFED
OPQRSTUVWXYZYXWVUTSRQPO
ABCDEFGHIJKLMLKJIHGFEDCBA
Here is my attempt at the solution:
#include <stdio.h>
#include <stdlib.h>
int main(void){
char c = 'A';
int height = 13;
int max = 1;
for (int i = 1; i <= height; i++){
//int j = 1;
for (int k = 0; k < height - i; k++)
printf(" "); // print space on left
for (int j = 1; j <= max; j++){
if (j <= max / 2){ // print left side of pyramid
printf ("%c", c);
c = (c - 'A' + 1) % 26 + 'A';
}
else{ // print right side of pyramid
printf ("%c", c);
c = (c -'A' + 25) % 26 + 'A';
}
}
printf("\n");
max += 2;
}
}
However it gives the following incorrect output:
A
ZAZ
YZAZY
XYZAZYX
WXYZAZYXW
VWXYZAZYXWV
UVWXYZAZYXWVU
TUVWXYZAZYXWVUT
STUVWXYZAZYXWVUTS
RSTUVWXYZAZYXWVUTSR
QRSTUVWXYZAZYXWVUTSRQ
PQRSTUVWXYZAZYXWVUTSRQP
OPQRSTUVWXYZAZYXWVUTSRQPO
if I remove the the if/else statement which splits the pyramid in to two sides and simply have only c = (c - 'A' + 1) % 26 + 'A';, I get the following output:
A
BCD
EFGHI
JKLMNOP
QRSTUVWXY
ZABCDEFGHIJ
KLMNOPQRSTUVW
XYZABCDEFGHIJKL
MNOPQRSTUVWXYZABC
DEFGHIJKLMNOPQRSTUV
WXYZABCDEFGHIJKLMNOPQ
RSTUVWXYZABCDEFGHIJKLMN
OPQRSTUVWXYZABCDEFGHIJKLM
Any ideas?

The problem is that you're forgetting to increment the actual overall character. For each line, you need to add characters until you get to the value that you should start at for the next line. Thankfully, this is pretty easy to do:
...
max += 2;
c = (c - 'A' + max / 2 + 1) % 26 + 'A'; // Add this line
}

Here's a short version:
#include <stdio.h>
#define HEIGHT 6
int main(void) {
char* f = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char* b = "ZYXWVUTSRQPONMLKJIHGFEDCBA";
int c = 0;
for(int i=0; i<HEIGHT; ++i)
{
printf("%*.*s%.*s\n", 10, i+1, f+i+c, i, b+strlen(b)-(c+2*i));
c+=i;
}
return 0;
}
IDEOne Link
Output:
Success #stdin #stdout 0s 9424KB
A
BCB
DEFED
GHIJIHG
KLMNONMLK
PQRSTUTSRQP

Related

How to make competitive coding solutions more efficient (BIT wise operations)?

How do I make my code more efficient (in time) pertaining to a competitive coding question (source: codechef starters 73 div 4):
(Problem) Chef has an array A of length N. Chef wants to append a non-negative integer X to the array A such that the bitwise OR of the entire array becomes = Y .
Determine the minimum possible value of X. If no possible value of X exists, output -1.
Input Format
The first line contains a single integer T — the number of test cases. Then the test cases follow.
The first line of each test case contains two integers N and Y — the size of the array A and final bitwise OR of the array A.
The second line of each test case contains N space-separated integers A_1, A_2, ..., A_N denoting the array A.
Please don't judge me for my choice of language .
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int* binary_number(int n) // returns pointer to a array of length 20(based on given constrains) representing binary
{
int* ptc;
ptc = (int*) malloc(20*sizeof(int));
for(int i = 0; i < 20; i++)
{
if((n / (int) pow(2,19-i)) > 0){*(ptc + i) = 1;}
else {*(ptc + i) = 0;}
n = n % (int) pow(2,19-i) ;
}
return ptc;
}
int or_value(int* ptc, int n) // Takes in pointers containing 1 or zero and gives the logical OR
{
for(int k = 0; k < n; n++)
{
if(*ptc == *(ptc + 20*k)){continue;} // pointers are 20 units apart
else{return 1;break;}
}
return *ptc;
}
int main(void) {
int t; scanf("%d", &t);
for (int i = 0; i < t; i++)
{
int n, y;
scanf("%d %d", &n, &y);
int a[n];
for(int j = 0; j < n ; j++)
{
scanf("%d", &a[j]);
}
int b[20*n];
for (int j = 0; j < n; j++)
{
for (int k = 0; k < 20; k++)
{
b[20*j + k] = *(binary_number(a[n])+k);
}
}
int c = 0;
int p = 0;
for (int j = 0; j < 20; j++)
{
if ((*(binary_number(y) + j) == 1) && (or_value((&b[0] + j),n) == 0)){c = c + pow(2,19 - j);}
else if ((*(binary_number(y) + j) == 0) && (or_value((&b[0] + j),n) == 1)){p = 1; break;}
}
if (p==1){printf("-1");}
else {printf("%d\n", c);}
}
return 0;
}

Converting couple of integers into one integer in C

In doing an assignment, in which:
Program prints out the sum in the form of the following text
1 + 22 + 333 + 4444 + . . . + nn. . . n }n
and its result. The number n ∈ {1, 2, . . . , 9} is provided by the user
I'm stuck at the point where I don't know how to glue the numbers into one integer, so how to convert "333" into 333, etc.
Here's my code:
#include <stdio.h>
#include <string.h>
int main()
{
printf("Program calculates a sum.\nAutor: Jakub Drozd\n");
int n;
int sum = 0;
printf("Enter the length of the sum (no more than 9): ");
while (scanf_s("%d", &n)!=1 || n < 1 || getchar()!='\n')
{
printf("Wrong input, enter the length of the sum: ");
int c;
while ((c = getchar()) != '\n' && c != EOF)
;
}
for (int i = 1; i <= n; i++)
{
if (i == 1);
else { printf(" + "); }
for (int j = 1; j <= i; j++)
{
printf("%d", i);
}
}
printf("\nEnd of the program\n");
return 0;
}
As you can see, The program correctly displays the numbers to be added, but I don't know how to cast them into integers to sum them up.
Instead of printing out the individual digits, add them together to form the actual value, and then add them to a sum that you present.
The creation of the numbers could be like
int number = 0;
for (int j = 1; j <= i; ++j)
{
number = number * 10 + i;
}
Then adding the numbers is as simple as creating a variable to hole the sum, and adding to it:
int sum = 0;
// ...
sum += number;

I want to print c pattern as upper triangle

I want to print some C pattern for upper triagnle which sholud print numeric value 1 to 10.
Now my code is like this:-
#include <stdio.h>
int main() {
int j = 1, k, l, i;
for (i = 4; i >= 1; i--) {
for (k = i - 1; k >= 0; k--) {
printf(" ");
}
for (l = 4; l >= i; l--) {
printf("%2d", j);
j++;
}
printf("\n");
}
return 0;
}
Its output is fine but when my value reach near 10 it's space is missing.
How can I resolve it?
My output looks like
1
2 3
4 5 6
7 8 910
It should be:
1
2 3
4 5 6
7 8 9 10
You can change the alignment by using the - sign. This makes it left-justified.
Replace
printf("%2d",j);
with
printf("%-2d",j);
Live demo
If you want the bottom of the pyramid to be completely to the left with no space you can replace
for (k = i - 1; k >= 0; k--)
with
for (k = i - 1; k > 0; k--)
EDIT:
As #chqrlie pointed out this will leave a trailing blank space in every line except the last one, this can be fixed like:
//...
for (i = 4; i >= 1; i--)
{
for (k = i - 1; k > 0; k--) // change from k >= 0 to k > 0
{
printf(" ");
}
for (l = 4; l >= i; l--)
{
printf(" %d", j); // change from "%2d" to " %d"
j++;
}
printf("\n");
}
//...
Live demo
For this problem, with n lines of output, you need to produce n - i spaces at the beginning of line i and i numbers each preceded by a space. Instead of "%2d", use " %d" and output one less space at the start of each line. You can use printf to output an arbitrary number of spaces using %*s and an empty string.
Here is a modified version:
#include <stdio.h>
int main() {
int i; // line number
int j = 1; // starting number
int n = 4; // number of lines
int k;
for (i = 1; i <= n; i++) {
printf("%*s", n - i, ""); // output n - i spaces
for (k = 0; k < i; k++) {
printf(" %d", j);
j++;
}
printf("\n");
}
return 0;
}
Output:
1
2 3
4 5 6
7 8 9 10
It can be solved in two ways:
One way to resolve this is by simply add spacing (padding) for each character you are printing.
#include<stdio.h>
int main()
{
int j=1,k,l,i;
for(i=4;i>=1;i--){
for(k=i-1;k>=0;k--){
printf(" ");
}
for(l=4;l>=i;l--){
printf(" %2d ",j); //Padding added
^ ^
j++;
}
printf("\n");
}
return 0;
}
Secondly you can change the alignment by using - sign
#include<stdio.h>
int main()
{
int j=1,k,l,i;
for(i=4;i>=1;i--){
for(k=i-1;k>=0;k--){
printf(" ");
}
for(l=4;l>=i;l--){
printf("-%2d",j); //Left justified
^
j++;
}
printf("\n");
}
return 0;
}
Amongst the other good answers, another way is to use printf("%d ", j); instead of printf("%2d", j); - Note the white space ' ' behind the %d format specifier. - This method has the disadvantage that you have a trailing white space after 10 but it accomplishes the (obvious) desired output:
Online example
#include <stdio.h>
int main (void)
{
int j = 1, k, l, i;
for (i = 4; i >= 1; i--){
for (k = i - 1; k >= 0; k--) {
printf(" ");
}
for(l = 4; l >= i; l--) {
printf("%d ", j);
j++;
}
printf("\n");
}
return 0;
}
Output:
1
2 3
4 5 6
7 8 9 10

How do I print a right triangle with alphabets?

A
A B
A B C
Please let me know how to print the above sequence.
Condition for spaces should be as below
A(no space)
A(space)B(no space)
A(space)B(space)C(no space)
#include <stdio.h>
int main() {
int i = 65; //'A' = 65 ASCII value
for (int x = 1; x < 10; x++) {
for (int y = 0; y < x; y++) {
printf("%c", (char)i);
i++;
if (y < (x-1)) printf(" ");
}
printf("\n");
i = 65;
}
return 0;
}
Instead of 10 x < 10, insert how many lines with letters you want to be printed

Nested for/while loops and arrays, filtering out numbers from an array

int main(void)
{
int i,j=0,k; //initialization
char equation[100]; //input is a string (I think?)
int data[3]; //want only 3 numbers to be harvested
printf("Enter an equation: ");
fgets(equation, 100, stdin); //not so sure about fgets()
for (i = 0; i < equation[100]+1; i++) { //main loop which combs through
//"equation" array and attempts
//to find int values and store
while (j <= 2) { //them in "data" array
if (isdigit(equation[i])) {
data[j] = equation[i]
j++;
}
}
if (j == 2) break;
}
for (k = 0; k <= 2; k++) { //this is just to print the results
printf("%d\n", data[k]);
}
return 0;
}
Hello! This is my program for my introductory class in C, I am trying to comb through an array and pluck out the numbers and assign them to another array, which I can then access and manipulate.
However, whenever I run this I get 0 0 0 as my three elements in my "data" array.
I am not sure whether I made an error with my logic or with the array syntax, as I am new to arrays.
Thanks in advance!!! :)
There are a few problems in your code:
for (i = 0; i < equation[100]+1; i++) { should be something like
size_t equ_len = strlen(equation);
for (i = 0; i < equ_len; i++) {
Whatever the input is, the value of equation[100] is uncertain, because char equation[100];, equation only has 100 element, and the last of them is equation[99].
equation[i] = data[j]; should be
data[j] = equation[i];
I suppose you want to store digit in equation to data.
break; should be deleted.
this break; statement will jump out of the while loop, the result is you will store the last digit in equation to data[0] (suppose you have switched data and equation, as pointed out in #2).
If you want the first three digits in equation, you should do something like
equ_len = strlen(equation);
j = 0;
for (i = 0; i < equ_len; i++) {
if (j <= 2 && isdigit(equation[i])) {
data[j] = equation[i];
j++;
}
if (j > 2) break;
}
printf("%d\n", data[k]); should be printf("%c\n", data[k]);
%d will give the ASCII code of data[k], for example, if the value of data[k] is character '1', %d will print 50 (the ASCII code of '1') instead of 1.
Here is my final code, based on the OP code:
#include <ctype.h>
#include <string.h>
#include <stdio.h>
int main(void)
{
int i,j,k;
char equation[100];
int data[3];
int equ_len;
printf("Enter an equation: ");
fgets(equation, 100, stdin);
equ_len = strlen(equation);
j = 0;
for (i = 0; i < equ_len; i++) {
if (j <= 2 && isdigit(equation[i])) {
data[j] = equation[i];
j++;
}
if (j > 2) break;
}
for (k = 0; k <= 2; k++) {
printf("%c\n", data[k]);
}
return 0;
}
Tested with:
$ ./a.out
Enter an equation: 1 + 2 + 3
1
2
3

Resources