Click here to Skip to main content
15,896,730 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
if n=4, then the output should be MNOM

I am not getting the logic of how to print O here because there are 3 alphabets here. In 2 alphabets I can use even and odd logic but what should I do here.Please help me

What I have tried:

class Main {
  public static void main(String[] args) {
    int n=8;
    String str="";
    
    for(int i=1;i<=n;i++)
    {
      if(i%2!=0)
      {
        str=str+"M";
      }
      else
      {
        str=str+"N";
      }
      System.out.println(str);
      
    }
  }
}
Posted
Updated 13-Mar-18 12:31pm
Comments
Member 13724614 13-Mar-18 17:50pm    
solved it. yesssss!!!!

class Main {
  public static void main(String[] args) {
    int n=8;
    String str="";
    
    for(int i=1;i<=n;i++)
    {
      if(i%3==1)
      {
        str=str+"M";
      }
      if(i%3==2)
      {
        str=str+"N";
      }
      if(i%3==0)
      {
        str=str+"O";
      }
    }
      System.out.println(str);
    
  }
}
 
Share this answer
 
You code can be easily generalized. Try, for instance
Java
class Main
{
  public static String build(int letters, int length)
  {
    StringBuilder sb = new StringBuilder();
    for (int n=0; n<length; ++n)
    {
      sb.append((char)('M'+ n % letters));
    }
    return sb.toString();
  }

  public static void main( String args[])
  {
    String msg1 = build(2, 4);
    String msg2 = build(3, 4);
    System.out.printf("msg1 '%s', msg2 '%s'\n", msg1, msg2);
  }
}
 
Share this answer
 
Comments
Member 13724614 13-Mar-18 20:55pm    
Sir, I am a beginner and very new to java. I appreciate your efforts but this code that you have written, I could not get it. Please make me understand this, I will be really grateful to you.
CPallini 14-Mar-18 5:23am    
You are using (i % 2) result, that is either 0 or 1 to distinguish between 'M' and 'N'. Since 'N' character code is equal to 'M' character code plus one, then
'M' + (i % 2)
replaces your conditional statements.
That could be easily generalized to
'M' + (i % 3)
'M' + (i % 4)
...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900