Ad

Stuck With The Same Question For 3 Days Now

- 1 answer

Write a program to print the following number series 1,4,27,16,25,36………100

I have tried using this code but it only shows the squares and not the cubes. the pattern is cube,square,cube,square...

The code I used is

import java.util.*;

class squares{

public static void main(){
    int x;
    
    for (int i = 1;i<=10;i++){
     int j=i*i;
     System.out.println(j);
    }
   }
}
Ad

Answer

You want to print the squares for i being odd (i%2 == 0) and the cubes for i being even (i%2 == 1, the complementary case)

You're looking for something like this:

class squares {
  public static void main(String[] args) {
    int j;
    for (int i = 1; i <= 10; i++) {
      if (i % 2 == 0) {
        j = i * i;
      } else {
        j = i * i * i;
      }
      System.out.println(j);
    }
  }
}
Ad
source: stackoverflow.com
Ad