Hmm need some help trying to terminate the loop. Basically I want to receive a set of 2 integers, so when the user wants to terminate he/she should just enter nothing and press another enter.
So for example, input would be:
5 50
7 70
<enter> (this should terminate the input process and it should process the data)
Any input would be appreciated - my C may be a bit rusty since I haven't coded in a while so bare with it
Here's what I got so far:
Code:
/* The 3n+1 Problem */
#include <stdio.h>
/* Gets the cycle length for an input n */
int get_cycle_length(int n);
/* Returns the maximum cycle length between i and j */
int maximum_cycle_length(int i, int j);
struct node* insert_data(struct node**, int, int);
void print_list(struct node*);
/* Structure for storing info */
struct node {
int i;
int j;
int result;
struct node *next;
};
int main(int argc, char **argv)
{
int i, j, k=0, res=0;
int max_cycle = 0;
struct node* empty = NULL;
while(1){
if (scanf("%d %d",&i, &j) != 2)
{
/* Checking Exceptions here */
/* Need help here!! */
if ((k = getchar()) == '\n')
break;
break;
} else
{
insert_data(&empty,i,j);
}
}
print_list(empty);
printf("\n");
return 0;
}
int get_cycle_length(int n)
{
int cycles = 0;
/* Implement algorithm */
while (n != 1)
{
if (n % 2 == 0){
n /= 2;
} else {
n = 3*n + 1;
}
cycles++;
}
cycles++;
return cycles;
}
int maximum_cycle_length(int i, int j)
{
int k, res, max_cycle = 0;
for (k = i; k <= j; k++)
{
res = get_cycle_length(k);
if (res >= max_cycle)
max_cycle = res;
}
return max_cycle;
}
struct node* insert_data(struct node** list, int i, int j)
{
if (*list == NULL)
{
*list = malloc(sizeof(struct node));
(*list)->i = i;
(*list)->j = j;
(*list)->result = maximum_cycle_length(i,j);
(*list)->next = NULL;
}
else
{
/* Traverse until reach insertion point */
struct node* current = *list;
while (current->next != NULL)
{
current = current->next;
}
struct node *new = (struct node*)malloc(sizeof(struct node));
new->i = i;
new->j = j;
new->result = maximum_cycle_length(i, j);
new->next = NULL;
current->next = new;
}
/* Finish up by returning head */
return *list;
}
void print_list(struct node* list)
{
if (list == NULL)
{
printf("Empty list - nothing printed\n");
return;
} else {
while (list != NULL){
printf("%d %d %d",list->i, list->j, list->result);
printf("\n");
list = list->next;
}
}
return;
}