In: Computer Science
This program works with strings complete the following functions to allow the program to function properly;
a) Write a C function int string_to_number(char *) that takes a string of decimal digits as an input parameter, and returns the integer value that the string represents. For example, if the char s[] ="256", then string_to_number(s) returns integer 256 (int data type). You are allowed to use strlen(…) function, but not allowed to use atoi and other functions. Ignore the negative sign and overall.
b) Write a C function void reverse(char *s) that takes a string as input, and reverses the order of its characters and stores in the string. For example, if string s is "abcd", after the function call, s becomes "dcba". You are allowed to use strlen(…) function.
c) Implement the above function without using strlen function. Just use pointer notation.
C CODE:
A.
#include
#include
int string_to_decimal(char *a,int n){
int i,k=0;
for(i=0;a[i]!='\0';i++){
//logic for converting string to
int
k=k*10+a[i]-'0';
}
return k;
}
int main(){
int n;
printf("Enter the length of string\n");
scanf("%d",&n);
printf("Enter the string of length %d \n",n);
char s[n];
scanf("%s",&s);
int res=string_to_decimal(s,strlen(s));
printf("Number changed to int is %d",res);
//printf("%d",res);
}
SCREENSHOT OF THE CODE AND OUTPUT:
B.
#include
#include
void reverse(char *s){
int n,low,high;
n=strlen(s);
high=n-1;
char k[50];
for(low=0;s[low]!='\0';low++){
k[low]=s[high];//copying into new
string
high--;
}
k[low]='\0';
printf("Reversed string is %s",k);
}
int main(){
printf("Enter the string\n");
char s[50];
scanf("%s",&s);//taking input
//calling reverse function
reverse(s);
}
SCREENSHOT OF THE CODE AND OUTPUT:
C.
#include
#include
int fun(char *s)
{
int i = 0;
while( *(s+i) != '\0' )
{
i++;}
return i;
}
void reverse(char *s)
{
int n, i;
char *low, *high, temp;
n= fun(s);
low = s;
high = s;
for (i = 0; i < n - 1; i++)
{
high++;}
for (i = 0; i < n/2; i++)
{
temp = *high;//storing anf swapping
*high = *low;
*low= temp;
low++;
high--;
}
}
int main(){
printf("Enter the string\n");
char s[50];
scanf("%s",&s);//taking input
//calling reverse function
reverse(s);
printf("Reversed string is %s",s);
}
SCREENSHOT OF THE CODE AND OUTPUT: