I need help trying to find where to place the print statements in each function (alpha_count and sum_digits) so that they will only print once (at the end of the program).
Ex.
Number of characters: 8
Sum of digits: 19
As of right now they print each time the function has been called. Any ideas?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
//Prototypes
void count_alpha(char *s, int len, int index);
void sum_digit(char *s, int len, int index);
#define SIZE 22
int main(void){
//Declarations
char string[SIZE];
int length;
//Get string from user
printf("Enter a string of letters and numbers: ");
scanf("%s", string);
printf("String: %s\n", string);
//Get length of string
length = strlen(string);
printf("Length: %d\n", length);
//Get letters from string
count_alpha(string, length, 0);
return 0;
}
void count_alpha(char *s, int len, int index){
static int characters = 0;
char c = ' ';
if (index < len){
c = s[index];
if(isalpha(c)){
characters++;
printf("char: %d\n", characters);
index++;
printf("index: %d\n", index);
count_alpha(s, len, index);
}
else if(isdigit(c)){
sum_digit(s, len, index);
}
//index++;
//printf("index: %d\n", index);
//printf("Number of Characters: %d\n", characters);
}
//else
printf("Number of Characters: %d\n", characters);
}
void sum_digit(char *s, int len, int index){
static int digits = 0;
char c = ' ';
if (index < len){
c = s[index];
if(isalpha(c)){
count_alpha(s, len, index);
}
else if(isdigit(c)){
printf("num is: %c", c);
//printf("number is: %d", (atoi(&s[index])));
//digits += atoi(&c);
digits += c - '0';
printf("sum: %d\n", digits);
index++;
printf("index: %d\n", index);
sum_digit(s, len, index);
}
//index++;
//printf("index: %d\n", index);
//printf("Sum of digits: %d\n", digits);
}
//else
printf("Sum of digits: %d\n", digits);
}
Declare int characters = 0 and int digits =0 globally, keeping them global will be of same use as of static variables in addition it can be accessed anywhere thus will help you in printing what you wanted just once in main function.
For declaring them global just declare them outside all functions and at start of program.
.
.//header files
.
//#include <ctype.h>
int characters = 0;
int digits = 0;
In main(): just print them
printf("Number of Characters: %d\n", characters);
printf("Sum of digits: %d\n", digits);
EDIT: Without global variables by using pointers.
void count_alpha(char *s, int len, int index,int *charac,int *dig);
void sum_digit(char *s, int len, int index,int *charac,int *dig);
In main:
int* charac=&characters;
int* dig=&digits;
count_alpha(string,length,0,charac,dig);
And whenever you see a function call pass these pointers:
count_alpha(string,length,0,charac,dig);
For incrementing values just use:
(*charac)++;
(*dig)++;
As alpha_count() and sum_digits() are effectively doing some statistics gathering, pass in a pointer to a statistics type. Drop the static variables.
typedef struct {
unsigned characters;
unsigned digits;
} char_digs;
void sum_digit(char *s, int len, int index, char_digs *stat) {
// static int digits = 0;
...
count_alpha(s, len, index, stat);
...
stat->digits += c - '0';
...
sum_digit(s, len, index, stat);
...
}
void count_alpha(char *s, int len, int index, char_digs *stat) {
// like sum_digit() above
}
int main(void) {
...
char_digs stat = {0,0};
...
count_alpha(..., ..., &stat);
printf("Number of Characters: %u\n", stat.characters);
printf("Sum of digits: %u\n", stat.digits);
}
Related
I want to convert Name and Surname(e.g., Nova Stark) into a large integer by juxtaposing integer ASCII codes for alphabet, print the corresponding converted integer then cut the large integer into two halves and add the two halves.Following is my approach:-
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char* arr2str(int arr[], int size) {
static char buffer[256];
memset(&buffer[0], 0, sizeof(buffer)/sizeof(char));
char *ptr = &buffer[0];
for(int i=0; i<size; ++i) {
sprintf(ptr += strlen(ptr), "%d", arr[i]);
}
return buffer;
}
int arr2int(int arr[], int size)
{
char buffer[256] = {0,};
char *ptr = &buffer[0];
for(int i = 0; i < size; ++i) {
sprintf(ptr += strlen(ptr), "%d", arr[i]);
}
return atoi(&buffer[0]);
}
int main()
{
int *A;
long long int num;
int div,base=10;
char name[50],asc[200];
printf("Enter your name : ");
scanf(" %[^\n]",name);
int len=strlen(name);
A=(int*)malloc(len*sizeof(int));
for(int i=0;i<len;i++)
{
A[i]=name[i];
}
char *str = arr2str(A, len); //for converting array to string
num = arr2int(A, len); //again for converting the character array to integer.
//num=array_to_num(A,len);
div=base;
while(num/div>div)
{
div=div*base;
}
long long int a=num/div;
long long int b=num%div;
long long int c=a+b;
printf("The required integer is %lld and the sum is %lld ",num,c);
return 0;
}
But I am not getting the desired output. Please help!
Also, if there exists a simpler approach to the problem please specify that too.
Following is running, for explanations see comments in the code. Maybe you have to handle the whitespaces in the name:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int *A;
long long int num;
int div,base=10;
char name[50];
printf("Enter your name : ");
scanf(" %[^\n]",name);
int len=strlen(name);
A=(int*)malloc(len*sizeof(int));
for(int i=0;i<len;i++)
{
*(A+i)=(int)name[i]; // *(A+i) is accessing array as pointer+index : https://www.programiz.com/c-programming/c-dynamic-memory-allocation
// letters to ascii is done by simply typecasting to (int)
}
// string to int array
for(int i=0;i<len;i++)
{
printf("%i -> %c \n", *(A+i), (char)(*(A+i)));
}
// long long int from concatenating the elements of the int array
int s_idx=0; // index for string
char str[512]; //string of fixed size, possibly malloc this
for (int i=0; i<len; i++)
s_idx += snprintf(&str[s_idx], 512-s_idx, "%d", *(A+i));
printf("%s \n", str);
num = strtoll(str, NULL, 10); // https://en.cppreference.com/w/c/string/byte/strtol
// from here your code is unchanged
div=base;
while(num/div>div)
{
div=div*base;
}
long long int a=num/div;
long long int b=num%div;
long long int c=a+b;
printf("The required integer is %lld and the sum is %lld \n ",num,c);
free(A);
return 0;
}
#include <stdio.h>
int main() {
int k;
unsigned long long int aray[94];
aray[0]=0;
aray[1]=1;
unsigned long long int total=0;
printf("\n FIBONACCI : \n\n");
printf("1 + ");
for(k=2;k<=93;k++){
aray[k]=aray[k-1]+aray[k-2];
total+=aray[k];
printf("%llu + ",aray[k]);
}
return 0;
}
Hi guys I need to print total value printf("%llu",total);at the begining but I don't know how to do this thanks
calculate and "print" into a large enough string (or realloc() as needed)
char bigenough[200000];
char *p = bigenough;
loop {
/* ... calculate ... */
p += sprintf(p, "%llu + ", value);
}
afterwards print total and result string
printf("total: %llu = ", total);
printf("%s\n", bigenough);
I have been working on this simple code for hours now, and I have no idea what is wrong! I need to display number of alphabetical letters and the number of decimal digits in standard input. So far I have this:
#include<stdio.h>
#include<ctype.h>
int isalpha(int);
int isdigit (int);
int main()
{
int c;
while((c=getchar())!=EOF)
printf("The number of letters is %d and the number of digits is %d.\n", isalpha(c), isdigit(c));
return 0;
}
int isalpha(int one)
{
int ch;
int i;
i=0;
scanf("%d", &ch);
if(isalpha(ch))
i++;
return i;
}
int isdigit(int two)
{
int a;
int k;
k=0;
scanf("%d", &a);
if(isdigit(a))
k++;
return k;
}
Program crashes whenever I try to run it and I have no clue what part of the code is wrong. Although I don't have much experience in this field yet, so any help is highly appreciated! Thank you in advance.
Just use the existing API's gently and get the count as shown below
int alp = 0;
int dig = 0;
while ((c = getchar()) != EOF)
{
if (isalpha(c)
alp++;
else if (isdigit(c))
dig++;
}
printf("The number of letters is %d and the number of digits is %d.\n", alp,dig);
PS: Take care to flush the newline char if you have \n in the input
The example by recursive call
//gcc -O2 count_alpha_num.c -o count_alpha_num
#include <stdio.h>
#include <ctype.h>
void count_alpha_num(FILE *fp, int *alpha, int *num){
int ch;
if(EOF==(ch=fgetc(fp)))
return ;
if(isalpha(ch))
++*alpha;
else if(isdigit(ch))
++*num;
count_alpha_num(fp, alpha, num);
}
int main(void){
int a_c = 0, n_c = 0;
count_alpha_num(stdin, &a_c, &n_c);
printf("The number of letters is %d and the number of digits is %d.\n", a_c, n_c);
return 0;
}
Examples of Mutually recursive
#include <stdio.h>
#include <ctype.h>
void count_num(int loaded, int ch, int *alpha, int *num);
void count_alpha(int loaded, int ch, int *alpha, int *num){
if(ch==EOF)
return ;
if(isalpha(ch)){
++*alpha;
count_alpha(0, getchar(), alpha, num);
} else {
if(loaded)//Already been inspected by 'count_num'
count_num(0, getchar(), alpha, num);
else
count_num(1, ch, alpha, num);
}
}
void count_num(int loaded, int ch, int *alpha, int *num){
if(ch==EOF)
return ;
if(isdigit(ch)){
++*num;
count_num(0, getchar(), alpha, num);
} else {
if(loaded)
count_alpha(0, getchar(), alpha, num);
else
count_alpha(1, ch, alpha, num);
}
}
int main(void){
int a_c = 0, n_c = 0;
count_alpha(0, getchar(), &a_c, &n_c);
printf("The number of letters is %d and the number of digits is %d.\n", a_c, n_c);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 24
void rez(char **c, char *s, int n, int ks);
void rez(char **c, char *s, int n, int ks)
{
int t = 0, j = 0;
char *p;
p = strtok(s," ");
t = t + strlen(p);
if (strlen(p)>N) *(c+j)=(char*)malloc((strlen(p)+1)*sizeof(char));
else *(c+j)=(char*)malloc((N+1)*sizeof(char));
while(p!=NULL)
{
if (t>N)
{
*(*(c+j)+t) = '\0';
t = strlen(p) + 1;
j++;
if (t>N) *(c+j)=(char*)malloc(strlen(p)+1);
else *(c+j)=(char*)malloc(N+1);
}
strcat(*(c+j), p);
c[j][t]=' ';
p = strtok(NULL, " ");
t=t+strlen(p)+1;
}
c[j][t]='\0';
for(j=0; j<ks; j++)
{
printf("\n %s", *(c+j));
}
}
int main(void)
{
FILE *fin;
int n, ks;
char s1[2048], filename[256];
char **c;
printf("Enter the file name->");
scanf("%s", filename);
fin=fopen(filename,"r");
if (!fin)
{
printf ("Error\n");
return -1;
}
while (fscanf(fin, "%[^\n]", s1)==1)
{
fscanf(fin, "%*[ \n]");
printf("\n String: %s \n", s1);
n=strlen(s1);
ks=n/(N-1)+1;
c=(char **)malloc(ks*sizeof(char*));
rez(c, s1, n, ks);
}
fclose(fin);
return 0;
}
This code should cut long strings into some shorter, but it gives "core dumped" in gcc. It doesn't exit from while in void rez().
In my mind, strtok() works incorrectly.
This is wrong:
char r[1]=" ";
because the string literal " " is TWO characters! It is both a space and a NULL-terminator (which is at the end of every string in C. But you explicitly said it should only be a 1 character array.
I am having a few issues with my code. First: when I try to compile, I get error: too few arguments to function 'strcmp'. I have looked all over and made multiple changes and am still unable to get it to work. Second: when my code does compile (if I remove the strcmp part), it will not complete the count functions correctly. Can anyone please assist? Thank you!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int count(char array[], int size);
int stringLen(char array[]);
int convert(char ch);
int value, n;
int main()
{
//char * str;
//char s;
char a[100];
char b[100];
char c[100];
int charCount = stringLen(a);
int lCount = count(a, charCount);
printf("Enter your string: \n");
scanf("%s \n", a);
printf("Enter your string: \n");
scanf("%s \n", b);
printf("Enter your string: \n");
scanf("%s \n", c);
printf("The count is %d, length is %d\n", lCount, charCount);
int i;
for(i = 0; i < charCount; i++)
{
char c = a[i];
printf("Char %s = %d \n", &c, value);
}
n = strcmp(char string1[], char string2[], char string3[]);
printf("The first string in the alphabet is: %d \n", n);
return 0;
}
int stringLen(char array[])
{
char count;
int index;
while(array[index] !=0)
{
count++;
index++;
}
return count;
}
int count(char array[], int size)
{
int count;
int i;
for(i = 0; i < size; i++)
{
if(array[i] == 'a')
{
count ++;
}
else if(array[i] == 'A')
{
count ++;
}
}
return count;
}
This is not right way to use strcmp.
n = strcmp(char string1[], char string2[], char string3[]);
strcmp is used for compararison of string. See doc
int result = strcmp (string1,string2)
If strings are same, function will return 0.