Thread for Programming and Realeted Topics

rclakmal

Active member
  • May 8, 2008
    698
    183
    43
    In a galaxy far far away
    Hey guys i saw lot of threads had started for this purpose but non of them continued.So Lets make this thread a place where we can discuss the problems we encounter in programming and any other topic related to that .

    Im currently learning Java and VB.net. but as i believe if u master on one programming language it won't be difficult to catch up another language.Specially these OO languages.im still a newbie on programming and i want all of u to post ur questions on this thread. And i will do the same .So the people who have already got a sound knowledge on that field will answer it!!

    And it will help others too !!!!!!!!!! Lets Learn as a team

    THIS IS FOR ALL OF U WHO ARE WILLING TO LEARN PROGRAMMING !!!!!!!!
     
    • Like
    Reactions: Zeus and koondeGoda

    OptiplexFx

    Member
    May 29, 2009
    2,568
    44
    0
    cyberspace
    Well in my personal opinion, having a single very long thread makes it difficult to find something quickly. Personally I think it is better to start separate threads for separate discussions, easier to search and organize information.

    Well...., that is just what I feel. But don't get discouraged. Maybe others will like your idea.
     

    rclakmal

    Active member
  • May 8, 2008
    698
    183
    43
    In a galaxy far far away
    Well in my personal opinion, having a single very long thread makes it difficult to find something quickly. Personally I think it is better to start separate threads for separate discussions, easier to search and organize information.

    Well...., that is just what I feel. But don't get discouraged. Maybe others will like your idea.


    yr machan .Its true for some extent !!! and im ready to accept it !!! Actually i thought we can share our codes and technological matters in this thread, So a person who is interested in this field can obtain a good help by reading it !!!
    And also if we stick our self to the thread then we will be able to see others problems and also replies for our problems !!!!!! May be ,May be it will become impractical after some time !!!!!! But first of all we have to start nah??? :D

    Anyway thanks for ur reply !!!!!!!
     

    rclakmal

    Active member
  • May 8, 2008
    698
    183
    43
    In a galaxy far far away
    Ok here is a small code to Read 10 numbers from keyboard and to output average and to print how many numbers are larger than the average

    Code:
    package firstex;
    import java.util.Scanner;
    
    class Numbers{
        public static void main(String[] args) {
            Scanner input=new Scanner(System.in);
            int arrayNum[]=new int[10];
            double total=0;
            int noOfHigh=0;
            try{
            System.out.println("Enter 10 numbers keeping a space");
            for (int i=0;i<=9;i++){
               arrayNum[i]=input.nextInt();
            }
            
    
            for (int i=0;i<=9;i++){
                total+=arrayNum[i];
            }
            double average=total/10;
            System.out.println("Average="+average);
    
            for(int i=0;i<=9;i++){
    
                if(arrayNum[i]>average)
                    noOfHigh++;
    
            }
            System.out.println( noOfHigh+" numbers are greater than the average.");
            } catch(Exception e){
                System.out.println("Wrong Input! Try Agin!!");
            }
    
        }
    }
     

    OptiplexFx

    Member
    May 29, 2009
    2,568
    44
    0
    cyberspace
    One suggestion : Try to merge related loops whenever you can, for example in the above code you could combine total+= and noOfHigh++ inside the same loop. Java compiler might internally optimize that code to run inside one loop (not sure tho..) but its better if you do it while coding.
     

    rclakmal

    Active member
  • May 8, 2008
    698
    183
    43
    In a galaxy far far away
    One suggestion : Try to merge related loops whenever you can, for example in the above code you could combine total+= and noOfHigh++ inside the same loop. Java compiler might internally optimize that code to run inside one loop (not sure tho..) but its better if you do it while coding.


    Ah thanks friend ,
    Actually this was a problem in a another site....and i saw two parts of this problem
    1. To output average
    2. To output no of larger numbers

    Then i thought it would be better to have separated for loops for that .
    But now i think after looking @ it again ,as i have used meaningful variable names it is OK to have a single for loop for both parts.

    If the compiler takes it as a single for loop ,then the compiling time won't increase no ? But as u suggest it is nice to code like that.Thanks again !!!!!!!
     

    madurax86

    Member
    Jun 29, 2006
    4,385
    88
    0
    I dont know java but here is the C++ equivalent :P

    Code:
    #include <cstdlib>
    #include <iostream>
    
    using namespace std;
    
    main() 
    {
        int i,j=0;
        float fNum[9],fTot=0;
        for (i=0;i<=9;i++){
            cin>>fNum[i];
            fTot=fTot+fNum[i];
        }
        cout<<"Following numbers are above average "<<endl;
        fTot=fTot/10;
        for (i=0;i<=9;i++){
            if (fTot<fNum[i]) {j++;cout<<fNum[i]<<endl;}
        }
        cout<<j<<" numbers are above average"<<endl;
        cout<<"average is "<<fTot<<endl;
        system("PAUSE");
    }
     

    rclakmal

    Active member
  • May 8, 2008
    698
    183
    43
    In a galaxy far far away
    I dont know java but here is the C++ equivalent :P

    Code:
    #include <cstdlib>
    #include <iostream>
    
    using namespace std;
    
    main() 
    {
        int i,j=0;
        float fNum[9],fTot=0;
        for (i=0;i<=9;i++){
            cin>>fNum[i];
            fTot=fTot+fNum[i];
        }
        cout<<"Following numbers are above average "<<endl;
        fTot=fTot/10;
        for (i=0;i<=9;i++){
            if (fTot<fNum[i]) {j++;cout<<fNum[i]<<endl;}
        }
        cout<<j<<" numbers are above average"<<endl;
        cout<<"average is "<<fTot<<endl;
        system("PAUSE");
    }

    Elaz macho !!! Thanks !!! if u have more programming problems like this with u please post here !!! So a person can try them with a language familiar to them !!! and we can share our codes !!!!!!!
     

    madurax86

    Member
    Jun 29, 2006
    4,385
    88
    0
    hmm try posting your code for a prime factor finder
    example,
    if i input 10, it's prime factors are 5 and 2
    if i input 60, its prime factors are 3,5 and 2 ..like that
     

    rclakmal

    Active member
  • May 8, 2008
    698
    183
    43
    In a galaxy far far away
    Thanks madhura for contribution in this thread. And for your problem !!!! How about this !!!:d check if u can !!!!! Thanks again !!!

    Code:
    package firstex;
    import java.util.Scanner;
    
    /**
     *
     * @author lakmal
     */
     class PrimeFactor {
         static boolean checkPrime(int number){
             if (number==0||number==1)
                 return false;
             else{
             int  noOfFactors=0;
             for (int i=1;i<=number;i++){
                 if (number%i==0)
                     noOfFactors++;
             }
    
             if (noOfFactors==2)
                 return true;
             else
                 return false;
         }
        }
    
    
         public static void main(String[] args) {
             try {
             Scanner input=new Scanner(System.in);
             System.out.print("Enter Your Prefered Number:");
             int number=input.nextInt();
             
    
             System.out.println("Here are the prime factors of that number");
             for (int i=1;i<=number;i++){
                 if(checkPrime(i)){
                     if ((number%i)==0)
                         System.out.println(i);
                 }
             }
                 } catch(Exception e){
                     System.out.println("Wrong Input!");
                 }
                 }
             }
     
    • Like
    Reactions: koondeGoda

    madurax86

    Member
    Jun 29, 2006
    4,385
    88
    0
    Heres my solution,
    Code:
    #include <cstdlib>
    #include <iostream>
    
    using namespace std;
    
    FindPrimeFactors(long s)
    {
        long i;
    
        if (s==0){ cout<<"0"<<endl; return 0; }
        for (i=2;i<=(s/2);i++)
        {
            if (s % i == 0)
            {
                cout<<i<<endl;
                s=s/i;
                i=2;        
            }
        }
        cout<<s<<endl;
    }

    It is just the code of the function that finds the Prime Factors. Input code is not there .. and oh i've made it to give all the results :P
    my bad i gave you the problem after making the program :P it finds all prime factors with repetition ..
     
    Last edited:

    rclakmal

    Active member
  • May 8, 2008
    698
    183
    43
    In a galaxy far far away
    We both have used same logic ne machan !!! Elaz
    and i have two problem machan ......
    1.Im little bit familiar with C and seems that C++ is some what like 'C'. Machan i tried to run ur programs in NetBeans IDE (it has provided C/C++ compilers) but may be it hasnt provided libraries realted ur programme coz im getting erros in them.So can u plese tell me a way to run ur code and see. (easy way :D :P)

    2. and the second problem is how ur going to handle exceptions in C++. As an example if the user inputs a character instead of a number then how u r going to handle that without terminating the programme .In my code

    i have included the main method inside a
    Code:
    try{}
    catch(Exception e){}

    So does c++ have that kind of fucntionality??
     

    madurax86

    Member
    Jun 29, 2006
    4,385
    88
    0
    We both have used same logic ne machan !!! Elaz
    and i have two problem machan ......
    1.Im little bit familiar with C and seems that C++ is some what like 'C'. Machan i tried to run ur programs in NetBeans IDE (it has provided C/C++ compilers) but may be it hasnt provided libraries realted ur programme coz im getting erros in them.So can u plese tell me a way to run ur code and see. (easy way :D :P)

    2. and the second problem is how ur going to handle exceptions in C++. As an example if the user inputs a character instead of a number then how u r going to handle that without terminating the programme .In my code

    i have included the main method inside a
    Code:
    try{}
    catch(Exception e){}

    So does c++ have that kind of fucntionality??

    C++ has that kind of functionality but I personally dont use try catch statements in my code :P
    C++ is the OOP version of C, C is some what structural C++ has OOP functionality.

    Use Dev C++, I use it to code they run well in Dev C++.
     

    madurax86

    Member
    Jun 29, 2006
    4,385
    88
    0
    ඕන්න කට්ටියට ඕන නම් ගන්න මේක Scientific Cal එකක් Delphi වලින් ලිව්වෙ
    මට VB6 වල string functions පුරුදුවෙලා නිසා මේකෙ ඒවත් අලුතෙන් හදලා තමා පටන් ගත්තෙ.
    සම්පූර්ණ project එක(exe සමඟ)
    http://madurax86.2kmegs.com/Calc.zip

    Code:
    //--Info
    // * Originally written by Madura Anushanga Shelton
    // * Last updated: 16/09/09
    // * Please give credit where credit is due, if you are planning to use this code
    //   or its ideas :D
    //--
    program Project1;
    {$APPTYPE CONSOLE}
    uses SysUtils;
    var  s:string;   iWidth:integer;  sTmp:string;
    //--main cal functions
    function add(sVal1,sVal2:string):string;
    var r1,r2:real;
    begin
      val(sval1,r1,iWidth);
      val(sval2,r2,iWidth);
      result:=formatfloat('',r2+r1) ;
    end;
    function subtract(sVal1,sVal2:string):string;
    var r1,r2:real;
    begin
      val(sval1,r1,iWidth);
      val(sval2,r2,iWidth);
      result:=formatfloat('',r1-r2) ;
    end;
    function divide(sVal1,sVal2:string):string;
    var r1,r2:real;
    begin
      val(sval1,r1,iWidth);
      val(sval2,r2,iWidth);
      result:=formatfloat('',r1/r2) ;
    end;
    function multiply(sVal1,sVal2:string):string;
    var r1,r2:real;
    begin
      val(sval1,r1,iWidth);
      val(sval2,r2,iWidth);
      result:=formatfloat('',r1*r2) ;
    end;
    //--
    //--string manipulation and convertion
    function Rev(sMain:string):string;
    var s:string;i:integer;
    begin
      s:=smain;
      for i := 1 to length(sMain) do
      begin
         s[length(sMain)-i+1]:=sMain[i];
      end;
      rev:= s;
    end;
    function Mid(const strMain:string;const iStart,iLen:Integer):string;
    var i,j:integer;var strOut:string;
    begin
      j:=iLen;
      if iLen = 0 then
      begin
        j:=length(strMain)-iStart;
      end;
    
      for i := 1 to j do
        begin
          strOut := strOut + strMain[i+iStart];
        end;
      result:=strout;
    end;
    function Replace(const strMain,strSearch,strReplace:string):string;
    var i:integer;strOut:string;t:integer;
    begin
      //go through the string
      i:=-1;
      t:=1;
      while (t=1) do
        begin
          i:=i+1;
          if strSearch = mid(strMain,i,length(strSearch)) then
            begin
              strOut:=strOut+strReplace;               //replace if found
              i:= i+length(strSearch)-1;
            end
          else
            begin
              strOut:=strOut+mid(strMain,i,1);        //if not found amend
            end;
          if i= length(strMain) then t:=0;
    
        end;
      result:=strOut;
    end;
    function InStr(const strMain,strSearch:string; iStart:integer=0):integer;
    var i,j:integer;
    begin
      j:=-1;
      for i := iStart to length(strMain) - length(strSearch) do
      begin
        if strSearch=mid(strMain,i,length(strSearch)) then
        begin
          j:=i;
          break;
        end;
      end;
      InStr:=j;
    end;
    function c_sr(sNum:string):real;
    var r1:real;
    begin
      val(snum,r1,iWidth);
      c_sr:=r1;
    end;
    function c_rs(rNum:real):string;
    begin
      c_rs:=formatfloat('',rNum);
    end;
    procedure GetNumbers(const strMain,strChk:string;var iL,iR:real;var strRep:string);
    var   i,j:integer;k,l:string; label 2;
    begin
      j:=instr(strmain,strChk,1);
    
      for i := j+2 to length(strmain) do
        begin
          if ((strmain[i]='/') or (strmain[i]='*') or (strmain[i]='+')  or (strmain[i]='-') )And not (j+2=i )then
            begin
              //if  (strmain[i]='+')  or (strmain[i]='-') then  k:=k+strmain[i];
              break;
            end
          else
            begin
              k:=k+strmain[i];
            end;
        end;
        for i := j downto 1 do
        begin
          if (strmain[i]='/') or (strmain[i]='*') or (strmain[i]='+')  or (strmain[i]='-') then
            begin
              if  (strmain[i]='+')  or (strmain[i]='-') then  l:=l+strmain[i];
              break;
            end
          else
            begin
              l:=l+strmain[i];
            end;
        end;
        l:=rev(l);
        iL:=c_sr(l);
        iR:=c_sr(k);
        strRep:=l+strchk+k;
    end;
    //--
    //--recursive
    function Division(const strMain:string;var strRes:string):string;
    var sOut,sRep:string;r1,r2:real;
    begin
      if not (instr(strmain,'/') = -1) then
      begin
        getnumbers(strmain,'/',r1,r2,sRep);
        sout:=replace(strmain,srep,c_rs(r1/r2));
        if instr(sout,'/') = -1 then
          strRes := sout
        else
          Division(sout,strRes);
      end
      else strres:=strmain;
    end;
    function Multiplication(const strMain:string;var strRes:string):string;
    var sOut,sRep:string;r1,r2:real;
    begin
      if not (instr(strmain,'*') = -1) then
      begin
        getnumbers(strmain,'*',r1,r2,sRep);
        sout:=replace(strmain,srep,c_rs(r1*r2));
        if instr(sout,'*') = -1 then
          strRes := sout
        else
          Multiplication(sout,strRes);
      end
      else strres:=strmain;
    end;
    function Addition(const strMain:string;var strRes:string):string;
    var sOut,sRep:string;r1,r2:real;
    begin
      if not (instr(strmain,'+',1) = -1) then
      begin
        getnumbers(strmain,'+',r1,r2,sRep);
        sout:=replace(strmain,srep,c_rs(r1+r2));
        if instr(sout,'+') = -1 then
          strRes := sout
        else
          Addition(sout,strRes);
      end
      else strres:=strmain;
    end;
    function Subtraction(const strMain:string;var strRes:string):string;
    var sOut,sRep:string;r1,r2:real;
    begin
      if not (instr(strmain,'-',1) = -1) then
      begin
        getnumbers(strmain,'-',r1,r2,sRep);
        sout:=replace(strmain,srep,c_rs(r1-r2));
        if (instr(sout,'-') = -1) then
          strRes := sout
        else
          Subtraction(sout,strRes);
      end
      else strres:=strmain;
    end;
    //--
    //--Execution--no parenthesis level
    function Execute(const str:string):string;
    var i:integer; label 1;
    begin
      //BODMAS
      if (trim(str)='') then begin stmp:=str; goto 1; end;
    
      division(str,stmp);
      multiplication(stmp,stmp);
      addition(stmp,stmp);
      subtraction(stmp,stmp);
       1: Execute:=stmp;
    end;
    //--
    //--Calculator-main
    procedure CutParenthesis(strIn:string);
    var i,j,k:integer; a:string;
    begin
      k:=0;
      for i := 0 to length(strIn) do if strIn[i] = '('  then j:=i; //get last '('
      for i := j to length(strIn) do if (strIn[i] = ')') and (k=0) then k:=i  ; //first ')'
      a:=mid(strIn,j,k-j-1);    //execute a, a will not include '(',')'
      strIn:=replace(strIn,'('+a+')',trim(Execute(a)));
      if instr(strIn,'(')=-1 then
        begin
          strIn:=Execute(strIn);
          writeln(' = '+strIn);
          writeln('');
        end
      else
        cutparenthesis(strIn);
    end;
    procedure Calc();            //main loop of the whole calculator
    var s:string;
    begin
      stmp:='';
      iWidth:=3;
      s:='';
      readln(s);
      if not (instr(s,'{') = -1)  then  s:=replace(s,'{','(');
      if not (instr(s,'[') = -1)  then  s:=replace(s,'[','(');
      if not (instr(s,']') = -1)  then  s:=replace(s,']',')');
      if not (instr(s,'}') = -1)  then  s:=replace(s,'}',')');
    
      CutParenthesis(s);
    end;
    //--
    //--Some DOS graphics :P
    procedure PrintHeader();
    var j:integer;
    begin
      for j := 1 to 80 do write('=');
      writeln('');
      writeln(' A Simple Scientific Calculator - Written by Madura Anushanga Shelton in Delphi');
      writeln(' * Do NOT enter wrong expressions, it''ll not throw an error for wrong input.');
      writeln('');
      for j := 1 to 80 do write('=');
      writeln('');
    end;
    //--
    var i:integer;
    begin
      PrintHeader;
      i:=0;
      while i=0 do calc;
    end.
     

    rclakmal

    Active member
  • May 8, 2008
    698
    183
    43
    In a galaxy far far away
    ඕන්න කට්ටියට ඕන නම් ගන්න මේක Scientific Cal එකක් Delphi වලින් ලිව්වෙ
    මට VB6 වල string functions පුරුදුවෙලා නිසා මේකෙ ඒවත් අලුතෙන් හදලා තමා පටන් ගත්තෙ.
    සම්පූර්ණ project එක(exe සමඟ)
    http://madurax86.2kmegs.com/Calc.zip
    Machan meke thiyena operators monda???? I mean Sin cos tan ewath thiynewada .............
     

    rclakmal

    Active member
  • May 8, 2008
    698
    183
    43
    In a galaxy far far away
    I dont know java but here is the C++ equivalent :P

    Code:
    #include <cstdlib>
    #include <iostream>
    
    using namespace std;
    
    main() 
    {
        int i,j=0;
        float fNum[9],fTot=0;
        for (i=0;i<=9;i++){
            cin>>fNum[i];
            fTot=fTot+fNum[i];
        }
        cout<<"Following numbers are above average "<<endl;
        fTot=fTot/10;
        for (i=0;i<=9;i++){
            if (fTot<fNum[i]) {j++;cout<<fNum[i]<<endl;}
        }
        cout<<j<<" numbers are above average"<<endl;
        cout<<"average is "<<fTot<<endl;
        system("PAUSE");
    }

    Machan i pasted this code on a windows application of dev C++ .And it compiled successfully.But when i hit the RUN button command prompt appeared and said press any key to continue and after pressing a key it closed..........

    I erased all the codings which comes automatcially when we create a windows application ....May be that is the case !!!! So Please help me on this !!!
     

    madurax86

    Member
    Jun 29, 2006
    4,385
    88
    0
    Machan meke thiyena operators monda???? I mean Sin cos tan ewath thiynewada .............

    ඒව දාල තාම හදාගෙන යනව මේ සිංහල ටයිපින් එකේ පොඩිවැඩ ටිකක් තිබ්බ නිසා ඒව මග නැවතුන :S
    ම්ම් ඕකට පුළුවන් වරහන් +,-,*,/ වලින් දෙන ඕන ගණිතමය ප්‍රකාශනයක් සුලු කරන්න
    උදා: ((4+46*5)/99 + 9)*8