Printing square using specified character and multiplying chars [closed] - c

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed last year.
The community reviewed whether to reopen this question last year and left it closed:
Original close reason(s) were not resolved
Improve this question
Write a programme that prints a square pattern of side length M of any single character specified by the user using a single for loop and a single if else statement. You should define both M and the character constant C as preprocessor statements.
I actually did that but I wonder is there any easier way to solve this problem. Here's my code:
#include <stdio.h>
#include <string.h>
int
main()
{
int M, i = 1;
char C, G[1000];
printf("Input a value for side length:\n");
scanf("%d", &M);
printf("Input a character for pattern:\n");
scanf(" %c", &C);
for (; i <= M; i++) {
printf("%c", C);
if (i <= M) {
memset(G, C, (M - 1));
G[M - 1] = '\0';
puts(G);
}
}
return 0;
}

Something along these lines, perhaps:
int M1 = M + 1;
for (int i = 0; i < M*M1; ++i) {
if (i % M1 == M) putchar('\n');
else putchar(C);
}

You can do the memset outside of the loop once.
You can just do puts inside the loop:
#include <stdio.h>
#include <string.h>
int
main()
{
int M, i = 1;
char C, G[1000];
printf("Input a value for side length:\n");
scanf("%d", &M);
printf("Input a character for pattern:\n");
scanf(" %c", &C);
memset(G, C, M);
G[M] = '\0';
for (; i <= M; i++)
puts(G);
return 0;
}
For an input of 8 rows and a char of *, the output is:
Input a value for side length:
8
Input a character for pattern:
*
********
********
********
********
********
********
********
********
UPDATE:
After rereading the requirements, if C and M must be macros, the code should be:
#include <stdio.h>
#include <string.h>
#ifndef M
#error M not defined
#endif
#ifndef C
#error C not defined
#endif
int
main()
{
int i = 1;
char G[1000];
memset(G, C, M);
G[M] = '\0';
for (; i <= M; i++)
puts(G);
return 0;
}
And, the program should be compiled with:
cc -o program -DM=8 -DC="'*'" program.c

Related

warning array comparison between pointer and integer [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
So i have this problem where i have to input a string of unknown size with only lowercase letters then output the number of distinct letters.this is the main program
#include <stdio.h>
#include <ctype.h>
int test(char *T);
int main(){
char T[100];int i=-1,j=0,nd=0;
do{
gets(T);
}while((test(T))==1);
do {
i++;
j=i;
do{j++;
}while ((T[i]!=T[j])||((T[j])!=""));
if (T[j]=="")
nd++;
}while (T[i+1]!="");
and this is my function test
int test(char *T){
int i=-1,s;
do {
i++;
}while (((islower(T[i])==1))||(T[i]==""));
if ((T[i]=="")&&(i!=0))
s=0;
else s=1;
return s;
}
the problem is that i get a lot of warnings "comparison between integer and pointer" everytime i compare a char of the array T and i don't knowhow to fix that.your help would be much appreciated.
Update:So i tried fixing the program following your advices and this is the new main program
#include <stdio.h>
#include <ctype.h>
int test(char *T);
int main(){
char T[100];int i=-1,j=0,nd=0;
do{
gets(T);
}while((test(T))==1);
do {
i++;
j=i;
do{j++;
}while ((T[i]!=T[j])||((T[j])!='\0'));
if (T[j]=='\0')
nd++;
}while (T[i+1]!='\0');
printf("%d",nd);}
and this is function test
int test(char *T){
int i=-1,s;
do {
i++;
}while (((islower(T[i])==1))||(T[i]=='\0'));
if ((T[i]=='\0')&&(i!=0))
s=0;
else s=1;
return s;
}
I don't get anymore warnings and the program gets compiled with no problems but after i input the string in the execution nothing happens.
You function test should return 1 if the string contains only lowercase letters, and 0 otherwise. Unfortunately, it is not doing that.
You should first test if the character is a letter and then if it's a lowercase letter. Or more efficiently, you test if the character is in the range 'a' to 'z'.
Another problem of your code is the use of do while loops which makes the code difficult to understand and executes the loop once.
Here is a better implementation of the test function:
int test(char *T){
// reject empty strings
if(T[0] == '\0')
return 0;
// reject strings containing non lowercase letter
for(int i = 0; T[i] != '\0'; i++)
if((T[i] < 'a') || (T[i] > 'z'))
return 0;
// string is not empty and contains only lowercase letters
return 1;
Counting the different letters can be made more readable by using a for loop instead of a go while loop.
int nd = 0;
for(int i = 0; T[i] != '\0'; i++) {
for(int j = 0; j < i; j++) {
if(T[j] == T[i])
break; // quit inner loop
nd++;
}
}
This code examine each letter and see if it has been seen before. It is thus different from yours.
A problem in your code is the test (T[i]!=T[j])||((T[j])!='\0'). It should be && instead of ||, and testing if the end of string is reached should be performed first. The test should be (T[j]!='\0')&&(T[i]!=T[j]).
So my code is finally working here's the final main program
#include <stdio.h>
#include <ctype.h>
int test(char *T);
int main(){
char T[100];int i,j,nd=0;
do{
gets(T);
}while((test(T))==0);
for(i = 0; T[i] != '\0'; i++) {
j=i;
do{
j++;
}while ((T[j]!='\0')&&(T[j]!=T[i]));
if (T[j]=='\0')
nd++;
}
(#chmike i used the code you posted with a little adjustment on the loop)
and for the function test i used the code that posted #chmike as well.
Huge thanks to all of you guys for the help you provided :)

Adding integers together in C but not mathematically [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
How would one go about adding integers together like this.
Say you start with 1, then you add 2. So you have 12, next add 3, so you have 123. And so on.
I would just concatenate but I'm not allowed to use strings in this program.
Using some unusual math (based on the mechanisms of the decimal system) to make the desired variation of adding:
Code:
#include <stdio.h>
int main(void)
{
int i;
int number=0;
for (i=1; i<5; ++i)
{
number=number*10 + i;
printf("%d\n", number);
}
return 0;
}
Output:
1
12
123
1234
Like this?
#include <stdio.h>
int main() {
int a = 4, b = 5, c = 6, d = 7;
printf("a+b=%d\n",a*10+b);
printf("a+b+c=%d\n",(a*10+b)*10+c);
printf("a+b+c+d=%d\n",((a*10+b)*10+c)*10+d);
return 0;
}
This can be typical case to use realloc
char *mystr = NULL;
char *temp;
char c, ch;
short count = 0;
do {
printf("Enter character : ");
scanf(" %c", &c); // Better use sscanf or fgets, scanf is problematic
temp = (char*)realloc(mystr, (++count) * sizeof *mystr);
if (NULL != temp) {
mystr = temp;
mystr[count - 1] = c;
}
printf("Do you wish to continue: ");
scanf(" %c", &ch);
} while ('y' == ch);
// Since and since you don't have a null terminated string, do
for (int i = 0; i < count; i++)
printf("%c", mystr[i]);
printf("\n");
free(mystr); // Freeing the memory
getch();
Note : And you don't have strings in this program ;)

C program to find total number of digits [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I wrote this program to find the total number of digits from a line of text entered by user. I am having error on using getchar(). I can't seem to figure out what am I doing wrong?
#include <stdio.h>
#define MAX_SIZE 100
void main() {
char c[MAX_SIZE];
int digit, sum, i;
digit, i = 0;
printf("Enter a line of characters>");
c = getchar();
while (c[i] != '\n') {
digit = 0;
if (c [i] >= '0' && c[i] <= '9') {
digit++;
}
}
printf("%d\n", digit);
}
I will be adding all the digits I found using sum variable. but I am getting error on getchar() line. HELP??
You can enter a "line of text" without using an array.
#include <stdio.h>
#include <ctype.h>
int main(void) { // notice this signature
int c, digits = 0, sum = 0;
while((c = getchar()) != '\n' && c != EOF) {
if(isdigit(c)) {
digits++;
sum += c - '0';
}
}
printf("%d digits with sum %d\n", digits, sum);
return 0;
}
Note that c is of type int. Most of the library's character functions do not use char type.
Edit: added the sum of the digits.
Weather Vane's answer is the best and simplest answer. However, for future reference, if you want to iterate (loop through) an array, it would be easier to use a for loop. Also, your main function should return an int and should look like this: int main(). You will need to put a return 0; at the end of your main function. Here is a modified version of your program that uses a for loop to loop through the character array. I used the gets function to read a line of characters from the console. It does wait for the user to enter the string.
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
char c[MAX_SIZE];
int digit = 0;
printf("Enter a line of characters>");
gets(c);
for (int i = 0; i < MAX_SIZE; i++)
{
if (c[i] == '\n') break; // this line checks to see if we have reached the end of the line. If so, exit the for loop (thats what the "break" statment does.)
//if (isdigit(c[i])) // uncomment this line and comment or delete the one below to use a much easier method to check if a character is a digit.
if (c [i]>= '0' && c[i] <= '9')
{
digit++;
}
}
printf("%d\n", digit);
return 0;
}
An easy of getting the number of digits in an integer is the use of log10() function which is defined in math.h header. Consider this program
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main (int argc, const char *argv[]) {
system("clear");
unsigned int i, sum = 0, numberOfDigits;
puts("Enter a number");
scanf("%u", &i);
numberOfDigits = (int) (log10(x) + 1);
system("clear");
while(i != 0) {
sum += (i % 10);
i /= 10;
}
fprintf(stdout, "The sum is %i\n", sum);
fflush(stdin);
return 0;
}

Eerror message in function 'main' [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Program to take the input and output the reverse of it:
#define MAX 1000
int readtext(char[],int); /*used to store text in array and
returns the size of the line*/
void reverse(char[]); /*used to reverse the text in the line and
returns 0*/
int main(void)
{
char text[MAX];
printf("Enter text, press Ctrl+d when done \n"); /*prompt user input*/
while((redtext(text, sizeof text)>0)) /*loop repeats until text size is >0*/
{
reverse(text);
printf("%s\n\n",text);
}
return 0;
}
int readtext(char a[],int len)
{
int letchar,i;
for(i=0;i<len-1 && (letchar=getchar())!=EOF && letchar!='\n';i++) /*for loop repeats until end of line*/
a[i]=letchar;
if(letchar=='\n') /*checks if letchar is \n. if true, changes it to null and returns i value*/
a[i++]=letchar;
a[i]='\0';
return i;
}
void reverse(char a[])
{
char t;
int x,y;
for(y=0;a[y]!='\0';y++) /*loop used to get the last element of the array*/
--y;
for(x=0;x<y;x++) /*loop used to reverse the array 'a'*/
{
t=a[x];
a[x]=a[y];
a[y]=t;
--y;
}
}
expected input/output:
happy birthday
yadhtrib yppah
I am getting this error message, but do not know what it means:
/tmp/ccA71SDX.o: In function `main':
1-19.c:(.text+0x63): undefined reference to `redtext'
collect2: ld returned 1 exit status
You have made a mistake in function call (redtext instead of readtext). However you can use my solution:
#include <stdio.h>
#include <strings.h>
#define MAXSTRLEN 256
void Reverse(char* str);
int main()
{
printf("Enter string below:\n");
char str[MAXSTRLEN];
fgets(str, MAXSTRLEN, stdin);
Reverse(str);
printf("Result:\n%s\n", str);
return 0;
}
void Reverse(char* str)
{
char tmp;
int length = strlen(str) - 1;
int i;
for(i = 0; i < length / 2; i++)
{
tmp = str[i];
str[i] = str[length - i - 1];
str[length - i - 1] = tmp;
}
}

Double Pyramid Pattern : Not Getting desired output [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am not getting the desired output for my C program can anyone please have a look on the code and help me to rectify the error ?
Desired output and actual output of my code is:
My Code is:
#include <stdio.h>
#include <conio.h>
void main()
{
int i,j,k;
int blank=0;
int lines = 6;
char symbol='A';
int temp ;
int diff[7]= {0,1,3,5,7,9,11};
k=0;
for(i=lines;i>=0;i--)
{
printf("\n");
symbol = 'A';
for(j=i;j>=0;j--)
printf("%c ",symbol++);
blank = diff[k++];
for(j=0;j<blank;j++)
printf(" ");
symbol = 'F' - (blank/2);
if (blank== 0)
temp = i-1;
else
temp = i;
for(j=0;j<=temp;j++)
printf("%c ",symbol--);
}
getch();
}
Your have written the code in a right way. You have to change the line
for(j=0;j<blank;j++)
printf(" ");
to
for(j=0;j<blank;j++)
printf(" "); // increase one more space
And also try to avoid using void main().Here is your edited code;
#include <math.h>
#include <stdio.h>
int main()
{
int i,j,k;
int blank=0;
int lines = 6;
char symbol='A';
int temp ;
int diff[7]= {0,1,3,5,7,9,11};
k=0;
for(i=lines;i>=0;i--)
{
printf("\n");
symbol = 'A';
for(j=i;j>=0;j--)
printf("%c ",symbol++);
blank = diff[k++];
for(j=0;j<blank;j++)
printf(" ");
symbol = 'F' - (blank/2);
if (blank== 0)
temp = i-1;
else
temp = i;
for(j=0;j<=temp;j++)
printf("%c ",symbol--);
}
return 0;
}
And do not forgot to include headers.
The problem is here
for(j=0;j<blank;j++)
printf(" ");
^
A
You are printing only a single space it should be two.So that one space corresponds to the alphabet and another to the actual space
printf(" ");
^^
A(space)
Firstly, you're printing the wrong number of blanks. And the number you need can be worked out with a small piece of arithmetic.
Secondly, you don't need that messy calculation to work out the first symbol to print out after the blanks because you've already worked it out.
(editted so downvote can be withdrawn)
You need to use more blank spaces
Use 0, 2, 6... so on
Your "diff" array is too small. You're accounting for the missing characters on the left side of the pattern, but not on the right side. Try making the first three elements {0, 2, 6...} and see if that works, and then work on extrapolating the correct pattern from there

Resources