COBOL SAMPLE PROGRAMS

cobol

WHY COBOL?

I seriously don’t know why or how I ended up learning COBOL. It is not so bad after all and thought I’ll share few of the programs when I began learning. Tutorials point is one amazing place to try out COBOL programs in real time. Of course, JCL’s cant be tried as you need an actual mainframe. I’m not too sure how the current free emulators for mainframe works. I had a tough-luck find one that’s actually working.

 

I shall also try sharing a more advanced programs. Watch out in this space.

Here are the few programs for a head start. Cheers.

 1. COMPILER CODE
/*
* COBOL COMPILER SAMPLE
* Example 1 - 
* 
* by surender, www.suren.space
* 


//WPR020A JOB SUREN,SUREN,CLASS=A,NOTIFY=&SYSUID
//MYLIB JCLLIB ORDER=WPRADM.WIP.COMPILER
//STEP1 EXEC PROC=COBCL,
//           SRCLIB=WPR020.SEP18.COBOLPGM,
//           MEMBER=PRG1,
//           LOADLIB=WPR020.SEP18.$LOADLIB,
//           COPYLIB=WPR020.SEP18.COBOLPGM


* COBOL HELLO WORLD
* Example 1 - 
* 
* by surender, www.suren.space
* 


        IDENTIFICATION DIVISION.                
        PROGRAM-ID. PRG1.                       
        ENVIRONMENT DIVISION.                   
        DATA DIVISION.                          
        PROCEDURE DIVISION.                     
               DISPLAY "HELLO WORLD!".          
               STOP RUN.               

* PRG2 Write a program to accept the string from user and to display the same.     

* Example 2 - 
* 
* by surender, www.suren.space
* 
        IDENTIFICATION DIVISION.                        
        PROGRAM-ID. PRG2.                               
        ENVIRONMENT DIVISION.                           
        DATA DIVISION.                                  
        WORKING-STORAGE SECTION.                        
        77 USERINP PIC A(10).                           
        PROCEDURE DIVISION.                             
               ACCEPT USERINP.                          
               DISPLAY "USER INPUT IS:" USERINP.        
               DISPLAY "HELLO WORLD!".                  
               STOP RUN.              


/*
* COBOL COMPILER SAMPLE
* Example 3 - PRG3 Write a program to accept the 2 nos. from user and display the same.    

* 
* by surender, www.suren.space
* 

       IDENTIFICATION DIVISION.              
       PROGRAM-ID. PRG3.                     
       ENVIRONMENT DIVISION.                 
       DATA DIVISION.                        
       WORKING-STORAGE SECTION.              
       77 NUM1 PIC 9(2).                     
       77 NUM2 PIC 9(2).                     
       PROCEDURE DIVISION.                   
           ACCEPT NUM1.                      
           ACCEPT NUM2.                      
           DISPLAY NUM1.                     
           DISPLAY NUM2.                     
           STOP RUN.                         


/*
* COBOL COMPILER SAMPLE
* Example 4 - 
* 
* by surender, www.suren.space
* 
PRG4 Write a program to accept the student record (ROLL NO, NAME and 3 subject marks) individually and display the same. Also accept as a group and display individually. 

        IDENTIFICATION DIVISION.                     
        PROGRAM-ID. PRG4.                            
        ENVIRONMENT DIVISION.                        
        DATA DIVISION.                               
        WORKING-STORAGE SECTION.                     
        01 G1.                                       
            02 ROLLNO PIC 9(3).                      
            02 FILLER PIC X.                         
            02 STUNAME PIC A(8).                     
            02 FILLER PIC X.                         
            02 MARK1 PIC 9(3).                       
            02 FILLER PIC X.                         
            02 MARK2 PIC 9(3).                       
            02 FILLER PIC X.                         
            02 MARK3 PIC 9(3).       
       PROCEDURE DIVISION.          
           ACCEPT G1.               
           DISPLAY G1               
           STOP RUN.                

/*
* COBOL COMPILER SAMPLE
* Example 5 - 
* 
* by surender, www.suren.space
* 
PRG5 Write  a program to accept the date and time from system and display in the given format( USING MOVE CORRESPONDING and FILLER)  DD/MM/YYYY & HH:MM:SS.    
  
        IDENTIFICATION DIVISION.                   
        PROGRAM-ID. PRG5.                          
        ENVIRONMENT DIVISION.                      
        DATA DIVISION.                             
        WORKING-STORAGE SECTION.                   
        01 G1.                                     
           02 YY PIC X(2).                         
           02 MM PIC X(2).                         
           02 DD PIC X(2).                         
        01 G2.                                     
           02 DD PIC X(2).                         
           02 FILLER PIC X VALUE '-'.              
           02 MM PIC X(2).                  
           02 FILLER PIC X VALUE ‘-‘.     
           02 YY PIC X(2).                     
        01 G3.                                 
           02 HH PIC X(2).                     
           02 MM PIC X(2).                     
           02 SS PIC X(2).                     
        01 G4.                                 
           02 HH PIC X(2).                     
           02 FILLER PIC X VALUE ':'.          
           02 MM PIC X(2).                     
           02 FILLER PIC X VALUE ':'.          
           02 SS PIC X(2).                     
        PROCEDURE DIVISION.                    
               ACCEPT G1 FROM DATE.            
               ACCEPT G3 FROM TIME.            
               MOVE CORRESPONDING G1 TO G2.    
               MOVE CORRESPONDING G3 TO G4.    
               DISPLAY G2.                   
               DISPLAY G4.                   
               STOP RUN. 


* Example 6 - 
* 
* by surender, www.suren.space
* 
PRG6 Write a program to illustrate data movement in the variable ( Justification, Truncation and zero padding ) ( USING Value CLAUSE and MOVE statement)  ( Hint : Declare the Variables  with 9(5) and X(10)  and pass the value with lesser size and more size both in Value CLAUSE and MOVE statement)  Also try this with Accept and SYSIN.  

       IDENTIFICATION DIVISION.                        
       PROGRAM-ID. PRG6.                               
       ENVIRONMENT DIVISION.                           
       DATA DIVISION.                                  
       WORKING-STORAGE SECTION.                        
       77 EMPID PIC 9(5) VALUE 3454.                   
       77 EMPID2 PIC 9(5).                             
       77 ALPNUM PIC X(10) VALUE 'ABC123'.             
       PROCEDURE DIVISION.                             
           MOVE EMPID TO EMPID2.                       
           DISPLAY EMPID.                              
           DISPLAY EMPID2.                             
           DISPLAY ALPNUM.                             
           STOP RUN.                                


/*
* Example 7 - 
* 
* by surender, www.suren.space
* 
PRG7 Write a program to work with Decimal Nos. ( ACCEPT , VALUE and MOVE)  ( Hint: Declare a variable for decimal value and accept the value  from SYSIN , MOVE and VALUE clause and Display the same) .

       IDENTIFICATION DIVISION.               
       PROGRAM-ID. PRG7.                      
       ENVIRONMENT DIVISION.                  
       DATA DIVISION.                         
       WORKING-STORAGE SECTION.               
       77 TEMP PIC 9(2)V9(2).                 
       PROCEDURE DIVISION.                    
           ACCEPT TEMP.                       
           DISPLAY TEMP.                      
           STOP RUN.       



* Example 8 - 
* 
* by surender, www.suren.space
PRG8 Write a program for work with Signed Nos. (Accept, Value and Move statement). Also check the difference with Sign leading, Sign leading Separate.
      IDENTIFICATION DIVISION.                  
      PROGRAM-ID. PRG8.                         
      ENVIRONMENT DIVISION.                     
      DATA DIVISION.                            
      WORKING-STORAGE SECTION.                  
      77 TEMP PIC S9(4).                        
      PROCEDURE DIVISION.                       
          ACCEPT TEMP.                          
          DISPLAY TEMP.                         
          STOP RUN.                  



* Example 9 - 
* 
* by surender, www.suren.space
* 
PRG 9 Write a program to illustrate the Edit picture clause( Z, $,*,-, +,CR,DB, .(period) , ,(Comma) , Blank when zero). 

       IDENTIFICATION DIVISION.               
       PROGRAM-ID. PRG7.                      
       ENVIRONMENT DIVISION.                  
       DATA DIVISION.                         
       WORKING-STORAGE SECTION.               
       01 G1.                                 
           02 NUM1 PIC ZZ99.                  
           02 NUM2 PIC **99.                  
           02 NUM3 PIC ZZ99.99.               
           02 NUM4 PIC $$$.99.                
           02 NUM5 PIC -999.                  
           02 NUM6 PIC +999.                  
           02 NUM7 PIC 99CR.                  
       PROCEDURE DIVISION.                  


/*

* Example 10 - 
* 
* by surender, www.suren.space
* 
PRG 10 Write a program to implement the usage of COMP variables. Move some Alphanumeric value in Comp variable and also do some Arithmetic operation on COMP variables with Alphanumeric and Find the result.

       IDENTIFICATION DIVISION.                                     
       PROGRAM-ID. PRG10.                                           
       ENVIRONMENT DIVISION.                                        
       DATA DIVISION.                                               
       WORKING-STORAGE SECTION.                                     
       77 NUM1       PIC 9(4) USAGE IS COMP VALUE 0045.             
       77 NUM2       PIC 9(4) USAGE IS COMP VALUE 0045.             
       77 TOTAL      PIC 9(5) USAGE IS COMP.                        
       PROCEDURE DIVISION.                                          
           COMPUTE TOTAL = NUM1 + NUM2.                             
           DISPLAY TOTAL.                                           
           STOP RUN.               



* Example 11 - 
* 
* by surender, www.suren.space
* 
PRG 11 Write a program to perform the arithmetic operations using Arithmetic Verbs. (Workout with Integer Nos, Decimal Nos and Signed Nos).

      IDENTIFICATION DIVISION.                             
      PROGRAM-ID. PRG10.                                   
      ENVIRONMENT DIVISION.                                
      DATA DIVISION.                                       
      WORKING-STORAGE SECTION.                             
      77 NUM1       PIC 9(4).                              
      77 NUM2       PIC 9(4).                              
      77 TOTAL      PIC 9(5).                              
      PROCEDURE DIVISION.                                  
          ACCEPT NUM1.                                     
          ACCEPT NUM2.                                     
          ADD NUM1 TO NUM2 GIVING TOTAL.                   
          DISPLAY TOTAL.                                 
          SUBTRACT NUM1 FROM NUM2 GIVING TOTAL.          
          DISPLAY TOTAL.                                 
          MULTIPLY NUM1 BY NUM2 GIVING TOTAL.            
          DISPLAY TOTAL.                                 
          DIVIDE NUM1 BY NUM2 GIVING TOTAL.              
          DISPLAY TOTAL.                                 
          STOP RUN.                          



* Example 12 - 
* 
* by surender, www.suren.space
* 
PRG 12 Write a program for the following requirement:

WS-A  99v999 value 23.678
WS-B 99V999 value 29.459
WS-TOT 99v9  

Added value of WS-A and WS-B is stored in WS-TOT .  (Handle the overflow/truncation of the data )

       IDENTIFICATION DIVISION.                                     
       PROGRAM-ID. PRG10.                                           
       ENVIRONMENT DIVISION.                                        
       DATA DIVISION.                                               
       WORKING-STORAGE SECTION.                                     
       77 WS-A       PIC 99V999 VALUE 23.678.                       
       77 WS-B       PIC 99V999 VALUE 29.459.                       
       77 WS-TOT     PIC 99V9.                                      
       PROCEDURE DIVISION.                                          
           COMPUTE WS-TOT = WS-A + WS-B.                            
           DISPLAY WS-TOT.                                          
           STOP RUN.                                



* Example 13 - 
* 
* by surender, www.suren.space
* 
PRG 13 Write a program for the above data to stored rounded values in WS-TOT.

       IDENTIFICATION DIVISION.                                     
       PROGRAM-ID. PRG10.                                           
       ENVIRONMENT DIVISION.                                        
       DATA DIVISION.                                               
       WORKING-STORAGE SECTION.                                     
       77 WS-A       PIC 99V999 VALUE 23.678.                       
       77 WS-B       PIC 99V999 VALUE 29.459.                       
       77 WS-TOT     PIC 99V9.                                      
       PROCEDURE DIVISION.                                          
           COMPUTE WS-TOT ROUNDED = WS-A + WS-B.                    
           DISPLAY WS-TOT.                                          
           STOP RUN.          



/*
* Example 14 - 
* 
* by surender, www.suren.space
* 
PRG 14 Write a program to convert the Celsius to Fahrenheit using compute statement(°C x 9/5 + 32 = °F ,   (°F - 32) x 5/9 = °C )


       IDENTIFICATION DIVISION.                                        
       PROGRAM-ID. PRG14.                                              
       ENVIRONMENT DIVISION.                                           
       DATA DIVISION.                                                  
       WORKING-STORAGE SECTION.                                        
       77 CELCIUS       PIC 9(3).                                      
       77 FAHRENHEIT    PIC 999V999.                                   
       PROCEDURE DIVISION.                                             
           ACCEPT CELCIUS.                                             
           COMPUTE FAHRENHEIT = ( CELCIUS * ( 9 / 5 ) ) + 32.          
           DISPLAY FAHRENHEIT.                                         
           STOP RUN.         



/*

* Example 15 - 
* 
* by surender, www.suren.space
* 
PRG 15 Write a program to calculate the rate of interest using Compute statement( I=PNR/100)

       IDENTIFICATION DIVISION.                                  
       PROGRAM-ID. PRG14.                                        
       ENVIRONMENT DIVISION.                                     
       DATA DIVISION.                                            
       WORKING-STORAGE SECTION.                                  
       77 P       PIC 9(2).                                      
       77 R       PIC 9(2).                                      
       77 T       PIC 9(2).                                      
       77 I       PIC 9(4).                                      
       PROCEDURE DIVISION.                                       
           ACCEPT P.                                             
           ACCEPT R.                                             
           ACCEPT T.                                             
           COMPUTE I = ( P * R * R ) / 100                       
           DISPLAY "INTEREST IS:   " I                           
           STOP RUN.                                                                                                                         



/*
* Example 16 - 
* 
* by surender, www.suren.space
* 
PRG 16 Write a program to calculate the TOT, AVG and GRADE for the given student and display the same.( GRADE I for AVG >80 and PASS in all subject , GRADE II if AVG is 60 to 79 and all pass, Grade III , if AVG <60 and all pass, else GRADE is FAIL).        IDENTIFICATION DIVISION.                                     PROGRAM-ID. PRG7.                                            ENVIRONMENT DIVISION.                                        DATA DIVISION.                                               WORKING-STORAGE SECTION.                                     01 G1.                                                           02 MARK1 PIC 9(2).                                           02 FILLER PIC X.                                             02 MARK2 PIC 9(2).                                           02 FILLER PIC X.                                             02 MARK3 PIC 9(2).                                       77 TOTAL PIC 9(3).                                           77 AVG PIC 9(3)V9(3).                                        77 PER PIC 9(3)V9(3).                                      77 GRADE PIC A(5).                                         PROCEDURE DIVISION.                                        MAIN-PARA.                                                     PERFORM INPUT-PARA.                                        PERFORM COMP-PARA.                                         PERFORM DISP-PARA.                                         STOP RUN.                                              INPUT-PARA.                                                    ACCEPT G1.                                             COMP-PARA.                                                     COMPUTE TOTAL = ( MARK1  + MARK2 + MARK3 ).                COMPUTE AVG = TOTAL / 3.                                   COMPUTE PER = ( TOTAL / 300 ) * 100.                       IF AVG > 80                                    
              MOVE "I" TO GRADE                         
           ELSE                                         
              IF AVG > 60 AND AVG < 79                                    MOVE "II" TO GRADE                                    ELSE                                                        IF AVG > 40 AND AVG < 60               
                    MOVE "III" TO GRADE                 
                 ELSE                                   
                    MOVE "FAIL" TO GRADE                
           END-IF.                                      
       DISP-PARA.                                       
           DISPLAY "THE TOTAL IS: "    TOTAL.           
           DISPLAY "THE AVERAGE IS: "    AVG.           
           DISPLAY "THE PERCENTAGE IS: "    PER.        
           DISPLAY "GRADE IS: "    GRADE.        

/*
* Example 17 - 
* 
* by surender, www.suren.space
* 
PRG 17 Repeat the above program for 5 students using Perform statement.  Display the output in spool in given format. ( Using Group , Filler and Value all )
       IDENTIFICATION DIVISION.                    
       PROGRAM-ID. PRG7.                           
       ENVIRONMENT DIVISION.                       
       DATA DIVISION.                              
       WORKING-STORAGE SECTION.                    
       01 G1.                                      
           02 MARK1 PIC 9(2).                      
           02 FILLER PIC X.                        
           02 MARK2 PIC 9(2).                      
           02 FILLER PIC X.                        
           02 MARK3 PIC 9(2).                      
       77 TOTAL PIC 9(3).                          
       77 AVG PIC 9(3)V9(3).                       
       77 PER PIC 9(3)V9(3).                                  
       77 GRADE PIC A(5).                                     
       PROCEDURE DIVISION.                                    
       MAIN-PARA.                                             
           PERFORM ACCEPT-PARA THRU DISP-PARA 5 TIMES.        
           STOP RUN.                                          
       ACCEPT-PARA.                                           
           ACCEPT G1.                                         
       COMP-PARA.                                             
           COMPUTE TOTAL = ( MARK1  + MARK2 + MARK3 ).        
           COMPUTE AVG = TOTAL / 3.                           
           COMPUTE PER = ( TOTAL / 300 ) * 100.               
           IF AVG > 80                                        
              MOVE "I" TO GRADE                               
           ELSE                                               
              IF AVG > 60 AND AVG < 79                                   MOVE "II" TO GRADE                                   ELSE                                                       IF AVG > 40 AND AVG < 60              
                    MOVE "III" TO GRADE                
                 ELSE                                  
                    MOVE "FAIL" TO GRADE               
           END-IF.                                     
       DISP-PARA.                                      
           DISPLAY "THE TOTAL IS: "    TOTAL.          
           DISPLAY "THE AVERAGE IS: "    AVG.          
           DISPLAY "THE PERCENTAGE IS: "    PER.       
           DISPLAY "GRADE IS: "    GRADE.              

/*
* Example 18 - 
* 
* by surender, www.suren.space
* 
PRG 18 Write a program to check the given no is Prime or not.

        IDENTIFICATION DIVISION.                                    
        PROGRAM-ID. PRG18.                                          
        ENVIRONMENT DIVISION.                                       
        DATA DIVISION.                                              
        WORKING-STORAGE SECTION.                                    
        77 INP-NUM      PIC 9(3).                                   
        77 RES          PIC 9(1) VALUE 0.                           
        77 INC          PIC 9(2)  VALUE 2.                          
        77 QUO          PIC ZZ9.                                    
        77 REM          PIC ZZ9.                                    
        PROCEDURE DIVISION.                                         
        MAIN-PARA.                                                  
           PERFORM ACCEPT-PARA.                                     
            PERFORM COMP-PARA.                                    
            PERFORM DISP-PARA.                                    
            STOP RUN.                                             
         ACCEPT-PARA.                                             
            ACCEPT INP-NUM.                                       
         COMP-PARA.                                               
            PERFORM UNTIL INC < INP-NUM                           
               DIVIDE INP-NUM BY INC GIVING QUO REMAINDER REM     
               IF REM IS EQUAL TO 0                               
                  MOVE 1 TO RES                                   
                  EXIT   

               ELSE                                               
                COMPUTE INC = INC + 1                             
               END-IF                                             
            END-PERFORM.                                          
        DISP-PARA.                                           
           IF RES IS EQUAL TO 0                              
              DISPLAY "THE GIVEN NUMBER IS PRIME!"           
           ELSE                                              
              DISPLAY "THE GIVEN NUMBER IS NON PRIME!"       
           END-IF.                                           
                                         


/*
* Example 19 - 
* 
* by surender, www.suren.space
* 
PRG 19 Write a program to display the natural Nos up to given limit ( using Perform Varying )

        IDENTIFICATION DIVISION.                          
        PROGRAM-ID. PRG18.                                
        ENVIRONMENT DIVISION.                             
        DATA DIVISION.                                    
        WORKING-STORAGE SECTION.                          
        77 STOP-AT      PIC 9(3).                         
        77 INCREMENT    PIC 9(3) VALUE 1.                 
        PROCEDURE DIVISION.                               
        MAIN-PARA.                                        
           PERFORM ACCEPT-PARA.                           
           PERFORM COMP-PARA.                             
           STOP RUN.                                      
        ACCEPT-PARA.                                      
           ACCEPT STOP-AT.                                
        COMP-PARA.                                   
           PERFORM VARYING INCREMENT FROM 1 BY 1     
              UNTIL INCREMENT > STOP-AT              
                 DISPLAY INCREMENT                   
           END-PERFORM.  


/*
* Example 20 - 
* 
* by surender, www.suren.space
* 
PRG 20 Write a program to find the sum of individual digits in a given 'N'  number.

       IDENTIFICATION DIVISION.                                
       PROGRAM-ID. PRG18.                                      
       ENVIRONMENT DIVISION.                                   
       DATA DIVISION.                                          
       WORKING-STORAGE SECTION.                                
       77 NUM          PIC 9(4).                               
       77 TEMP         PIC 9(4).                               
       77 INCREMENT    PIC 9(3) VALUE 1.                       
       77 QUO          PIC 9(3).                               
       77 REM          PIC 9(3).                               
       77 TOTAL        PIC 9(4) VALUE 0.                       
       PROCEDURE DIVISION.                                     
       MAIN-PARA.                                              
           PERFORM ACCEPT-PARA.                                
           PERFORM COMP-PARA.                                 
           PERFORM DISP-PARA.                                 
           STOP RUN.                                          
       ACCEPT-PARA.                                           
           ACCEPT NUM.                                        
       COMP-PARA.                                             
           MOVE NUM TO TEMP                                   
           PERFORM UNTIL TEMP < 10                            
              DIVIDE TEMP BY 10 GIVING QUO REMAINDER REM      
              MOVE QUO TO TEMP                                
              COMPUTE TOTAL = TOTAL + REM                     
           END-PERFORM.                                       
           COMPUTE TOTAL = TOTAL + TEMP.                      
       DISP-PARA.                                             
           DISPLAY "THE SUM OF DIGITS OF NUMBER " NUM.        
           DISPLAY "IS:  "    TOTAL.                    


/*
* Example 21 - 
* 
* by surender, www.suren.space
PRG 21 List the odd and even number between the given limits by using PERFORM statement        

        IDENTIFICATION DIVISION.                                    
        PROGRAM-ID. PRG18.                                          
        ENVIRONMENT DIVISION.                                       
        DATA DIVISION.                                              
        WORKING-STORAGE SECTION.                                    
        77 START-LIST        PIC 9(4).                              
        77 END-LIST          PIC 9(4).                              
        77 INCREMENT         PIC 9(3).                              
        77 REM               PIC 9(3).                              
        77 QUO               PIC 9(3).                              
        PROCEDURE DIVISION.                                         
        MAIN-PARA.                                                  
            PERFORM ACCEPT-PARA.                                    
            PERFORM COMP-PARA.                                      
            STOP RUN.                                               
       ACCEPT-PARA.                                               
           ACCEPT START-LIST.                                     
           ACCEPT END-LIST.                                       

/*
* Example 23 - 
* 
* by surender, www.suren.space
* 
PRG 23 Write a program to perform the Arithmetic operation based the given Options Using Evaluate Statement.
Option 1 -> ADD
Option 2 -> SUBTRACT
Option 3 -> MULTIPLY
Option 4 -> DIVIDE

       IDENTIFICATION DIVISION.                       
       PROGRAM-ID. PRG18.                             
       ENVIRONMENT DIVISION.                          
       DATA DIVISION.                                 
       WORKING-STORAGE SECTION.                       
       77 NUM-1        PIC 9(3).                      
       77 NUM-2        PIC 9(3).                      
       77 OPTION       PIC 9(1).                      
       77 RESULT       PIC 9(4) VALUE 0.              
       PROCEDURE DIVISION.                            
       MAIN-PARA.                                     
           PERFORM ACCEPT-PARA.                       
            PERFORM COMP-PARA.                             
            PERFORM DISPLAY-PARA.                          
            STOP RUN.                                      
        ACCEPT-PARA.                                       
            ACCEPT NUM-1.                                  
            ACCEPT NUM-2.                                  
            ACCEPT OPTION.                                 
        COMP-PARA.                                         
            EVALUATE OPTION                                
               WHEN '1'                                    
                     COMPUTE RESULT = NUM-1 + NUM-2        
               WHEN '2'                                    
                     COMPUTE RESULT = NUM-1 - NUM-2        
               WHEN '3'                                    
                     COMPUTE RESULT = NUM-1 * NUM-2        
               WHEN '4'                                    
                    COMPUTE RESULT = NUM-1 / NUM-2          
           END-EVALUATE.                                    
       DISPLAY-PARA.                                        
           DISPLAY "OPTION WAS: " OPTION.                   
           DISPLAY "RESULT IS: " RESULT.       


/*
* Example 24 - 
* 
* by surender, www.suren.space
* 
PRG 24 Write a program to get the telephone no. and display the ISD code, STD code, Area Code individually using Redefine Clause.

         IDENTIFICATION DIVISION.                         
         PROGRAM-ID. PRG18.                               
         ENVIRONMENT DIVISION.                            
         DATA DIVISION.                                   
         WORKING-STORAGE SECTION.                         
         01 TELEPHONE-NUMBER         PIC X(13).           
         01 TELE-NUM REDEFINES TELEPHONE-NUMBER.          
            05 ISD-CODE              PIC X(3).            
            05 STD-CODE              PIC X(3).            
            05 AREA-CODE             PIC X(3).            
            05 NUM                   PIC X(7).            
         PROCEDURE DIVISION.                              
         MAIN-PARA.                                       
           PERFORM ACCEPT-PARA.                        
           PERFORM DISP-PARA.                          
           STOP RUN.                                   
        ACCEPT-PARA.                                   
           ACCEPT TELEPHONE-NUMBER.                    
        DISP-PARA.                                     
           DISPLAY ISD-CODE.                           
           DISPLAY STD-CODE.                           
           DISPLAY AREA-CODE.                          
           DISPLAY NUM.                                         



/*
* Example 25 - 
* 
* by surender, www.suren.space
* 
PRG 25 Write a Program to get the first name and last name then display the Name together first & last name using Redefine clause.

        IDENTIFICATION DIVISION.                         
        PROGRAM-ID. PRG25.                               
        ENVIRONMENT DIVISION.                            
        DATA DIVISION.                                   
        WORKING-STORAGE SECTION.                         
        01 F-NAME.                                       
            02 FIRST-NAME       PIC A(5).                
            02 LAST-NAME        PIC A(5).                
        01 INDI-NAME REDEFINES F-NAME.                   
            02 FULL-NAME        PIC A(10).               
        PROCEDURE DIVISION.                              
        MAIN-PARA.                                       
           PERFORM ACCEPT-PARA.                          
           PERFORM DISP-PARA.                       
           STOP RUN.                                
        ACCEPT-PARA.                                
           ACCEPT F-NAME.                           
        DISP-PARA.                                  
           DISPLAY FIRST-NAME.                      
           DISPLAY LAST-NAME.                       
           DISPLAY FULL-NAME.  



/*
* COBOL COMPILER SAMPLE
* Example 26 - 
* 
* by surender, www.suren.space
* 
PRG 26 Write a program that declares a group with 7 group items initialized with 7 week days using Value clause.  Redefine this group has occur clause and display the week days using occur subscript.  

       IDENTIFICATION DIVISION.                              
         PROGRAM-ID. PRG25.                                    
         ENVIRONMENT DIVISION.                                 
         DATA DIVISION.                                        
         WORKING-STORAGE SECTION.                              
         01 W-REC.                                             
            02 W-DAYS.                                         
               05 D1 PIC X(10) VALUE "SUNDAY".                 
               05 D2 PIC X(10) VALUE "MONDAY".                 
               05 D3 PIC X(10) VALUE "TUESDAY".                
               05 D4 PIC X(10) VALUE "WEDNESDAY".              
               05 D5 PIC X(10) VALUE "THURSDAY".               
               05 D6 PIC X(10) VALUE "FRIDAY".                 
               05 D7 PIC X(10) VALUE "SATURDAY".                   
            02 W-DAYS1 REDEFINES W-DAYS PIC X(10) OCCURS 7 TIMES.  
         77 I PIC 9(2) VALUE 0.                                    
         PROCEDURE DIVISION.                                       
         MAIN-PARA.                                                
            PERFORM DISP-PARA.                                     
            STOP RUN.                                              
         DISP-PARA.                                                
            PERFORM VARYING I FROM 1 BY 1 UNTIL I > 7              
               DISPLAY W-DAYS1(I)                                  
            END-PERFORM.                                                                


 1. COMPILER CODE
/*
* COBOL COMPILER SAMPLE
* Example 27 - 
* 
* by surender, www.suren.space
* 
PRG 27 Write a Program which accepts the Payroll of employee as given below:

01  WS-PAY.
                       05  WS-FIXED-PAY.
                              10  WS-BASIC  PIC  9(6)V99.
                              10  WS-DA  PIC  9(6)V99.
                      05  WS-ADDITIONAL-PAY.
                             10  WS-HRA  PIC  9(6)V99.
                      05  WS-MTHLY-INCENTIVE PIC  9(6)V99.
                      05  WS-DEDUCTIONS.	
                            10  WS-PF  PIC  9(6)V99.
                            10  WS-IT  PIC  9(6)V99.
                            10  WS-OTHER  PIC  9(6)V99.


/*
* Example 28 - 
* 
* by surender, www.suren.space
* 
PRG 28 Write a program to accept age and amount of deposit and calculate the returns with the interest based on the age, Using Condition name ( 88 level). ( returns = amount + interest).if Minor( Age <18)    7%,  major (age is 18 to 30) 9% , middle age (age 30 to 40 )  10%,  old age (age is 41 to 60) 11%  and  Sr. Citizen (above 60 ) 12%.

        IDENTIFICATION DIVISION.                                 
        PROGRAM-ID. PRG25.                                       
        ENVIRONMENT DIVISION.                                    
        DATA DIVISION.                                           
        WORKING-STORAGE SECTION.                                 
        01 INP-AGE          PIC 999.                             
           88 MINOR         VALUE IS 1 THRU 18.                  
           88 MAJOR         VALUE IS 18 THRU 30.                 
           88 MIDDLE-AGE    VALUE IS 30 THRU 40.                 
           88 OLD-AGE       VALUE IS 41 THRU 60.                 
           88 SR-CITIZEN    VALUE IS 60 THRU 100.                
        77 AMOUNT           PIC 9(5).                            
        77 RETURNS          PIC 9(5)V9(5).                       
        PROCEDURE DIVISION.                    
        MAIN-PARA.                             
           PERFORM ACCEPT-PARA.                
           PERFORM COMP-PARA.                  
           PERFORM DISP-PARA.                  
           STOP RUN.                           
        ACCEPT-PARA.                           
           ACCEPT INP-AGE.                     
           ACCEPT AMOUNT.                      
        COMP-PARA.                                                
           IF MINOR                                               
              COMPUTE RETURNS = AMOUNT + ( ( 7 / 100 ) * AMOUNT)  
           ELSE IF MAJOR                                          
              COMPUTE RETURNS = AMOUNT + ( ( 9 / 100 ) * AMOUNT)  
           ELSE IF MIDDLE-AGE                                     
              COMPUTE RETURNS = AMOUNT + ( ( 10 / 100 ) * AMOUNT) 
           ELSE IF OLD-AGE                                        
              COMPUTE RETURNS = AMOUNT + ( ( 11 / 100 ) * AMOUNT)
           ELSE                                                    
              COMPUTE RETURNS = AMOUNT + ( ( 12 / 100 ) * AMOUNT)  
           END-IF.                                                 
        DISP-PARA.                                                 
           DISPLAY INP-AGE.                                        
           DISPLAY AMOUNT.                                         
           DISPLAY RETURNS.


/*
* COBOL COMPILER SAMPLE
* Example 29 - 
* 
* by surender, www.suren.space
* 
PRG 29 Write a program to display the given character is Vowel, consonant or digit using Condition name ( 88 level )        

       IDENTIFICATION DIVISION.                                     
       PROGRAM-ID. PRG25.                                           
       ENVIRONMENT DIVISION.                                        
       DATA DIVISION.                                               
       WORKING-STORAGE SECTION.                                     
       01 INP-CHAR         PIC X(1).                                
           88 VOWEL         VALUE "A", "E", "I", "O", "U".          
           88 CONSONANT     VALUE "B", "C", "D", "F", "G", "H"      
                                  "J" THRU "N", "P" THRU "T"        
                                  "V" THRU "Z".                     
           88 DIGIT         VALUE "0" THRU "9".                     
        PROCEDURE DIVISION.                                    
        MAIN-PARA.                                             
            PERFORM ACCEPT-PARA.                               
            PERFORM COMP-PARA.                                 
            STOP RUN.                                          
        ACCEPT-PARA.                                           
            ACCEPT INP-CHAR.                                   
        COMP-PARA.                                             
            IF VOWEL                                           
               DISPLAY "THE GIVEN CHARACTER IS A VOWEL!"       
            ELSE IF CONSONANT                                  
               DISPLAY "THE GIVEN CHARACTER IS A CONSONENT!"   
            ELSE IF DIGIT                                      
               DISPLAY "THE GIVEN CHARACTER IS A DIGIT!"       
            ELSE                                               
              DISPLAY "THE GIVEN CHARACTER IS AN INVALID CHARACTER!"   
           END-IF.         


/*
* COBOL COMPILER SAMPLE
* Example 32 - 
* 
* by surender, www.suren.space
* 
PRG 32  Write a program to accept 10 Nos and display the sum of 10 Nos using Occur Clause.

       IDENTIFICATION DIVISION.                                   
       PROGRAM-ID. PRG25.                                         
       ENVIRONMENT DIVISION.                                      
       DATA DIVISION.                                             
       WORKING-STORAGE SECTION.                                   
       01 MAX-NUM.                                                
           05 NUM        PIC 9(2) OCCURS 5 TIMES.                 
       77 IDX            PIC 9(2) VALUE 1.                        
       77 TOTAL          PIC 9(2) VALUE 0.                        
       PROCEDURE DIVISION.                                        
       MAIN-PARA.                                                 
           PERFORM ACCEPT-PARA.                                   
           PERFORM COMP-PARA.                                     
           STOP RUN.                                              
       ACCEPT-PARA.                                               
           PERFORM VARYING IDX FROM 1 BY 1 UNTIL IDX > 5     


/*
* Example 33 - 
* 
* by surender, www.suren.space
* 
PRG 33 Write a program to find which of the numbers from 1 to 50 are divisible by 3.      

       IDENTIFICATION DIVISION.                                      
       PROGRAM-ID. PRG25.                                            
       ENVIRONMENT DIVISION.                                         
       DATA DIVISION.                                                
       WORKING-STORAGE SECTION.                                      
       01 MAX-NUM.                                                   
           05 NUM        PIC 9(2) OCCURS 50 TIMES.                   
       77 IDX            PIC 9(2) VALUE 1.                           
       77 REM            PIC 9(2).                                   
       77 QUO            PIC 9(2).                                   
       PROCEDURE DIVISION.                                           
       MAIN-PARA.                                                    
           PERFORM ACCEPT-PARA.                                      
           PERFORM COMP-PARA.                                        
           STOP RUN.                                                 
       ACCEPT-PARA.                                                  
           PERFORM VARYING IDX FROM 1 BY 1 UNTIL IDX > 50            
              ACCEPT NUM(IDX)                                       
           END-PERFORM.                                             
       COMP-PARA.                                                   
           PERFORM VARYING IDX FROM 1 BY 1 UNTIL IDX > 50            
              DIVIDE0D NUM(IDX) BY 3 HAVING QUO REMAINDER REM        
              IF REM = 0                                            
                 DISPLAY NUM(IDX)                                   
              END-IF                                                
           END-PERFORM.                                             
           DISPLAY TOTAL.                                           



/*
* Example 34 - 
* 
* by surender, www.suren.space
* 
PRG 34 Write a program to find the biggest of N given numbers

       IDENTIFICATION DIVISION.                                       
       PROGRAM-ID. PRG25.                                             
       ENVIRONMENT DIVISION.                                          
       DATA DIVISION.                                                 
       WORKING-STORAGE SECTION.                                       
       01 MAX-NUM.                                                    
           05 NUM        PIC 9(2) OCCURS 5 TIMES.                     
       77 IDX            PIC 9(2) VALUE 1.                            
       77 MAX            PIC 9(2) VALUE 0.                            
       PROCEDURE DIVISION.                                            
       MAIN-PARA.                                                     
           PERFORM ACCEPT-PARA.                                       
           PERFORM COMP-PARA.                                         
           STOP RUN.                                                  
       ACCEPT-PARA.                                                   
           PERFORM VARYING IDX FROM 1 BY 1 UNTIL IDX > 5              
              ACCEPT NUM(IDX)                                         
           END-PERFORM.                                               
       COMP-PARA.                                                     
           PERFORM VARYING IDX FROM 1 BY 1 UNTIL IDX > 5              
              IF NUM(IDX) > MAX                                       
                 MOVE NUM(IDX) TO MAX                                 
              END-IF                                                  
           END-PERFORM.                                               
           DISPLAY MAX.                     



/*
* Example 35 - 
* 
* by surender, www.suren.space
* 

PRG 35 Write  a program to display the number of even and odd numbers , sum of even numbers and odd numbers between 1 to 100.

       IDENTIFICATION DIVISION.                                    
       PROGRAM-ID. PRG25.                                          
       ENVIRONMENT DIVISION.                                       
       DATA DIVISION.                                              
       WORKING-STORAGE SECTION.                                    
       01 EVEN-ODD.                                                
           05 NUM        PIC 9(1) OCCURS 100 TIMES.                
       77 SUM-EVEN       PIC 9(4) VALUE 0.                         
       77 SUM-ODD        PIC 9(4) VALUE 0.                         
       77 IDX            PIC 9(3) VALUE 1.                         
       77 QUO            PIC 9(3).                                 
       77 REM            PIC 9(3).                                 
       PROCEDURE DIVISION.                                         
       MAIN-PARA.                                                  
            PERFORM COMP-PARA.                                   
            STOP RUN.                                            
        COMP-PARA.                                               
            PERFORM VARYING IDX FROM 1 BY 1 UNTIL IDX > 100      
               DIVIDE IDX BY 2 GIVING QUO REMAINDER REM          
               IF REM = 0                                        
                  COMPUTE SUM-EVEN = SUM-EVEN + IDX              
               ELSE                                              
                  COMPUTE SUM-ODD = SUM-ODD  + IDX               
               END-IF                                            
            END-PERFORM.                                         
            DISPLAY "SUM EVEN" SUM-EVEN.                         
            DISPLAY "SUM ODD" SUM-ODD.          


It’s an excellent language and when has compatibility with new technologies, It can go beyond its limitations. Their integrity on such environments indeed proven.

Mainframe is dead? It’s a sinking ship. Sinks too slow that you can actually build a new one by then !!

Advertisements

NRF24L01+ 2.4GHz Antenna Wireless Transceiver Module For Arduino

www.suren.space

I’ve been playing with NRF24L01 module for few weeks now and tested almost all of its features present the data sheet. No other module can come close to this one from my experience. This module is available for around 250 comes along with a 2dbi antenna. Even though, the 433Mhz module is available for the same price, This one proves it worth every penny.

I added the 5dBI rubber duck antenna for around 150 to both transmitter and receiver and it made a huge difference in range and strength.

 

While the NRF is little cumbersome with 8 pin SPI interface and little work of adding libraries when compare dto the traditional age old 433 Mhz or other modules, It only adds worth and reliability for wireless projects of ours.

The best features I admire of NRF is

  • MESH NETWORK
  • 2.5Ghz band support. You can choose from 125 channels of such.
  • Wide range of antennas
  • ACK SUPPORT
  • Excellent reliability and datalink.

The only disappointment I had was the feature of determining the signal strength was however not available in this mode. If not for that, I would perfectly rated 10/10 among wireless modules.

While the makers say, It can go upto 2KM on open point to point, It actually yields poor results. Considering the signal traffic of existing WiFi. I’d suggest you to work on 125th channel or 2.5Ghz.

IMG_20170517_112136.jpg

 

TRANSMITTER CODE BELOW:

/*
* Arduino Wireless Communication Tutorial
* Example 1 - Transmitter Code
* 
* by surender, www.suren.space
* 
* Library: TMRh20/RF24, https://github.com/tmrh20/RF24/
*/

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8); // CNS, CE

const byte address[6] = "00001";

void setup() {
 radio.begin();
 radio.openWritingPipe(address);
 radio.setPALevel(RF24_PA_MIN);
 radio.stopListening();
}

void loop() {
 const char text[] = "Hello World";
 radio.write(&text, sizeof(text));
 delay(1000);
}

CONNECTIONS :

  • 3.3V – VCC
  • GND-GND
  • 8-CSN
  • 7-CS
  • 13-SCK
  • 11-MOSI
  • 12-MISO

RECEIVER CODE BELOW :

/*
* Arduino Wireless Communication Tutorial
* Example 1 - Receiver Code
* 
* by surender, www.suren.space
* 
* Library: TMRh20/RF24, https://github.com/tmrh20/RF24/
*/

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8); // CNS, CE

const byte address[6] = "00001";

void setup() {
 Serial.begin(9600);
 radio.begin();
 radio.openReadingPipe(0, address);
 radio.setPALevel(RF24_PA_MIN);
 radio.startListening();
}

void loop() {
 if (radio.available()) {
 char text[32] = "";
 radio.read(&text, sizeof(text));
 Serial.println(text);
 }
}

It’s an excellent addition to any home automation or industrial automation projects and products. Their integrity on such environments indeed proven.

OH BOY! IT’S SO GOOD AND FLAWLESS !!

WEIGHING SCALE – SMART SYSTEM

www.suren.space

 

This is a prototype done as a model for PLC implementation for weighing bridge scale to ease out for trucks or other heavy vehicles.

It houses a bunch of sensors like wheel sensor, infrared wheel separator to smoothen the entire process. The weight measure is displayed and the toll hand(if that’s what it’s called) moves 90 degrees up or down to allow and stop the vehicle respectively with the help of a servo motor.

The picture below is prototype I made.

IMG_20170409_132759.jpg

Inbox me for the codes.

DRV 8255 vs A4988

www.suren.space

While I went on to explore the most suitable module to control my stepper motor. Preferably for a CNC machine, and many promising contestants showed up. Contestants include l293d, TB560, DRV8255, A4988, Rees52 This blog decides the winner.
IMG_20170504_143045

The good looking(DRV-8255) on the left is surely attractive and there doesn’t stand much difference when it comes performance with the A4988. The screw type adjustment to control the current limit is the same both the modules and might look different than yours as there are multiple chinese manufactures. Where aren’t they? Really? Handle the trim pot gently or else you might end up ruining the module

Heating was very common on both the IC’s which can be pulled down to an extent with additional usage of sink and fan cooling options. The A4988 seemed to cool off much faster when motor is not in operation. The polou IC is technically more reliable on paper. A4988 IC is tiny and might come off under intense heat and rugged usage.

On the programming front, The libraries were available combined for both of them and looked equally comfortable.

Mixing of both A4988 and DRV8255 worked fine on the CNC module. The availability of both in market is not the same, as drv8255 were found almost everywhere. And my observations below.

 

A4988 DRV8825
Availability very widely available widely available
Approx. price 225RS 185Rs
Max. theoretical current 2A 2.5A
Max. microsteps 16 32
PCB color Green / Red Purple
Stepper current adjust. trimpot Yes, near Dir pin Yes, near En pin
Typical Rs value 0.05 Ohm or
0.1 Ohm or
0.2 Ohm
0.1 Ohm
Vref formula (*) I_TripMax= Vref/(8*Rs) I_TripMax= Vref/(5*Rs)
Thermal Overload Protection (**) Yes Yes
PCB layers 2 4
Small heatsink included (***) Almost always Sometimes not
Active cooling required? Recommended Recommended
IC packaging 5x5mm 28-lead QFN 9.7×6.4mm 28HTSSOP

The judgement? Well . . .

A4988 wins. But, not by a fair margin.

NEXTION THE 16×2? Fancy screens for your DIY projects.

www.suren.space

Gone are the days when I used to believe the coolest facelift for any project was 16×2 LCD display. For a 90’s kid(me duh),  It really took me years to realize the painful connections and interfacing procedures behind the 16*2 until I got my hands on it. Woeful soldering and drooping connections and missed out connections stole my precious hours on vicious projects.

While, it’s safe to say the display is still the popular choice among project doers, I urge them to look at the alternative – NEXTION 2.4” or more size if you’d like to. The 4D systems display is an alternative, but it would burn a hole in your pocket unless for an industrial grade product.

LCD-

The nextion is just 4 wires with 5V,GND,Rx,Rx wires making it highly compatible to any microcontroller with UART interface. A touch screen interface to control and display all sorts of sensors, motors, leds, progress bars, virtual buttons, logos and what not? Well, definitely not videos.

Understandably, It costs 1400 and the 200 for 16×2 LCD, But it’s totally worth the looks and credibility for your projects.

GOOD NEWS!!!!!!!!

The nextion comes with an ITEAD IDE which enables the user to pick and drop components and compile it and even to emulate it before deploying it to the device. All, with the simple knowledge to C++ which you would have sufficed from your Arduino.

 

 

So? Pick up one and get started…….

 

Link

My Take on Lua – The embedded language

www.suren.space

lua

 

Lua is a powerful, efficient, lightweight, embeddable scripting language. It supports procedural programming, object-oriented programming, functional programming, data-driven programming, and data description.

Lua combines simple procedural syntax with powerful data description constructs based on associative arrays and extensible semantics. Lua is dynamically typed, runs by interpreting byte code with a register-based virtual machine, and has automatic memory management with incremental garbage collection, making it ideal for configuration, scripting, and rapid prototyping. However, My first take on Lua was when I started with the esp8266 wifi module. Though, most beginners would program the module with Arduino, I’d advise to begin with Lua which is relatively easy when understood. It comes of more handy when you deal with web pages and java scripting. My observation was the arduino programs took much less memory footprint that of the Lua. Lua is more suitable when you go for higher end applications. Below are the useful commands.

 

 

 

  1. — Prints to the screen (Can end with semicolon)
    print(“Hello World”)
    –[[
    Multiline comment
    ]]
    — Variable names can’t start with a number, but can contain letters, numbers
    — and underscores
    — Lua is dynamically typed based off of the data stored there
    — This is a string and it can be surrounded by ‘ or “
    name = “Derek”
    — Another way to print to the screen
    — Escape Sequences : \n \b \t \\ \” \’
    — Get the string size by proceeding it with a #
    io.write(“Size of string “, #name, “\n”)
    — You can store any data type in a variable even after initialization
    name = 4
    io.write(“My name is “, name, “\n”)
    — Lua only has floating point numbers and this is the max number
    bigNum = 9223372036854775807 + 1
    io.write(“Big Number “, bigNum, “\n”)
    io.write(“Big Number “, type(bigNum), “\n”)
    — Floats are precise up to 13 digits
    floatPrecision = 1.999999999999 + 0.0000000000005
    io.write(floatPrecision, “\n”)
    — We can create long strings and maintain white space
    longString = [[
    I am a very very long
    string that goes on for
    ever]]
    io.write(longString, “\n”)
    — Combine Strings with ..
    longString = longString .. name
    io.write(longString, “\n”)
    — Booleans store with true or false
    isAbleToDrive = true
    io.write(type(isAbleToDrive), “\n”)
    — Every variable gets the value of nil by default meaning it has no value
    io.write(type(madeUpVar), “\n”)
    — ———- MATH ———-
    io.write(“5 + 3 = “, 5+3, “\n”)
    io.write(“5 – 3 = “, 5-3, “\n”)
    io.write(“5 * 3 = “, 5*3, “\n”)
    io.write(“5 / 3 = “, 5/3, “\n”)
    io.write(“5.2 % 3 = “, 5%3, “\n”)
    — Shorthand like number++ and number += 1 aren’t in Lua
    — Math Functions: floor, ceil, max, min, sin, cos, tan,
    — asin, acos, exp, log, log10, pow, sqrt, random, randomseed
    io.write(“floor(2.345) : “, math.floor(2.345), “\n”)
    io.write(“ceil(2.345) : “, math.ceil(2.345), “\n”)
    io.write(“max(2, 3) : “, math.max(2, 3), “\n”)
    io.write(“min(2, 3) : “, math.min(2, 3), “\n”)
    io.write(“pow(8, 2) : “, math.pow(8, 2), “\n”)
    io.write(“sqrt(64) : “, math.sqrt(64), “\n”)
    — Generate random number between 0 and 1
    io.write(“math.random() : “, math.random(), “\n”)
    — Generate random number between 1 and 10
    io.write(“math.random(10) : “, math.random(10), “\n”)
    — Generate random number between 1 and 100
    io.write(“math.random(1,100) : “, math.random(1,100), “\n”)
    — Used to set a seed value for random
    math.randomseed(os.time())
    — Print float to 10 decimals
    print(string.format(“Pi = %.10f”, math.pi))
    — ———- CONDITIONALS ———-
    — Relational Operators : > < >= <= == ~=
    — Logical Operators : and or not
    age = 13
    if age < 16 then
        io.write(“You can go to school”, “\n”)
        local localVar = 10
    elseif (age >= 16) and (age < 18) then
        io.write(“You can drive”, “\n”)
    else
        io.write(“You can vote”, “\n”)
    end
    — A variable marked local is local only to this if statement
    — io.write(“Local Variable : “, localvar)
    if (age < 14) or (age > 67) then io.write(“You shouldn’t work\n”) end
    — Format, convert to string and place boolean value with string.format
    print(string.format(“not true = %s”, tostring(not true)))
    — There is no ternary operator in Lua
    — canVote = age > 18 ? true : false
    — This is similar to the ternary operator
    canVote = age > 18 and true or false
    io.write(“Can I Vote : “, tostring(canVote), “\n”)
    — There is no Switch statement in Lua
    — ———- STRINGS ———-
    quote = “I changed my password everywhere to ‘incorrect.’ That way when I forget it,it always reminds me, ‘Your password is incorrect.'”
    io.write(“Quote Length : “, string.len(quote), “\n”)
    — Return the string after replacing
    io.write(“Replace I with me : “, string.gsub(quote, “I”, “me”), “\n”)
    — Find the index of a matching String
    io.write(“Index of password : “, string.find(quote, “password”), “\n”)
    — Set characters to upper and lowercase
    io.write(“Quote Upper : “, string.upper(quote), “\n”)
    io.write(“Quote Lower : “, string.lower(quote), “\n”)
    — ———- LOOPING ———-
    i = 1
    while (i <= 10) do
      io.write(i)
      i = i + 1
      — break throws you out of a loop
      — continue doesn’t exist with Lua
      if i == 8 then break end
    end
    print(“\n”)
    — Repeat will cycle through the loop at least once
    repeat
      io.write(“Enter your guess : “)
      — Gets input from the user
      guess = io.read()
      — Either surround the number with quotes, or convert the string into
      — a number
    until tonumber(guess) == 15
    — Value to start with, value to stop at, increment each loop
    for i = 1, 10, 1 do
      io.write(i)
    end
    print()
    — Create a table which is a list of items like an array
    months = {“January”, “February”, “March”, “April”, “May”,
    “June”, “July”, “August”, “September”, “October”, “November”,
    “December”}
    — Cycle through table where k is the key and v the value of each item
    for k, v in pairs(months) do
      io.write(v, ” “)
    end
    print()
    — ———- TABLES ———-
    — Tables take the place of arrays, dictionaries, tuples, etc.
    — Create a Table
    aTable = {}
    — Add values to a table
    for i = 1, 10 do
      aTable[i] = i
    end
    — Access value by index
    io.write(“First Item : “, aTable[1], “\n”)
    — Items in Table
    io.write(“Number of Items : “, #aTable, “\n”)
    — Insert in table, at index, item to insert
    table.insert(aTable, 1, 0)
    — Combine a table as a String and seperate with provided seperator
    print(table.concat(aTable, “, “))
    — Remove item at index
    table.remove(aTable, 1)
    print(table.concat(aTable, “, “))
    — Sort items in reverse
    table.sort(aTable, function(a,b) return a>b end)
    print(table.concat(aTable, “, “))
    — Create a multidimensional Table
    aMultiTable = {}
    for i = 0, 9 do
      aMultiTable[i] = {}
      for j = 0, 9 do
        aMultiTable[i][j] = tostring(i) .. tostring(j)
      end
    end
    — Access value in cell
    io.write(“Table[0][0] : “, aMultiTable[1][2], “\n”)
    — Cycle through and print a multidimensional Table
    for i = 0, 9 do
      for j = 0, 9 do
        io.write(aMultiTable[i][j], ” : “)
      end
      print()
    end
    — ———- FUNCTIONS ———-
    function getSum(num1, num2)
      return num1 + num2
    end
    print(string.format(“5 + 2 = %d”, getSum(5,2)))
    function splitStr(theString)
      stringTable = {}
      local i = 1
      — Cycle through the String and store anything except for spaces
      — in the table
      for str in string.gmatch(theString, “[^%s]+”) do
        stringTable[i] = str
        i = i + 1
      end
      — Return multiple values
      return stringTable, i
    end
    — Receive multiple values
    splitStrTable, numOfStr = splitStr(“The Turtle”)
    for j = 1, numOfStr do
      print(string.format(“%d : %s”, j, splitStrTable[j]))
    end
    — Variadic Function recieve unknown number of parameters
    function getSumMore(…)
      local sum = 0
      for k, v in pairs{…} do
        sum = sum + v
      end
      return sum
    end
    io.write(“Sum : “, getSumMore(1,2,3,4,5,6), “\n”)
    — A function is a variable in that we can store them under many variable
    — names as well as in tables and we can pass and return them though functions
    — Saving an anonymous function to a variable
    doubleIt = function(x) return x * 2 end
    print(doubleIt(4))
    — A Closure is a function that can access local variables of an enclosing
    — function
    function outerFunc()
      local i = 0
      return function()
        i = i + 1
        return i
      end
    end
    — When you include an inner function in a function that inner function
    — will remember changes made on variables in the inner function
    getI = outerFunc()
    print(getI())
    print(getI())
    — ———- COROUTINES ———-
    — Coroutines are like threads except that they can’t run in parallel
    — A coroutine has the status of running, susepnded, dead or normal
    — Use create to create one that performs some action
    co = coroutine.create(function()
      for i = 1, 10, 1 do
      print(i)
      print(coroutine.status(co))
      if i == 5 then coroutine.yield() end
      end end)
    — They start off with the status suspended
    print(coroutine.status(co))
    — Call for it to run with resume during which the status changes to running
    coroutine.resume(co)
    — After execution it has the status of dead
    print(coroutine.status(co))
    co2 = coroutine.create(function()
      for i = 101, 110, 1 do
      print(i)
      end end)
    coroutine.resume(co2)
    coroutine.resume(co)
    — ———- FILE I/O ———-
    — Different ways to work with files
    — r: Read only (default)
    — w: Overwrite or create a new file
    — a: Append or create a new file
    — r+: Read & write existing file
    — w+: Overwrite read or create a file
    — a+: Append read or create file
    — Create new file for reading and writing
    file = io.open(“test.lua”, “w+”)
    — Write text to the file
    file:write(“Random string of text\n”)
    file:write(“Some more text\n”)
    — Move back to the beginning of the file
    file:seek(“set”, 0)
    — Read from the file
    print(file:read(“*a”))
    — Close the file
    file:close()
    — Open file for appending and reading
    file = io.open(“test.lua”, “a+”)
    file:write(“Even more text\n”)
    file:seek(“set”, 0)
    print(file:read(“*a”))
    file:close()
    — ———- MODULES ———-
    — A Module is like a library full of functions and variables
    — Use require to gain access to the functions in the module
    convertModule = require(“convert”)
    — Execute the function in the module
    print(string.format(“%.3f cm”, convertModule.ftToCm(12)))
    — ———- METATABLES ———-
    — Used to define how operations on tables should be carried out in regards
    — to adding, subtracting, multiplying, dividing, concatenating, or
    — comparing tables
    — Create a table and put default values in it
    aTable = {}
    for x = 1, 10 do
      aTable[x] = x
    end
    mt = {
      — Define how table values should be added
      — You can also define _sub, _mul, _div, _mod, _concat (..)
      __add = function (table1, table2)
        sumTable = {}
        for y = 1, #table1 do
          if (table1[y] ~= nil) and (table2[y] ~= nil) then
            sumTable[y] = table1[y] + table2[y]
          else
            sumTable[y] = 0
          end
        end
        return sumTable
      end,
      — Define how table values should be checked for equality
      __eq = function (table1, table2)
        return table1.value == table2.value
      end,
      — For homework figure out how to check if less then
      __lt = function (table1, table2)
        return table1.value < table2.value
      end,
      — For homework figure out how to check if less then or equal
      __le = function (table1, table2)
        return table1.value <= table2.value
      end,
    }
    — Attach the metamethods to this table
    setmetatable(aTable, mt)
    — Check if tables are equal
    print(aTable == aTable)
    addTable = {}
    — Add values in tables
    addTable = aTable + aTable
    — print the results of the addition
    for z = 1, #addTable do
      print(addTable[z])
    end
    — ———- OBJECT ORIENTED PROGRAMMING ———-
    — Lua is not an OOP language and it doesn’t allow you to define classes
    — but you can fake it using tables and metatables
    — Define the defaults for our table
    Animal = {height = 0, weight = 0, name = “No Name”, sound = “No Sound”}
    — Used to initialize Animal objects
    function Animal:new (height, weight, name, sound)
      setmetatable({}, Animal)
      — Self is a reference to values for this Animal
      self.height = height
      self.weight = weight
      self.name = name
      self.sound = sound
      return self
    end
    — Outputs a string that describes the Animal
    function Animal:toString()
      animalStr = string.format(“%s weighs %.1f lbs, is %.1f in tall and says %s”, self.name, self.weight, self.height, self.sound)
      return animalStr
    end
    — Create an Animal
    spot = Animal:new(10, 15, “Spot”, “Roof”)
    — Get variable values
    print(spot.weight)
    — Call a function in Animal
    print(spot:toString())
    — ———- INHERITANCE ———-
    — Extends the properties and functions in another object
    Cat = Animal:new()
    function Cat:new (height, weight, name, sound, favFood)
      setmetatable({}, Cat)
      — Self is a reference to values for this Animal
      self.height = height
      self.weight = weight
      self.name = name
      self.sound = sound
      self.favFood = favFood
      return self
    end
    — Overide an Animal function
    function Cat:toString()
      catStr = string.format(“%s weighs %.1f lbs, is %.1f in tall, says %s and loves %s”, self.name, self.weight, self.height, self.sound, self.favFood)
      return catStr
    end
    — Create a Cat
    fluffy = Cat:new(10, 15, “Fluffy”, “Meow”, “Tuna”)
    print(fluffy:toString())

Continue reading

TIMER FUNCTION IN APP INVENTOR

QUICK TIP : HOW TO BECOME AN APP DEVELOPER ?

  • Go to app inventor/thunkable to see how easy to create apps
  • Call yourself an App developer? DEFINETELY NO
  • UNDERSTAND HOW AN APP WORKS
  • SET REALISTIC LEARNING GOALS – ANDROID STUDIO/ECLIPSE
  • START LEARNING FOR REAL

 

For those who are on to create sample apps on third party MIT/THUNKABLE apps for arduino,raspberry, esp8066, bluetooth devices and experiments, you shall be forgiven and this post shares the crucial element of timer function below.

blocks