How can I print multiple character with one printf? - c

I want to print multiple character using printf. My approach up to now is this-
#include <stdio.h>
int main()
{
printf("%*c\n", 10, '#');
return 0;
}
But this only prints 9 spaces before the #.
I want to print it like this-
##########
I am unable to figure out how to do this. Please help me?

You can not use printf like that to print repetitive characters in Ansi C. I suggest you to use a loop like this -
#include <stdio.h>
int main()
{
int i;
for(i = 0; i < 10; i++) putchar('#');
return 0;
}
Or if you have absolutely no desire to use loops, you can do something like this-
#include <stdio.h>
int main()
{
char out[100];
memset(out, '#', 10);
out[10] = 0;
printf("%s", out);
return 0;
}
By the way, using printf like this also works-
#include <stdio.h>
int main()
{
printf("%.*s", 10, "############################################");
return 0;
}

I think the best approach, if you have an upper limit to the number of characters to be output is:
printf("%.*s", number_of_asterisks_to_be_printed,
"**********************************************************************");
I think this will also be the most efficient, portable way to do that.

this will print ten # characters, followed by a newline
char tenPounds[] = "##########";
printf( "%s\n", tenPounds);

I am working on a similar problem in "The C Programming Language" book (exercises 1-13 and 1-14). My own program, to start simply, is to count the occurrences of the digits 0 to 9 in a given input, and print a horizontal histogram made of '=' bars according to each count.
To do this, I created the following program;
main() {
int c, ix, k;
int nDigit[10];
//Instantiate zero values for nDigits array
for(ix = 0; ix < 10; ix++) {
nDigit[ix] = 0;
}
//Pull in input, counting digit occurrences and
//incrementing the corresponding value in the nDigit array
while ((c = getchar()) != EOF) {
if (c >= '0' && c <= '9') {
++nDigit[c-'0'];
}
}
//For each digit value in the array, print that many
//'=' symbols, then a new line when completed
for (ix = 0; ix < 10; ix++) {
k = 0;
while (k <= nDigit[ix]) {
putchar('=');
k++;
}
printf("\n");
}
}
Note that this is a work in progress. A proper histogram should include axes labels, and most importantly this program does not account for digits of zero count. If the input includes five 1's but no 0's, there is no visual way to show that we have no zeros. Still, the mechanism for printing multiple symbols works.

Related

Why are there random characters outputting in my code?

I have been writing a program to input a phrase and turn it into an acronym. For some reason when I output my acronym at the moment it comes out with a bunch of random characters. How do I fix it?
#include <stdio.h>
#include <string.h>
#define MAXLEN 50
int main() {
int num;
printf("Enter number of acronyms to add to the database:");
scanf("%d", &num);
getchar();
char strings[num][MAXLEN];
char acronym[num][MAXLEN];
for(int i = 0; i < num; i++){
printf("Enter the string to convert into an acronym:");
fgets(strings[i],MAXLEN,stdin);
printf("%s\n", strings[i]);
for(int j = 0; j < 11; j++){
if((strings[i][j]) >= 'A' && (strings[i][j]) <= 'Z'){
char buffer[][20] = {strings[i][j]};
strcat(acronym[i], buffer[i]);
}
}
puts(acronym[i]);
}
return 0;
}
I have tried changing the MAXLEN value to see if it was a memory issue or like a buffer overload. I've also just tried changing around how the strings switch and work together but nothing has worked.
char buffer[][20] = {strings[i][j]};
Here you let the compiler count how many elements the array has from the initialization.
It has 1 element, A string with single a single character strings[i][j] and rest of the 20 byte array filled with 0.
strcat(acronym[i], buffer[i]);
Here you access buffer[i], but there is only one string there (as explained above), so this is invalid if i is anything but 0.
I'm not sure what you are trying to do, but this would be valid implementation of what this code tries to do:
// extract single character as a string
char buffer[2] = {strings[i][j], 0}; // only one of 2 and 0 is mandatory
// append it to acronym
strncat(acronym[i], 20, buffer);
Probably lots of other stuff there is wrong, but here is one definite issue and a possible solution.

nice way to make a pyramid with numbers >10

I'm new to C and programming in general. I wanted to create a pyramid of numbers I have seen on a class test. I managed to do it, but the problem is that when the numbers get over 9, the pyramid gets terrific. this is what I wanted to achieve without writing a lot of IFs
my code:
#include <stdio.h>
int strlen(char *str);
int main(int argc, char **args){
char spaces[] = {"| "};
int i = 1, line = 1; //line number of numbers per line
while(spaces[strlen(spaces)-1] != '|'){
printf("%s", spaces);
for(int k = 0; k < line; k++){
printf("%d", i);
i++;
}
printf("\n");
spaces[strlen(spaces)-1] = '\0';
line += 2;
}
}
int strlen(char *str){
int i = 0;
while(*(str + i))
i++;
return i;
}
You showed what you wanted to achieve without writing a lot of IFs: print the pyramid of numbers with a field width of 6. Your principal approach was right: in each line, first print the leading spaces, then print the numbers. What is missing is to account for the field width of the leading spaces as well as the numbers themselves. This can be done e. g. by changing your while loop to
int lines = 16; // how many lines you want
while (lines--)
{
// in this line, we need leading spaces for `lines` numbers
printf("%*s", lines*6, ""); // you chose 6 spaces per number
// print each number with the chosen width
for (int k = 0; k < line; k++) printf("%-6d", i++);
puts("");
line += 2;
}

How to find duplicate letter in array in C

I am making a program which requires the user to input an argument (argv[1]) where the argument is every letter of the alphabet rearranged however the user likes it. Examples of valid input is "YTNSHKVEFXRBAUQZCLWDMIPGJO" and "JTREKYAVOGDXPSNCUIZLFBMWHQ". Examples of invalid input would then be "VCHPRZGJVTLSKFBDQWAXEUYMOI" and "ABCDEFGHIJKLMNOPQRSTUYYYYY" since there are duplicates of 'V' and 'Y' in the respective examples.
What I know so far is, that you can loop through the whole argument like the following
for (int j = 0, n = strlen(argv[1]); j < n; j++)
{
//Place something in here...
}
However, I do not quite know if this would be the right way to go when looking for duplicates? Furthermore, I want the answer to be as simple as possible, right know time and cpu usage is not a priority, so "the best" algorithm is not necessarily the one I am looking for.
Try it.
#include <stdio.h>
#include <stddef.h>
int main()
{
char * input = "ABCC";
/*
*For any character, its value must be locate in 0 ~ 255, so we just
*need to check counter of corresponding index whether greater than zero.
*/
size_t ascii[256] = {0, };
char * cursor = input;
char c = '\0';
while((c=*cursor++))
{
if(ascii[c] == 0)
++ascii[c];
else
{
printf("Find %c has existed.\n", c);
break;
}
}
return 0;
}
assuming that all your letters are capital letters you can use a hash table to make this algorithm work in O(n) time complexity.
#include<stdio.h>
#include<string.h>
int main(int argc, char** argv){
int arr[50]={};
for (int j = 0, n = strlen(argv[1]); j < n; j++)
{
arr[argv[1][j]-'A']++;
}
printf("duplicate letters: ");
for(int i=0;i<'Z'-'A'+1;i++){
if(arr[i]>=2)printf("%c ",i+'A');
}
}
here we make an array arr initialized to zeros. this array will keep count of the occurrences of every letter.
and then we look for letters that appeared 2 or more times those are the duplicated letters.
Also using that same array you can check if all the letters occured at least once to check if it is a permutation
I don't know if this is the type of code that you are looking for, but here's what I did. It looks for the duplicates in the given set of strings.
#include <stdio.h>
#include <stdlib.h>
#define max 50
int main() {
char stringArg[max];
int dupliCount = 0;
printf("Enter A string: ");
scanf("%s",stringArg);
system("cls");
int length = strlen(stringArg);
for(int i=0; i<length; i++){
for(int j=i+1; j<length; j++){
if(stringArg[i] == stringArg[j]){
dupliCount +=1;
}
}
}
if(dupliCount > 0)
printf("Invalid Input");
printf("Valid Input");
}
This code snippet is used to count the duplicate letters in the array.
If you want to remove the letters, Also this code snippet is helpful .Set null when the same characters are in the same letter.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int count=0;
int array[]={'e','d','w','f','b','e'};
for(int i=0;i<array.Lenth;i++)
{
for(int j=1;j<array.Length;j++)
{
if(array[i]==array[j])
{
count++;
}
}
}
printf("The dublicate letter count is : %d",count);
}

I want to print out the text with the most number of times entered

#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int h[26]={0};
int i, j, count, tmp=0;
scanf("%s", str);
count=strlen(str);
for(i=0; i<count; i++) {
h[str[i]-97]++;
}
for(j=0; j<25; j++) {
if(h[j]<h[j+1]) {
tmp=j+1;
}
}
printf("%c", (char)tmp+97);
}
I want to output the most frequently entered lowercase letters, but how can I change it by output the strange values?
Try input this code "aaaabbbbsefa", then the "s" will be output.
Your code has a lot of problems. And a good bit of traps.
scanf("%s", str);
What if the input is longer than str can hold?
count=strlen(str);
This is a waste of cpu cycles. You don't need the length of a string to loop through it, you can simply check if the current element of the string is a \0
for(i=0; i<count; i++) {
h[str[i]-97]++;
}
This is problematic, what if the input contained some other character than lower case characters, this could easily cause out of bounds reading.
for(j=0; j<25; j++) {
if(h[j]<h[j+1]) {
tmp=j+1;
}
}
Firstly, this loop stops before 25, but it should stop before 26
Secondly, this definitely does not do what you think it does.
If you want to print the most frequent lower case character from in your input, this is how the flow should look like-
Take the string input and store it into a char array, make sure it can actually hold it
Declare a variable to keep track of the number of occurrences for each lowercase alphabet
Loop through the input string
Check if the current element is lowercase - if it is, add to the counter - if it isn't, do nothing
Loop through the occurrences record, check if the current occurrence is higher than the highest record (which is set to 0 before the loop) - if it higher, change the highest record to it and store the character - if it isn't, move on
Print the resulting character
This is how that'd look like in C-
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define ALPHABET_COUNT 26
#define MAX_LEN 100
int main()
{
char str[MAX_LEN];
int occurrences[ALPHABET_COUNT] = { 0 };
if (!fgets(str, MAX_LEN, stdin))
{
// Something went wrong, error handling here
return 1;
}
for (int i = 0; str[i] != '\0'; i++)
{
if (islower(str[i]))
{
occurrences[str[i] - 'a']++;
}
}
int highest_occurrence = 0;
char highest_occurring_char;
for (int i = 0; i < ALPHABET_COUNT; i++)
{
if (occurrences [i] > highest_occurrence)
{
highest_occurrence = occurrences[i];
// Convert the current index to its corresponding lowercase alphabet
highest_occurring_char = (char) (i + 'a');
}
}
printf("Highest occurring character: %c\n", highest_occurring_char);
}

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;
}

Resources