Tutorial - 1
/******************************************************************************
Program to find sum of first n odd numbers, print pa erns, func on to find area of a triangle,
func on to find the total number of digits in a number.
*******************************************************************************/
import java.u [Link];
// find the sum of first n odd numbers
public class Main
{
public sta c void main(String[] args) {
int n, sum=0, oddN=1;
Scanner sc = new Scanner([Link]);
// find sum of n odd numbers
[Link]("Enter the value of n: ");
n = [Link]();
for(int i =1; i<=n; i++){
sum = sum+oddN;
oddN= oddN+2;
}
[Link] ("Sum of first %d odd numbers = %d", n, sum);
// print the following pa ern
/*
1
22
333
.
.
*/
[Link]("\n\n Enter the value of n: ");
n = [Link]();
for(int i = 1; i<=n; i++){
for(int j=0;j<i; j++){
[Link](i+" ");
}
[Link]("\n");
}
/* print pa ern
1
12
12 3
.
*/
[Link]("\n\n Enter the value of n: ");
n = [Link]();
for(int i = 1; i<=n; i++){
for(int j=1;j<=i; j++){
[Link](j+" ");
}
[Link]("\n");
}
/* print pa ern
.
.
** * * *
** * *
** *
**
*
*/
[Link]("\n\n Enter the value of n: ");
n = [Link]();
for(int i = n; i>0; i--){
for(int j=1;j<=i; j++){
[Link]("* ");
}
[Link]("\n");
}
float base, height, area;
[Link]("\n\n Enter the value of base and height: ");
base = [Link]();
height = [Link]();
area = findArea(base, height);
[Link]("\n\nArea of the triangle="+area);
int num, count;
[Link]("\n\n Enter a number to count the digits: ");
num = [Link]();
count = countDigits(num);
[Link] ("\nThe number of digits in %d is %d", num, count);
// define a func on to find the area of triangle
public sta c float findArea(float base, float height){
return (base*height/2);
}
//define a func on to count the number of digits in a number
public sta c int countDigits(int num){
int count=0;
while(num>0){
count++;
num = num/10;
}
return count;
}
}