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;
}
Related
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 :)
#define maximum 100
#include <math.h>
#include <stdio.h>
int main () {
float sum, mean, variance, difference;
float sumforvariance, standarddev;
sumforvariance=0;
sum=0;
mean=0;
variance=0;
difference=0;
standarddev=0;
int a, count, b, c;
float insertnum[maximum]
for (a=0; a<maximum; a++) {
scanf("%f",&insertnum[a]);
count ++;
if (insertnum[a]==35.00) {
if (count==1) {
printf ("no data\n");
return 0;
}
break;
}
}
for (b=0; b<count; b++) {
sum+=insertnum[b];
}
mean=sum/count;
for (c=0; c<count; c++) {
difference=insertnum[c]-mean;
sumforvariance=sumforvariance+pow(difference,2);
}
variance=variance/count;
standarddev=sqrt(variance);
printf("mean: %f",mean);
printf("standdev: %f",standarddev);
Hi so I have a simple question. I am trying to calculate a standard deviation and mean for a set of numbers like this
./a.out 12 20 30 etc #
The # is to terminate inputing more numbers. As you can see in the first for loop, I am trying to input the numbers from standard output into an array of floats. The problem is when I enter 35, I do not want to terminate inputting more numbers because its not equal to #. How am I able to enter 35 and continue to enter more numbers until I enter # since they both contain the same numerical value. #=35 and 35=35.
Read you user input in as a string. Sniff for the terminating condition, then convert from string to float. Using the helper function, strtof which is available from #include <stdlib.h>
#define maximum 100
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
int main() {
float sum, mean, variance, difference;
float sumforvariance, standarddev;
sumforvariance = 0;
sum = 0;
mean = 0;
variance = 0;
difference = 0;
standarddev = 0;
int a, count=0, b, c;
float insertnum[maximum];
for (a = 0; a < maximum; a++) {
char userinput[101] = {0};
userinput[0] = '\0';
scanf("%100s", userinput);
if (userinput[0] == '#')
{
break;
}
insertnum[count] = strtof(userinput, nullptr);
count++;
}
return 0;
}
Also, you forgot to initialize count. And your code was inserting the # read into the array as well. So I fixed that for you.
Aside - I'll never forget the day my computer science professor passionately screamed to the class about the dangers of "reading numbers" from input. Users type characters with the keyboard not numbers. Hence, "validating input" became engrained with me to this day. You might want to consider just letting your loop break whenever the user types anything not a number. A modified version of the loop as follows:
for (a = 0; a < maximum; a++) {
char userinput[101] = {0};
userinput[0] = '\0';
scanf("%100s", userinput);
char* endptr = NULL;
float f = strtof(userinput, &endptr);
if (userinput == endptr)
{
// whatever was typed was not a float
break;
}
insertnum[count] = f;
count++;
}
Check the return value of scanf -- when it successfully converts a float it will return 1 (or more generally, however many conversions in the format string succeeded). So when the input is #, it will return 0 (nothing converted) and leave the # on in the input stream. You can then check the next character to make sure its a #. So you end up with a loop like:
for (a=0; a<maximum && scanf("%f",&insertnum[a]) == 1; a++) {
++count;
}
or even
for (count=0; count < maximum && scanf("%f",&insertnum[count]) == 1; ++count);
if (count == maximum) {
// read the limit -- may be more data
} else {
if (getchar() == '#') {
// got the expected terminator
} else {
// something else caused a problem
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.
I'm new in C programming language.
I need to get every digit separately that user have entered.
Here is my code:
#include <stdio.h>
int main()
{
int n[100];
printf("Enter a number: ");
scanf("%d",&n);
printf("%d %d %d",n[1],n[2],n[3]);
return 0;
} //i know that my code is not assigning like i want.
and now for example user entered a number like 123, i want the output like 1 2 3, How can i assign every digit to n[i] ? Without using string to int or int to string like atoi? Here is what Im going to do: User will enter a number and the program will search from Matrix 100x100 in row or column. i think i need to get the every digit separately to search.
No need to go to character array. The lats digit of a number n can be computed using n%10. Then you can remove the last digit using n /= 10. So this cycle would print the digits in reverse order:
void print_rev_digits(int n) {
while (n) {
printf("%d\n", n%10);
n /= 10;
}
}
And using a stack you can print the digits in the correct order. You can also use recursion for this(which will use stack for you). I am deliberately not posting a complete solution.
In this case you should read the user input character by character:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
int main()
{
char input[100];
int n[100];
printf("Enter a number: ");
if (fgets(input, sizeof(input), stdin)) { // attempt to read a line
int i;
for (i = 0; input[i]; i++) { // for each entered character
if (input[i] >= '0' && input[i] <= '9') { // is a digit
n[i] = input[i] - '0';
printf("%d ", input[i] - '0');
}
else if (isspace(input[i])) // end of entered integer
break;
else {
printf(stderr, "Input is not a number\n");
return -1;
}
}
printf("\n");
} else {
fprintf(stderr, "User did not enter valid input.\n");
}
return 0;
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
The program requires a user to insert a number. Let's say we put 149. Now the program prints every number that has 0 digits in them till the number 149 (Including the number). So it's going to be 10,20,30,40,50,60,70,80,90,100,101...110..140 [Let's say the limit would be till 10000]
I have been trying to do this, but i only added +10 to every one, but that cannot be done >100 where it is 101,102..
Use the function sprintf to convert an integer to a string and then search for the character '0' in the string. If found, then print the number. Here's a simple working program implementing this idea.
#include <stdio.h>
#include <string.h>
#define MAXLEN 50 // max number of digits in the input number
int main(void) {
char buf[MAXLEN + 1]; // +1 for the null byte appended by sprintf
char ch = '0'; // char to be searched for in buf
int i, x;
if(scanf("%d", &x) != 1) {
printf("Error in reading input.\n");
return -1;
}
for(i = 1; i <= x; i++) {
sprintf(buf, "%d", i); // write i to the string buffer and append '\0'
if(strchr(buf, ch)) // strchr returns a pointer to ch if found else NULL
printf("%d\n", i);
}
return 0;
}
You can also extract each digit of an integer in the given range and check it for zero. Here's a naive implementation.
#include <stdio.h>
int main(void) {
int i, x;
int r;
if(scanf("%d", &x) != 1) {
printf("Error in reading input.\n");
return -1;
}
for(i = 1; i <= x; i++) {
for(r = i; r > 0; r /= 10) {
if(r%10 == 0) {
printf("%d\n", i);
break;
}
}
}
return 0;
}
The simple approach would be to iterate through all natural numbers up to the target number and testing each of them to see if they have any zero digits. Note that the last digit of a non-negative integer i can be obtained as the remainder from division by the base (i % 10 here). Also remember that integer division in C truncates decimals, e.g., (12 / 10) == 1
As a start, consider to convert each number to char [] and then check whether it contains a '0' or not.
To read on:
How to check if a int var contains a specific number
Count the number of Ks between 0 and N
I think this would be the answer.
int j;
for(int i=1;i<150;i++){
j=i;
while(j>0)
{
if(j%10==0)
{
printf("%d\n",i);
break;
}
else
j=j/10;
}
}