Hello All,
I've spent a ton of time on this code and am all of a sudden having a strange occurrence. While executing the case1 in my switch, it blasts through without accepting the user keyboard input and just runs the whole code. I put this section of code (the case 1) in it's own separate *.c file and it executed perfectly. Any help is greatly appreciated!
Thanks,
Dan
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <math.h>
long int factorial(int n_end);
void clear_message(char* input);
int main()
{
int menu, i, j, n, n_end;
double y, x, exp, sum, sum_2;
char message[111]={'\0'};
printf("\nHomework 4:\n\n");
printf("There are two parts: part 1 and part 2.\n");
printf("Enter the part number to execute (1 or 2):");
scanf("%d", &n);
switch(n){
case 1:
printf("\nPart I:\n\n");
printf("Enter your message:");
fgets(message, 111, stdin);
printf("\nYour message is: %s\n\n", message);
clear_message(message);
int length=strlen(message);
char* reverse = (char*) malloc(length + 1);
for(i=0,j=length-1;j>=0;--j,++i)
{
reverse[i] = message[j];
}
reverse[i] = '\0';
printf("Reversed String is: %s\n\n", reverse);
break;
case 2:
printf("\nPart II:\n\n");
printf("Series evaluation: x^n/n! from n=0 to n=n_end.\n");
printf("\n");
printf("Enter x, a real number, and n_end, a large positive interger.\n");
scanf("%g %d", &x, &n_end);
printf("\nThe values entered are: x = %g and n_end = %4d.\n\n", x, n_end);
for (n=0, sum=0.0;n<n_end;n++){
sum = sum + (pow(x,n)/(factorial(n)));
}
printf("The sum of %d terms of %g^%d/%d! is %g.\n", n_end, x, n_end,n_end, sum);
exp = pow(2.718281828,x);
printf("The true value for exp(%g) is %16.8e.\n", x, exp);
break;
default:
printf("part %d does not exist.\n", menu);
}
printf("\n");
exit(0);// optional
}
long int factorial(int n_end)
{
if (n_end<=1)
return(1);
else
n_end=n_end*factorial(n_end-1);
return(n_end);
}
void clear_message(char* input)
{
char* k=0;
if(k=strrchr(input, '\n'))
*k='\0';
}
The instructions were to accept user inputted message, redisplay message then reverse letters and words. This is all done in C.