Printing numbers from 1 to n
C Program
1.For Loop
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i=1;
printf("Enter the number you want to print till:");
scanf("%d",&n);
printf("---PRINTING---\n");
for(i=1;i<=n;i++)
{
printf("%d ",i);
}
}
2.While Loop
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i=1;
printf("Enter the number you want to print till:");
scanf("%d",&n);
printf("---PRINTING---\n");
while(i <=n)
{
printf("%d ",i);
i++;
}
}
3.DO While Loop
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i=1;
printf("Enter the number you want to print till:");
scanf("%d",&n);
printf("---PRINTING---\n");
if(n!=0)
{
do
{
printf("%d ",i);
i++;
}while(i<=n);
}
}
Java Program
1.For Loop
import java.util.Scanner;
public class PrintTillN {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter Any Number:");
int n = s.nextInt();
for(int i=1;i<=n;i++)
System.out.print(i + " ");
}
}
2.While Loop
import java.util.Scanner;
public class PrintTillN {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter Any Number:");
int n = s.nextInt();
int i=1;
while(i <=n)
{
System.out.print(i + " ");
i++;
}
}
}
3.Do While Loop
import java.util.Scanner;
public class PrintTillN {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter Any Number:");
int n = s.nextInt();
int i=1;
if(n!=0)
{
do
{
System.out.print(i + " ");
i++;
}while(i<=n);
}
}
}
0 Comments:
Post a Comment