Breaking

Thursday, 28 September 2017

Perfect Squares - Till N

                      Perfect Squares - Till N



                                  

Given a positive integer N as the input, print all the perfect squares till N (inclusive of N).
Input Format:
The first line contains N.
Output Format:
The first line contains the perfect squares till N separated by a space.
Boundary Conditions:
1 <= N <= 9999999
Example Input/Output 1:
Input:
20
Output:
1 4 9 16
Example Input/Output 2:
Input:
1
Output:
1

Code:
C language:

#include<stdio.h>
void printSquare(int N)
{
    int i=1,x=0;
    while(x<N)
    {
        x=i*i;
        if(x<=N)
        printf("%d ",x);
        i++;
    }
}
void main()
{
    int N;
    scanf("%d",&N);
    printSquare(N);
}

Java:
import java.util.Scanner;

public class Hello {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        printSquare(N);

    }

static void printSquare(int N) {
    int i=1,x=0;
    while(x<N)
    {
        x=i*i;
        if(x<=N)
            System.out.print(x+" ");
            i++;
    }
}
}


Please do comment If u have any Queries!

1 comment:

  1. #include
    void printSquare(int N)
    {
    for(int i=1;i<=N;i++)
    {
    for(int j=1;j*j<=i;j++)
    {
    if(j*j==i)
    {
    printf("%d\t",i);
    }
    }
    }
    }
    void main()
    {
    int N;
    scanf("%d",&N);
    printsquare(N);
    }

    ReplyDelete

Like