QUESTION-24 Converting an Integer to String & vice-versa

Answer-
 
void tostring(char [], int);
int toint(char []);
 
int main()
{
    char str[10];
    int num, result;
 
    printf("Enter a number: ");
    scanf("%d", &num);
    tostring(str, num);
    printf("Number converted to string: %s\n", str);
    result = toint(str);
    printf("Number converted back to integer: %d\n", result);
 
    return 0;
}
 
void tostring(char str[], int num)
{
    int i, rem, len = 0, n;
 
    n = num;
    while (n != 0)
    {
        len++;
        n /= 10;
    }
    for (i = 0; i < len; i++)
    {
        rem = num % 10;
        num = num / 10;
        str[len - (i + 1)] = rem + '0';
    }
    str[len] = '\0';
}
 
int toint(char str[])
{
    int len = strlen(str);
    int i, num = 0;
 
    for (i = 0; i < len; i++)
    {
        num = num + ((str[len - (i + 1)] - '0') * pow(10, i));
    }
 
   return num;
}

 

QUESTION-25 Find the Sum of ASCII values of All Characters in a given String

Answer-
void main()
{
    int sum = 0, i, len;
    char string1[100];
 
    printf("Enter the string : ");
    scanf("%[^\n]s", string1);
        len = strlen(string1);
    for (i = 0; i < len; i++)
    {
        sum = sum + string1[i];
    }
    printf("\n Sum of all characters : %d ",sum);
}

 

QUESTION-26 Find length of a string

Answer-
  
#define MAX_SIZE 100 // Maximum size of the string

int main()
{
    char text[MAX_SIZE]; /* Declares a string of size 100 */
    int i;
    int count= 0;
    
    printf("Enter any string: ");
    gets(text);

    for(i=0; text[i]!='\0'; i++)
    {
        count++;
    }

    printf("Length of '%s' = %d", text, count);

    return 0;
}

 

QUESTION-27 Toggle case of each character in a string

Answer-
#define MAX_SIZE 100 // Maximum string size

void toggleCase(char * str);


int main()
{
    char str[MAX_SIZE];

    printf("Enter any string: ");
    gets(str);

    printf("String before toggling case: %s", str);

    toggleCase(str);

    printf("String after toggling case: %s", str);

    return 0;
}

void toggleCase(char * str)
{
    int i = 0;

    while(str[i] != '\0')
    {
        if(str[i]>='a' && str[i]<='z') { str[i] = str[i] - 32; } else if(str[i]>='A' && str[i]<='Z')
        {
            str[i] = str[i] + 32;
        }

        i++;
    }
}