Showing posts with label Programming. Show all posts

Monday, February 16, 2015

C Programming: Non-recursive and Recursive Programs for Getting the Factorial of a Number

No comments :
Here are programs that compute for the factorial of a number both non-recursively and recursively.

Here is the non-recursive way:

Non-recursive Factorial Output

 #include<stdio.h>  
   
 int factorial(int num)  
 {  
      int i;  
        
      for(i=num-1;i>1;i--)  
      {  
           num=num*i;  
      }  
      return num;  
 }  
   
 main()  
 {  
      int num,ans;  
        
      clrscr();  
      printf("Non-recursive\n\n");  
      printf("Enter number: ");  
      scanf("%d",&num);  
      ans=factorial(num);  
      printf("The factorial of %d is %d.",num,ans);  
      getch();  
 }  

Here is the recursive way:
Recursive Factorial Output

 #include<stdio.h>  
   
 int factorial(int num)  
 {  
      if(num==1) //We don't have to multiply the number by 1 since it will just be the same number  
      {  
           return 1;  
      }  
      else  
      {  
           num=num*factorial(num-1);  
           return num;  
      }  
 }  
   
 main()  
 {  
      int num,ans;  
        
      clrscr();  
      printf("Recursive\n\n");  
      printf("Enter number: ");  
      scanf("%d",&num);  
      ans=factorial(num);  
      printf("The factorial of %d is %d.",num,ans);  
      getch();  
 }   

If you have questions on these, place a comment below.

Friday, February 6, 2015

C Programming: Stacking with a Singly Linked List of Nested Structures (2 Structures)

No comments :
This is a program that stacks (push) values to a certain range indicated by the user.
Will include an image of the visualization soon, as well as code comments... (updated)

Stack, Singly Linked List, Nested Structures


Program code:
 #include<stdio.h>  
   
 struct stack  
 {  
      int data;  
      struct stack *next;  
 };  
   
 struct range  
 {  
      int rangel, rangeh;  
      struct range *next;  
      struct stack *up;  
 }*range_start=NULL;  
   
 void display(int limit)  
 {  
      struct range *current;  
      int i,j,x=1,y=limit+2,ry=limit+2,ly=0;  
      current=range_start;  
        
      while(current!=NULL)  
      {  
           if(x>=80)  
           {  
                ly=y+1;  
                y=y+((limit+2)+1);  
                x=1;  
                ry=y;  
           }  
           if(ly+limit>=24)  
           {  
                gotoxy(1,25);  
                printf("press any key to continue...");  
                getch();  
                clrscr();  
                x=1;  
                y=limit+2;  
                ry=limit+2;  
                ly=0;  
           }  
           if(x==1)  
           {  
                for(i=1+ly;i<=y;i++)  
                {  
                     gotoxy(1,i);  
                     printf("|");  
                }  
           }  
           gotoxy(x+1,y);  
           if(current->rangel<10&&current->rangeh>9)  
           {  
                printf(" 0%d-%d",current->rangel,current->rangeh);  
           }  
           else if(current->rangeh<10)  
           {  
                printf(" 0%d-0%d",current->rangel,current->rangeh);  
           }  
           else  
           {  
                printf(" %d-%d",current->rangel,current->rangeh);  
           }  
           x=x+4;  
           for(j=x,i=1;i<8;i++,j++)  
           {  
                gotoxy(j-3,y-1);  
                printf("-");  
           }  
           y=y-1;  
           while(current->up!=NULL)  
           {  
                y=y-1;  
                gotoxy(x,y);  
                printf("%d",current->up->data);  
                current->up=current->up->next;  
           }  
           x=x+4;  
           y=ry;  
           current=current->next;  
      }  
 }  
   
 void insertRange(int rangel, int rangeh)  
 {  
      struct range *new_node,*current;  
        
      if(range_start==NULL)  
      {  
           new_node=(struct range *)malloc(sizeof(struct range));  
           new_node->rangel=rangel;  
           new_node->rangeh=rangeh;  
           new_node->up=NULL;  
           new_node->next=NULL;  
           range_start=new_node;  
           current=new_node;  
      }  
      else  
      {  
           current=range_start;  
           while(current->next!=NULL)  
           {  
                current=current->next;  
           }  
           new_node=(struct range *)malloc(sizeof(struct range));  
           new_node->rangel=rangel;  
           new_node->rangeh=rangeh;  
           new_node->up=NULL;  
           new_node->next=NULL;  
           current->next=new_node;  
           current=new_node;  
      }  
 }  
   
 void insertStackData(int data)  
 {  
      struct range *current;  
      struct stack *new_node,*c;  
      current=range_start;  
        
      /*find range*/  
      while(current!=NULL)  
      {  
           if(data>=current->rangel&&data<=current->rangeh)  
           {  
                /*insert data to stack*/  
                if(current->up==NULL)  
                {  
                     new_node=(struct stack *)malloc(sizeof(struct stack));  
                     new_node->data=data;  
                     new_node->next=NULL;  
                     current->up=new_node;  
                     break;  
                }  
                else  
                {  
                     c=current->up;  
                     while(c->next!=NULL)  
                     {  
                          c=c->next;  
                     }  
                     new_node=(struct stack *)malloc(sizeof(struct stack));  
                     new_node->data=data;  
                     new_node->next=NULL;  
                     c->next=new_node;  
                     break;  
                }  
           }  
           current=current->next;  
      }  
 }  
   
 void stack(int limit,int size)  
 {  
      int i=0,rangel=0,rangeh=size-1;  
      int data;  
        
      clrscr();  
        
      /*inserting to node*/  
      while(rangel<100)  
      {  
           if(rangeh>99)  
           {  
                rangeh=99;  
           }  
           insertRange(rangel,rangeh);  
           rangel=rangeh+1;  
           rangeh=rangeh+size;  
      }  
        
      clrscr();  
        
      while(i<limit)  
      {  
           printf("Enter value %d: ",i+1);  
           scanf("%d",&data);  
           if(data>=0&&data<=99)  
           {  
                insertStackData(data);  
                i++;  
           }  
           else  
           {  
                printf("Invalid input! Enter a value from 0-99\n");  
           }  
      }  
      clrscr();  
      display(limit);  
 }  
   
 void freeAllNodes()  
 {  
      free(range_start);  
 }  
   
 int getLimit()  
 {  
      int limit;  
      while(1)  
      {  
           printf("Enter number of inputs: ");  
           scanf("%d",&limit);  
           if(limit<0)  
           {  
                printf(" -Size cannot be lesser than zero!\n");  
           }  
           else  
           {  
                break;  
           }  
      }  
        
      return limit;  
 }  
   
 int getSize()  
 {  
      int size;  
        
      while(1)  
      {  
           printf("Enter size/range: ");  
           scanf("%d",&size);  
           if(size<1)  
           {  
                printf(" -Size cannot be equal to/lesser than 0!\n");  
           }  
           else if(size>99)  
           {  
                printf(" -Size cannot be equal to/greater than 100!\n");  
           }  
           else  
           {  
                break;  
           }  
      }  
        
      return size;  
 }  
   
 main()  
 {  
      int limit,size;  
      char choice=NULL;  
      clrscr();  
        
      while(1)  
      {  
           limit=getLimit();  
           size=getSize();  
           stack(limit,size);  
             
           while(choice!='Y'||choice!='y'||choice!='N'||choice!='n')  
           {  
                gotoxy(1,25);  
                printf("Again [y/n]? ");  
                choice=getche();  
                switch(choice)  
                {  
                     case 'Y': //same with case 'y'  
                     case 'y': /*free all nodes*/  
                               freeAllNodes();  
                               clrscr();  
                               limit=getLimit();  
                               size=getSize();  
                               stack(limit,size);  
                               break;  
                     case 'N': //same with case 'n'
                     case 'n': //PROGRAM EXIT  
                               exit(1);  
                               break;  
                     default:  
                               gotoxy(1,25);  
                               printf("Invalid input! press any key....");  
                               getch();  
                               gotoxy(14,25);  
                               printf("\t\t\t\t");  
                               break;  
                }  
           }  
      }  
 }  

If you have any question, place a comment below.

Monday, January 26, 2015

C Programming: Inserting at Start and End of a Singly Linked List and Displaying the List

No comments :
Here is a program which inserts at the start and end of a Singly Linked List, as well as, display the list from start to end.

Program output


The program consists of 4 functions:
1. insertEnd(int data): void
   -This function inserts the data entered by the user at the end of the list

2. insertStart(int data): void
   -This function inserts the data entered by the user at the start of the list

3. display(): void
   -This function displays all the data entered by the user from start to end

4. main()
   -Well, this is our main function.

Here are the codes.

 struct node  
 {  
      int data; /*the data*/  
      struct node *next; /*This is a structure within a structure.*/  
 }*start=NULL,*end=NULL; /*We instantiate var start and end with NULL since there is no node yet*/  
   
 void insertEnd(int data)  
 {  
      /*new_node is the new node we create each time this function is called.  
       current is for keeping track of the current node we are dealing with.*/  
      struct node *new_node,*current;  
        
      if(end==NULL) /*if the list is empty*/  
      {  
           /*printing something to indicate that there is no node yet. This is useful for debugging.*/  
           printf("no nodes. creating starting node for %d...\npress any key...",data);  
           getch();  
             
           /*Here, we allocate memory space for the variable new_node of type node.*/  
           new_node=(struct node *)malloc(sizeof(struct node));  
           /*We store the passed value of data to the variable data inside new_node.*/  
           new_node->data=data;  
           /*We instantiate the variable next inside new_node with NULL because there is nothing next  
            to this current node*/  
           new_node->next=NULL;  
           /*Since this is the first and only node being created, we will store this node to the  
            variable start and end*/  
           start=new_node;  
           end=start;  
           /*new_node is the current node we are dealing with.*/  
           current=new_node;  
      }  
      else /*If the list is not empty, we will go through the list until the end and add a new node  
            there.*/  
      {  
           current=start; /*let's start from the start*/  
           while(1) /*an infinite loop*/  
           {  
                if(current->next!=NULL) /*if this current node is not the end of the list,*/  
                {  
                     current=current->next; /*we will look at the next one*/  
                } /*until there is none next*/  
                else  
                {  
                     printf("nodes exist. creating new node for %d...\npress any key...",data);  
                     getch();  
                     new_node=(struct node *)malloc(sizeof(struct node));  
                     new_node->data=data;  
                     new_node->next=NULL;  
                     end=new_node; /*this is the last in the list, thus, we store this to var end*/  
                     current->next=new_node; /*this is next to the current node*/  
                     current=new_node; /*then, this will be our current node*/  
                     break; /*we'll break the infinity loop here*/  
                }  
           }  
      }  
      printf(" done\n"); /*printing something to indicate we are done inserting*/  
 }  
   
 void insertStart(int data)  
 {  
      /*We don't need a current variable of type node in this function since, we don't need to  
       traverse through the list.*/  
      struct node *new_node;  
        
      if(end==NULL) /*This is just the same with the creation of the first node in the insertEnd  
                      function above except that we don't have the variable current*/  
      {  
           printf("no nodes. creating starting node for %d...\npress any key...",data);  
           new_node=(struct node *)malloc(sizeof(struct node));  
           new_node->data=data;  
           new_node->next=NULL;  
           start=new_node;  
           end=start;  
      }  
      else  
      {  
           printf("nodes exist. creating a new node for %d...\npress any key...",data);  
           getch();  
           new_node=(struct node *)malloc(sizeof(struct node));  
           new_node->data=data;  
           new_node->next=start; /*since we are inserting at the start of the list, this new node will  
                                 be ahead of the starting node. In other words, start will be next  
                                 to this in the list.*/ 
           start=new_node; /*...and the starting node will, now, be this new node we are creating*/ 
      }  
      printf("done");  
 }  
   
 void display()  
 {  
      struct node *current; /*Here, we are only using the variable current to traverse through the  
                            list*/ 
      current=start; /*Let's start from the start of the list to the user*/ 
      printf("\nList:\n\nStart-->"); /*indicating the start of the list*/ 
      while(current!=NULL) /*while this current node is not the end of the list, (next to the end of  
                            the list is NULL)*/ 
      {  
           printf("%d-->",current->data); /*printing the data*/ 
           current=current->next; /*let's go to the next node*/ 
      }  
      printf("End\n\npress any key..."); /*indicating the end of the list to the user*/ 
      getch();  
 }  
   
 main()  
 {  
      /*This is easy right here. If you have any question in this part, though, just place a comment  
       below*/ 
      int data,pos,choice;  
        
      while(1)  
      {  
           clrscr();  
           printf("[1] Insert at End\n[2] Insert at Start\n[3] Display Linked List\n[4] Exit\nChoice: ");  
           scanf("%d",&choice);  
           switch(choice)  
           {  
                case 1:  
                     clrscr();  
                     printf("Inserting at End...\n\nEnter data: ");  
                     scanf("%d",&data);  
                     insertEnd(data);  
                     break;  
                case 2:  
                     clrscr();  
                     printf("Inserting at Start...\n\nEnter data: ");  
                     scanf("%d",&data);  
                     insertStart(data);  
                     break;  
                case 3:  
                     display();  
                     break;  
                case 4:  
                     exit(1);  
                     break;  
                default:  
                     printf("\nPlease choose one operation from the menu.")  
                     break;  
           }  
      }  
 }  


You may use this or any part of this program for noncommercial use, i.e. your assignments, projects, teaching programs.


If you have questions/suggestions, quickly place a comment below.

Tuesday, January 20, 2015

Java Programming: Program that adds two (2) floats

No comments :
Here is a program that adds two (2) floats. The program only accepts numbers. It keeps asking for input until a number is entered. The function add(float addend1, float addend2) returns the result in float.

Program output


code:
 import java.util.Scanner;  
   
 /**  
  *  
  * @author Engineering Problems and Answers (http://engineeringproblemsandanswers.blogspot.com)  
  */  
 public class main {  
        
      public static void main(String[] args) {  
             
           float addend1, addend2, result; //declare addends and result variables  
           Scanner sc = new Scanner(System.in); //initialize scanner  
             
           System.out.print("Enter 1st addend: "); //ask for the 1st number  
             
           //condition keep asking until a number is entered  
           while (!sc.hasNextFloat()) {  
                System.out.print("Enter 1st addend: ");  
                sc.next();  
           }  
           addend1 = sc.nextFloat(); //store the number here  
             
           System.out.print("Enter 2nd addend: "); //ask for the 2nd number  
             
           //condition to keep asking until a number is entered  
           while (!sc.hasNextFloat()) {  
                System.out.print("Enter 2nd addend: ");  
                sc.next();  
           }  
           addend2 = sc.nextFloat(); //store the number here  
             
           result = add(addend1, addend2); /*call add method and store result to variable  
                                           result(float)*/  
             
           System.out.println("\nNon-formatted print:");  
           System.out.println(addend1+" + "+addend2+" = "+result); /*here, result value is not  
                                                                   accurate*/  
           System.out.println("\nFormatted print:");  
           System.out.printf("%.2f + %.2f = %.2f", addend1, addend2, result); /*format to decimal  
                                                                              places (result is  
                                                                              rounded off) in order  
                                                                              to get a more accurate  
                                                                              result value*/  
      }  
        
      private static float add(float addend1, float addend2) {  
           return addend1 + addend2; //return the sum of the two numbers  
      }  
 }  

When operating on floats, the computer, sometimes, doesn't give the right answer. The computer isn't actually wrong. Read the explanation HERE. We can format the answer we print as a workaround for this (see code lines 38 to 43).

You may use this or any part of this program for noncommercial use, i.e. your assignments, projects, teaching programs.

If you have questions/suggestions, quickly place a comment below.