Saturday 11 November 2017

C Program to Input a String with atleast one Number, Print the Square of all the Numbers in a String


Code:

#include  stdio.h>
#include  string.h>
#include  ctype.h>
#include  math.h>

struct detail
{
    int number;
    int square;
};

int update(struct detail [], int, int);
int toint(char []);

int main()
{
    struct detail s[10];
    char unit[20], string[100];
    char c;
    int num, i, j = 0, count = 0;

    printf("Enter string: ");
    i = 0;
    do
    {
        fflush(stdin);
        c = getchar();
        string[i++] = c;

    } while (c != '\n');
    string[i - 1] = '\0';
    printf("The string entered is: %s\n", string);
    for (i = 0; i < strlen(string); i++)
    {
        while (i < strlen(string) && !isspace(string[i]))
        {
            unit[j++] = string[i++];
        }
        if (j != 0)
        {
            unit[j] = '\0';
            num = toint(unit);
            count = update(s, num, count);
            j = 0;
        }
    }
    printf("*****************\nNumber\tSquare\n*****************\n");
    for (i = 0; i < count; i++)
    {
        printf("%d\t   %d\n", s[i].number, s[i].square);
    }

    return 0;
}

int update(struct detail s[], int num, int count)
{
    s[count].number = num;
    s[count].square = num * num;

    return (count + 1);
}

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

Output:

Enter string: 1 2 3 4 5
The string entered is: 1 2 3 4 5
*****************
Number Square
*****************
1    1
2    4
3    9
4    16
5    25


More C Programs:














100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...