0% found this document useful (0 votes)
157 views62 pages

JAVA CODING AND C PROGRAMMING EXAMPLES - PROGRAMMING FOR BEGINNERS (BooksRack - Net)

This document provides examples of Java and C programming code. It includes Java programs to print "Hello World", read and print integer values, find the sum and average of numbers, print a Christmas tree, find the sum of digits in a number, calculate compound interest, and find the largest number. It also includes C programs to find the sum and average of two numbers, print ASCII values, and calculate area of a rectangle. The document is intended to provide programming examples for beginners to learn Java and C coding.

Uploaded by

Ivan Bengin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
157 views62 pages

JAVA CODING AND C PROGRAMMING EXAMPLES - PROGRAMMING FOR BEGINNERS (BooksRack - Net)

This document provides examples of Java and C programming code. It includes Java programs to print "Hello World", read and print integer values, find the sum and average of numbers, print a Christmas tree, find the sum of digits in a number, calculate compound interest, and find the largest number. It also includes C programs to find the sum and average of two numbers, print ASCII values, and calculate area of a rectangle. The document is intended to provide programming examples for beginners to learn Java and C coding.

Uploaded by

Ivan Bengin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 62

JAVA CODING AND

C
PROGRAMMING
EXAMPLES

PROGRAMMING FOR BEGINNERS


J KING
JAVA CODING EXAMPLES
JAVA PROGRAM TO PRINT 'HELLO WORLD'
PRINT DIFFERENT TYPE OF VALUES IN JAVA
READ AND PRINT AN INTEGER VALUE IN JAVA
JAVA PROGRAM TO FIND SUM AND AVERAGE
JAVA PROGRAM TO PRINT CHRISTMAS TREE
JAVA PROGRAM TO FIND SUM OF ALL DIGITS
JAVA PROGRAM TO CALCULATE COMPOUND
INTEREST
JAVA PROGRAM TO FIND LARGEST NUMBER
JAVA PROGRAM TO RUN AN APPLICATION
JAVA PROGRAM TO PRINT FIBONACCI SERIES
USING FOR LOOP TO PRINT NUMBERS FROM 1 TO N
USING WHILE LOOP TO PRINT NUMBERS FROM 1 TO N
ADDITION OF ONE DIMENSIONAL AND TWO
DIMENSIONAL ARRAYS
JAVA PROGRAM TO CONVERT DECIMAL TO BINARY
JAVA PROGRAM TO READ A FILE LINE BY LINE
JAVA PROGRAM TO GET CURRENT SYSTEM DATE
AND TIME
JAVA PROGRAM TO CALCULATE AREA OF A CIRCLE.
JAVA - PRINT FILE CONTENT, DISPLAY FILE
JAVA PROGRAM TO COPY FILES
FIND SUM OF FACTORIALS FROM 1 TO N
FIND SMALLEST ELEMENT IN AN ARRAY

C PROGRAMMING EXAMPLES
C PROGRAM TO FIND SUM AND AVERAGE OF TWO
NUMBERS.
C PROGRAM TO PRINT ASCII VALUE OF A
CHARACTER
C PROGRAM TO PRINT ALL NUMBERS FROM 1 TO N
USING GOTO STATEMENT
PROGRAM TO PRINT NUMBERS FROM 1 TO N USING
WHILE LOOP
PROGRAM TO PRINT SQUARE, CUBE AND SQUARE
ROOT
PROGRAM TO PRINT TABLE OF A GIVEN NUMBER
PROGRAM FOR LARGEST NUMBER AMONG THREE
NUMBERS
AREA OF RECTANGLE PROGRAM IN C
C PROGRAM - CONVERT FEET TO INCHES
PROGRAM TO CREATE A TEXT FILE USING FILE
HANDLING
C PROGRAM TO FIND FACTORIAL OF A NUMBER
PROGRAM TO SWAP TWO BITS OF A BYTE
PROGRAM TO SWAP TWO NUMBERS USING FOUR
DIFFERENT METHODS
AGE CALCULATOR (C PROGRAM TO CALCULATE
AGE)
C PROGRAM TO DESIGN A DIGITAL CLOCK
PROGRAM TO CALCULATE COMPOUND INTEREST
PROGRAM TO CHECK WHETHER NUMBER IS
PERFECT SQUARE OR NOT
PROGRAM TO PRINT MESSAGE WITHOUT USING ANY
SEMICOLON IN PROGRAM
SUM OF SERIES PROGRAMS / EXAMPLES USING C
JAVA CODING
EXAMPLES

PROGRAMMING FOR BEGINNERS


J KING
JAVA CODING EXAMPLES
Java program to print 'Hello
world'
SYNTAX
javac HelloWorld.java

Executing/Running java program


When you have compiled the Java program, and if it has been successfully
compiled, you can run the Java program to generate the output.
SYNTAX
java HelloWorld
PROGRAM
public class HelloWorld
{
public static void main(String []args)
{
//printing the message
System.out.println("Hello World!");
}
}
Output
Hello World!
Print different type of values in
Java
We will declare and describe some of the different types of variables in this
program, and then print them using System.out.println() method.

PROGRAM
class j2{
public static void main(String args[])
{
int num;
float b;
char c;
String s;
//integer
num = 100;
//float
b = 1.234f;
//character
c = 'A';
//string
s = "Hello Java";

System.out.println("Value of num: "+num);


System.out.println("Value of b: "+b);
System.out.println("Value of c: "+c);
System.out.println("Value of s: "+s);
}
}

Output
Value of num: 100
Value of b: 1.234
Value of c: A
Value of s: Hello Java
Read and print an integer value in
Java
Here we will learn how to take an integer input from the user and print it on
the screen, to take the input of an integer value-we use Scanner class, for this
we must include java.util. * package in our Java program.

PROGRAM
import java.util.*;

class j3
{
public static void main(String args[])
{
int a;

//declare object of Scanner Class


Scanner buf=new Scanner(System.in);
System.out.print("Enter value of a :");
/*nextInt() method of Scanner class*/
a=buf.nextInt();
System.out.println("Value of a:" +a);
}
}
Output
Enter value of a :120
Value of a:120
Java program to find sum and
average
Two integer numbers are given (input), and we have to calculate their SUM
and AVERAGE.

PROGRAM
// Find sum and average of two numbers in Java

import java.util.*;

public class Numbers {


public static void main(String args[]) {
int a, b, sum;
float avg;

Scanner buf = new Scanner(System.in);

System.out.print("Enter first number : ");


a = buf.nextInt();

System.out.print("Enter second number : ");


b = buf.nextInt();

/*Calculate sum and average*/


sum = a + b;
avg = (float)((a + b) / 2);

System.out.print("Sum : " + sum + "\nAverage : " + avg);


}
}

Output
Enter first number : 100
Enter second number : 200
Sum : 300
Average : 150.0
Java program to print Christmas
tree
Example:
*
***
*****
*******
***
*****
*******
*********
*****
*******
*********
***********
*******
*********
***********
*************
*
*
*******
PROGRAM
public class ChristmasTree
{
public static final int SEGMENTS = 4;
public static final int HEIGHT = 4;
public static void main(String[] args)
{
makeTree();
}

public static void makeTree()


{
int maxStars = 2*HEIGHT+2*SEGMENTS-3;
String maxStr = "";
for (int len=0; len < maxStars; len++)
{
maxStr+=" ";
}

for (int i=1; i <= SEGMENTS; i++)


{
for (int line=1; line <= HEIGHT; line++)
{
String starStr = "";
for (int j=1; j <= 2*line+2*i-3; j++)
{
starStr+="*";
}

for (int space=0; space <= maxStars-(HEIGHT+line+i); space++)


{
starStr = " " + starStr;
}
System.out.println(starStr);
}
}

for (int i=0; i <= maxStars/2;i++)


{
System.out.print(" ");
}
System.out.print("*\n");
for (int i=0; i <= maxStars/2;i++)
{
System.out.print(" ");
}
System.out.print("*\n");
for(int i=0; i <= maxStars/2-3;i++)
{
System.out.print(" ");
}
System.out.print("*******\n");
}
}

OUTPUT
Java program to find sum of all
digits
Provided a number and we have to use java program to find sum of all its
digits.
Example 1:
Input:
Number: 852
Output:
Sum of all digits: 15
Example 2:
Input:
Number: 256868
Output:
Sum of all digits: 35
PROGRAM
import java.util.Scanner;

public class AddDigits


{
public static void main(String args[])
{
// initializing and declaring the objects.
int num, rem=0, sum=0, temp;
Scanner scan = new Scanner(System.in);
// enter number here.
System.out.print("Enter the Number : ");
num = scan.nextInt();
// temp is to store number.
temp = num;
while(num>0)
{
rem = num%10;
sum = sum+rem;
num = num/10;
}
System.out.print("Sum of Digits of " +temp+ " is : " +sum);
}
}
Output
First run:
Enter the Number : 582
Sum of Digits of 582 is : 15

Second run:
Enter the Number : 256868
Sum of Digits of 256868 is : 35
Java program to calculate
compound interest
Given the principle, rate and time, and using java program we have to
find compound interest.
Example:
Enter Principal : 5000
Enter Rate : 5
Enter Time : 3
Amount : 5788.125000000001
Compound Interest : 788.1250000000009
PROGRAM
import java.util.Scanner;

public class CompoundInterest


{
public static void main(String args[])
{
// declare and initialize here.
double A=0,Pri,Rate,Time,t=1,CI;
// create object.
Scanner S=new Scanner(System.in);
// enter principal, rate, time here
System.out.print("Enter Principal : ");
Pri=S.nextFloat();
System.out.print("Enter Rate : ");
Rate=S.nextFloat();
System.out.print("Enter Time : ");
Time=S.nextFloat();
Rate=(1 + Rate/100);
for(int i=0;i<Time;i++)
t*=Rate;
A=Pri*t;
System.out.print("Amount : " +A);
CI=A-Pri;
System.out.print("\nCompound Interest : " +CI);
}
}
Output
First run:
Enter Principal : 5000
Enter Rate : 5
Enter Time : 3
Amount : 5788.125000000001
Compound Interest : 788.1250000000009

Second run:
Enter Principal : 10000
Enter Rate : 20
Enter Time : 5
Amount : 24883.199999999997
Compound Interest : 14883.199999999997
Java program to find largest
number
The program reads from the keyboard (three integer numbers), and selects the
largest number.
PROGRAM
//Java program to find largest number among three numbers.

import java.util.*;

class LargestFrom3
{
public static void main(String []s)
{
int a,b,c,largest;
//Scanner class to read value
Scanner sc=new Scanner(System.in);

System.out.print("Enter first number:");


a=sc.nextInt();
System.out.print("Enter second number:");
b=sc.nextInt();
System.out.print("Enter third number:");
c=sc.nextInt();

if ( a>b && a>c )


largest=a;
else if ( b>a && b>c )
largest=b;
else
largest=c;

System.out.println("Largest Number is : "+largest);

}
}
Output
Complie : javac LargestFrom3.java
Run : java LargestFrom3
Output
Enter first number:45
Enter second number:56
Enter third number:67
Largest Number is : 67
Java program to run an application
Using Java program this program can open (run) applications (Notepad,
Calculator). We use instance of Runtime.getRuntime() and method exec() to
open / run application.
PROGRAM
//Java program to run an application.

import java.util.*;

class OpenNotepad
{
public static void main(String[] args)
{
Runtime app=Runtime.getRuntime();
try
{
//open notepad
app.exec("notepad");
//open calculator
app.exec("calc");
}
catch (Exception Ex)
{
System.out.println("Error: " + Ex.toString());
}
}
}
OUTPUT
Notepad and Calculator will be opened.
Java program to print Fibonacci
Series
Fibonacci Series is a series where the term is the sum of two preceding terms.
PROGRAM
/*Java program to print Fibonacci Series.*/

import java.util.Scanner;

public class Fabonacci {

public static void main(String[] args) {

int SeriesNum ;
Scanner sc=new Scanner(System.in);

System.out.print("Enter the length of fibonacci series : ");


SeriesNum=sc.nextInt();

int[] num = new int[SeriesNum];


num[0] = 0;
num[1] = 1;
//number should be sum of last two numbers of Series
for(int i=2; i < SeriesNum; i++){
num[i] = num[i-1] + num[i-2];
}

System.out.println("fibonacci series : ");


for(int i=0; i< SeriesNum; i++){
System.out.print(num[i] + " ");
}
}

}
OUTPUT
Enter the length of fibonacci series : 10
fibonacci series :
0 1 1 2 3 5 8 13 21 34
Using for loop to print numbers
from 1 to N
PROGRAM
import java.util.Scanner;

public class Print_1_To_N_UsingFor


{
public static void main(String[] args)
{
//create object of scanner class
Scanner scanner = new Scanner(System.in);

// enter the value of " n ".


System.out.print("Enter the value n : ");

// read the value.


int n = scanner.nextInt();

System.out.println("Numbers are : " );


for(int i=1; i<=n; i++)
{
System.out.println(i);
}
}
}
Output
Enter the value n : 15
Numbers are :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Using while loop to print numbers
from 1 to N
PROGRAM
import java.util.Scanner;

public class Print_1_To_N_UsingWhile


{
public static void main(String[] args)
{
//loop counter initialisation
int i =1;

//create object of scanner class


Scanner Sc = new Scanner(System.in);

// enter the value of " n "


System.out.print("Enter the value n : ");

// read the value.


int n = Sc.nextInt();

System.out.println("Numbers are : ");

while(i<=n)
{
System.out.println(i);
i++;
}
}
}
Output
Enter the value n : 15
Numbers are :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Addition of one dimensional and
two dimensional arrays
IN JAVA PROGRAM
There are 2 programs: two one-dimensional arrays added, and two two-
dimensional arrays added

1) Addition of two one dimensional arrays in java


class AddTwoArrayClass{

public static void main(String[] args){

// Declaration and initialization of array


int a[] = {1,2,3,4,5};
int b[] = {6,7,8,9,10};

// Instantiation of third array to store results


int c[] = new int[5];

for(int i=0; i<5; ++i){


// add two array and result store in third array
c[i] = a[i] + b[i];

//Display results
System.out.println("Enter sum of "+i +"index" +" " + c[i]);
}
}
}
. Output
Enter sum of 0index 7
Enter sum of 1index 9
Enter sum of 2index 11
Enter sum of 3index 13
Enter sum of 4index 15
2) Addition of two two dimensional arrays in java
class AddTwoArrayOf2DClass{
public static void main(String[] args){
// Declaration and initialization of 2D array
int a[][] = {{1,2,3},{4,5,6}};
int b[][] = {{7,8,9},{10,11,12}};

// Instantiation of third array to store results


int c[][] = new int[2][3];
for(int i=0; i<2; ++i){
for(int j=0; j<3; ++j){
// add two array and result store in third array
c[i][j] = a[i][j] + b[i][j];
System.out.println("Enter sum of "+i + " " + j +"index" +" " + c[i]
[j]);
}
}
}
}
Output
Enter sum of 0 0index 8
Enter sum of 0 1index 10
Enter sum of 0 2index 12
Enter sum of 1 0index 14
Enter sum of 1 1index 16
Enter sum of 1 2index 18
Java program to convert Decimal to
Binary
Given an Integer (Decimal) number, and using java program we have to
convert it to Binary.
PROGRAM
// Scanner class is used for taking input from user
import java.util.Scanner;

class DecimalToBinaryConversionClass{
public static void main(String[] args){
// create Scanner class object
Scanner sc = new Scanner(System.in);

System.out.println("Enter Any Decimal Number :");


//Accept input from user
int input_decimal_num = sc.nextInt();

String binary_string = " ";

//Loop continues till input_decimal_num >0


while(input_decimal_num > 0){
//remainder add to string variable
binary_string = input_decimal_num%2 + binary_string;
input_decimal_num = input_decimal_num/2;
}
// Display Final Result
System.out.println("Conversion of decimal to binary is : " +
binary_string);
}
}
Output
Enter Any Decimal Number :
30
Conversion of decimal to binary is : 11110
Java program to read a file line by
line
Given a file, and using java program we have to read its contents line by line.

We use a file called "B.txt" for this program that is located at the "F:\" drive,
thus the file path is "F:\B.txt," and the file content is:
This is line 1
This is line 2
This is line 3
This is line 4
PROGRAM
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;

public class ReadLineByLine


{
public static void main(String[] args)
{
// create object of scanner class.
Scanner Sc=new Scanner(System.in);
// enter file name.
System.out.print("Enter the file name:");
String sfilename=Sc.next();
Scanner Sc1= null;
FileInputStream fis=null;
try
{
FileInputStream FI=new FileInputStream(sfilename);
Sc1=new Scanner(FI);

// this will read data till the end of data.


while(Sc1.hasNext())
{
String data=Sc1.nextLine();

// print the data.


System.out.print("The file data is : " +data);
}
}
catch(IOException e)
{
System.out.println(e);
}
}
Output
Enter the file name: F:/B.txt
This is line 1
This is line 2
This is line 3
This is line 4
Java program to get current system
date and time
PROGRAM
//program to get system date and time
import java.util.Date;

public class GetDateTime


{
public static void main(String args[])
{
// instance of Date class
Date date = new Date();

// get date, month and year


System.out.println(date.getDate()+"/"+(date.getMonth()+1)+"/"+
(date.getYear()-100));

// get complete date and time


System.out.println(date.toString());

// get time only


System.out.println(date.getHours()+":"+date.getMinutes()+":"+date.getSeconds(

}
OUTPUT
14/8/20
Thu Aug 14 21:29:07 GMT 2020
21:29:7
Java program to Calculate Area of
a Circle.
This program reads circle radius and calculates Area of the circle
PROGRAM
//Java program to Calculate Area of a Circle.

import java.util.Scanner;

public class AreaCircle {

public static void main(String[] args) {

double radius;
Scanner sc=new Scanner(System.in);

// input radius of circle


System.out.print("Enter the Radius of Circle : ");
radius=sc.nextDouble();

// circle area is pie * radius square


double area=3.14*radius*radius;

System.out.print("Area of Circle : "+area);

}
}
OUTPUT
Enter the Radius of Circle : 12.5
Area of Circle : 490.625
Java - Print File Content, Display
File
Using Java program we will print the file size and file information in this
code snippet.
PROGRAM
//Java - Print File Content, Display File using Java Program.

import java.io.*;

public class PrintFile{


public static void main(String args[]) throws IOException{
File fileName = new File("d:/sample.txt");

FileInputStream inFile = new FileInputStream("d:/sample.txt");


int fileLength =(int)fileName.length();

byte Bytes[]=new byte[fileLength];

System.out.println("File size is: " + inFile.read(Bytes));

String file1 = new String(Bytes);


System.out.println("File content is:\n" + file1);

//close file
inFile.close();
}
}
OUTPUT
File size is: 22
File content is:
This is a sample file.
Java program to copy files
This program copies files in Java.
//Java program to copy file.

import java.io.*;

public class FileCopy {


public static void main(String args[]) {
try {
//input file
FileInputStream sourceFile =new FileInputStream (args[0]);
//output file
FileOutputStream targetFile =new FileOutputStream(args[1]);

// Copy each byte from the input to output


int byteValue;
//read byte from first file and write it into second line
while((byteValue = sourceFile.read()) != -1)
targetFile.write(byteValue);

// Close the files!!!


sourceFile.close();
targetFile.close();

System.out.println("File copied successfully");


}
// If something went wrong, report it!
catch(IOException e) {
System.out.println("Exception: " + e.toString());
}
}
}
OUTPUT
Compile: javac FileCopy.java
Run: java FileCopy file1.txt file2.txt
File copied successfully
Find sum of factorials from 1 to N
Example:
Input: 3
Output: 9
Explanation:
1! + 2! + 3! = 1 + 2 + 6 = 9

Input: 5
Output: 152
Explanation:
1! + 2! + 3! + 4! + 5!
= 1+2+6+24+120
= 153
PROGRAM
import java.util.Scanner;

public class SumOfFactorial


{
public static void main(String[] args)
{
// create scanner class object.
Scanner sc = new Scanner(System.in);
// enter the number.
System.out.print("Enter number : ");
int n = sc.nextInt();

int total=0;

int i=1;
// calculate factorial here.
while(i <= n)
{
int factorial=1;
int j=1;
while(j <= i)
{
factorial=factorial*j;
j = j+1;
}
// calculate sum of factorial of the number.
total = total + factorial;
i=i+1;
}
// print the result here.
System.out.println("Sum : " + total);
}
}

Output
First run:
Enter number : 3
Sum : 9

Second run:
Enter number : 5
Sum : 153
Find smallest element in an array
Example:
Input:
Enter number of elements: 4
Input elements: 45, 25, 69, 40

Output:
Smallest element in: 25
PROGRAM
import java.util.Scanner;
public class ExArrayFindMinimum
{
public static void main(String[] args)
{
// Intialising the variables
int n, min;
Scanner Sc = new Scanner(System.in);

// Enter the number of elements.


System.out.print("Enter number of elements : ");
n = Sc.nextInt();

// creating an array.
int a[] = new int[n];

// enter array elements.


System.out.println("Enter the elements in array : ");
for (int i = 0; i < n; i++)
{
a[i] = Sc.nextInt();
}

for (int i = 0; i < n; i++)


{
for (int j = i + 1; j < n; j++)
{
if (a[i] > a[j])
{
min = a[i];
a[i] = a[j];
a[j] = min;
}
}
}
System.out.println("The Smallest element in the array is :"+a[0]);
}
}
Output
Enter number of elements : 4
Enter the elements in array :
45
25
69
40
The Smallest element in the array is :25
C PROGRAMMING
EXAMPLES

PROGRAMMING FOR BEGINNERS


J KING
C PROGRAMMING EXAMPLES
C program to find SUM and
AVERAGE of two numbers.
Sum and Average of two numbers
PROGRAM
/* c program find sum and average of two numbers*/
#include <stdio.h>

int main()
{
int a,b,sum;
float avg;

printf("Enter first number :");


scanf("%d",&a);
printf("Enter second number :");
scanf("%d",&b);

sum=a+b;
avg= (float)(a+b)/2;

printf("\nSum of %d and %d is = %d",a,b,sum);


printf("\nAverage of %d and %d is = %f",a,b,avg);

return 0;
}
Output
Enter first number :10
Enter second number :15

Sum of 10 and 15 is = 25
Average of 10 and 15 is = 12.500000
C program to print ASCII value of
a character
PROGRAM
#include <stdio.h>

int main()
{
char ch;

//input character
printf("Enter the character: ");
scanf("%c",&ch);

printf("ASCII is = %d\n", ch);


return 0;
}
Output
First run:
Enter the character: a
ASCII is = 97

Second run:
Enter the character: A
ASCII is = 65
C program to print all numbers
from 1 to N using goto statement
PROGRAM
#include <stdio.h>

int main()
{

int count,n;

//read value of N
printf("Enter value of n: ");
scanf("%d",&n);

//initialize count with 1


count =1;

start: //label
printf("%d ",count);
count++;

if(count<=n)
goto start;

return 0;
}
Output
Enter value of n: 10
1 2 3 4 5 6 7 8 9 10
Program to print numbers from 1 to
N using while loop
PROGRAM
#include <stdio.h>

int main()
{

//loop counter declaration


int number;
//variable to store limit /N
int n;
//assign initial value
//from where we want to print the numbers
number =1;
//input value of N
printf("Enter the value of N: ");
scanf("%d",&n);
//print statement
printf("Numbers from 1 to %d: \n",n);
//while loop, that will print numbers
//from 1 to n
while(number <= n)
{
//printing the numbers
printf("%d ",number);
//increasing loop counter by 1
number++;
}
return 0;
}
Output
Enter the value of N: 25
Numbers from 1 to 25:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
16 17 18 19 20 21 22 23 24 25
Program to print Square, Cube and
Square Root
PROGRAM
/*C program to print square, cube and square root of all numbers from 1 to
N.*/

#include <stdio.h>
#include <math.h>

int main()
{
int i,n;

printf("Enter the value of N: ");


scanf("%d",&n);

printf("No Square Cube Square Root\n",n);


for(i=1;i<=n;i++)
{
printf("%d \t %ld \t %ld \t %.2f\n",i,(i*i),(i*i*i),sqrt((double)i));
}

return 0;
}
Program to print table of a given
number
PROGRAM
#include<stdio.h>

int main()
{
//declare variable
int count,t,r;

//Read value of t
printf("Enter number: ");
scanf("%d",&t);

count=1;

start:
if(count<=10)
{
//Formula of table
r=t*count;
printf("%d*%d=%d\n",t,count,r);
count++;
goto start;
}

return 0;
}
Output
Enter number: 10
10*1=10
10*2=20
10*3=30
10*4=40
10*5=50
10*6=60
10*7=70
10*8=80
10*9=90
10*10=100
Program for Largest Number
among three numbers
PROGRAM
/* c program to find largest number among 3 numbers*/
#include <stdio.h>

int main()
{
int a,b,c;
int largest;

printf("Enter three numbers (separated by space):");


scanf("%d%d%d",&a,&b,&c);

if(a>b && a>c)


largest=a;
else if(b>a && b>c)
largest=b;
else
largest=c;

printf("Largest number is = %d",largest);

return 0;
}
Output
First Run:
Enter three numbers (separated by space): 10 20 30
Largest number is = 30

Second Run:
Enter three numbers (separated by space):10 30 20
Largest number is = 30

Third Run:
Enter three numbers (separated by space):30 10 20
Largest number is = 30

Fourth Run:
Enter three numbers (separated by space):30 30 30
Largest number is = 30
Area of rectangle program in c
PROGRAM
/*C program to find area of a rectangle.*/

#include <stdio.h>

int main()
{
float l,b,area;

printf("Enter the value of length: ");


scanf("%f",&l);

printf("Enter the value of breadth: ");


scanf("%f",&b);

area=l*b;

printf("Area of rectangle: %f\n",area);

return 0;
}
Output
Enter the value of length: 1.25
Enter the value of breadth: 3.15
Area of rectangle: 3.937500
C program - Convert Feet to Inches
PROGRAM
#include<stdio.h>

int main()
{
int feet,inches;
printf("Enter the value of feet: ");
scanf("%d",&feet);
//converting into inches
inches=feet*12;
printf("Total inches will be: %d\n",inches);
return 0;
}
Output
Enter the value of feet: 15
Total inches will be: 180
Program to create a text file using
file handling
PROGRAM
#include< stdio.h >
int main()
{

FILE *fp; /* file pointer*/


char fName[20];

printf("Enter file name to create :");


scanf("%s",fName);

/*creating (open) a file, in “w”: write mode*/


fp=fopen(fName,"w");
/*check file created or not*/
if(fp==NULL)
{
printf("File does not created!!!");
exit(0); /*exit from program*/
}

printf("File created successfully.");


return 0;
}
Output
Run 1:
Enter file name to create : file1.txt
File created successfully.

Run 2:
Enter file name to create : d:/file1.txt
File created successfully.

“file will be created in d: drive”.

Run 3:
Run 1:
Enter file name to create : h:/file1.txt
File does not created!!!
C program to find factorial of a
number
Factorial is an integer product, with all of it below integer till 1. Represent
factorial in mathematical by ! Sign.
Example:
Factorial 5 is:
5! = 120 [That is equivalent to 5*4*3*2*1 =120]

Simple program
/*C program to find factorial of a number.*/

#include <stdio.h>

int main()
{
int num,i;
long int fact;

printf("Enter an integer number: ");


scanf("%d",&num);

/*product of numbers from num to 1*/


fact=1;
for(i=num; i>=1; i--)
fact=fact*i;

printf("\nFactorial of %d is = %ld",num,fact);

return 0;
}
Output
Enter an integer number: 7
Factorial of 7 is = 5040
User Define Function
/*Using Function: C program to find factorial of a number.*/

#include <stdio.h>

/* function : factorial, to find factorial of a given number*/

long int factorial(int n)


{
int i;
long int fact=1;

if(n==1) return fact;

for(i=n;i>=1;i--)
fact= fact * i;

return fact;
}

int main()
{
int num;

printf("Enter an integer number :");


scanf("%d",&num);

printf("\nFactorial of %d is = %ld",num,factorial(num));

return 0;
}
Program to swap two bits of a byte
Example:
Input number: 0x0A (Hexadecimal)
Binary of input number: 0000 1010
After swapping of bit 1 and 2
Binary will be: 0000 1100
Output number will be: 0x0C (Hexadecimal)

PROGRAM
#include <stdio.h>

/*
Program to swap 1st and 2nd bit of hexadecimal value stored in data variable
*/

int main()
{
unsigned char data = 0xA; // Assiging hexadecimal value

// Get 1st bit from data


unsigned char bit_1 = (data >> 1) & 1;

// Get 2nd bit from data


unsigned char bit_2 = (data >> 2) & 1;

// Get XOR of bit_1 and bit_2


unsigned char xor_of_bit = bit_1 ^ bit_2;

printf("After swapping the bits, data value is: %2X", data ^ (xor_of_bit
<< 1 | xor_of_bit << 2));

return 0;
}

Output
After swapping the bits, data value is: C
Program to swap two numbers
using four different methods
METHODS
1. Using third variable
2. Without using third variable
3. Using X-OR operator
4. Using simple statement

PROGRAM
//C program to swap two numbers using four different methods.

#include <stdio.h>

int main()
{
int a,b,t;
printf(" Enter value of A ? ");
scanf("%d",&a);
printf(" Enter value of B ? ");
scanf("%d",&b);

printf("\n Before swapping : A= %d, B= %d",a,b);

/****first method using third variable*/


t=a;
a=b;
b=t;
printf("\n After swapping (First method) : A= %d, B= %d\n",a,b);

/****second method without using third variable*/


a=a+b;
b=a-b;
a=a-b;
printf("\n After swapping (second method): A= %d, B= %d\n",a,b);

/****Third method using X-Or */


a^=b;
b^=a;
a^=b;
printf("\n After swapping (third method) : A= %d, B= %d\n",a,b);

/****fourth method (single statement)*/


a=a+b-(b=a);
printf("\n After swapping (fourth method): A= %d, B= %d\n",a,b);

return 0;
}
Output
Enter value of A ? 100
Enter value of B ? 200

Before swapping : A= 100, B= 200


After swapping (First method) : A= 200, B= 100

After swapping (second method): A= 100, B= 200

After swapping (third method) : A= 200, B= 100

After swapping (fourth method): A= 100, B= 200


Age Calculator (C program to
calculate age)
PROGRAM
/*Age Calculator (C program to calculate age).*/

#include <stdio.h>
#include <time.h>

/*check given year is leap year or not*/


int isLeapYear(int year, int mon)
{
int flag = 0;
if (year % 100 == 0)
{
if (year % 400 == 0)
{
if (mon == 2)
{
flag = 1;
}
}
}
else if (year % 4 == 0)
{
if (mon == 2)
{
flag = 1;
}
}
return (flag);
}

int main()
{

int DaysInMon[] = {31, 28, 31, 30, 31, 30,


31, 31, 30, 31, 30, 31};
int days, month, year;
char dob[100];
time_t ts;
struct tm *ct;

/* enter date of birth */


printf("Enter your date of birth (DD/MM/YYYY): ");
scanf("%d/%d/%d",&days,&month, &year);

/*get current date.*/


ts = time(NULL);
ct = localtime(&ts);

printf("Current Date: %d/%d/%d\n",


ct->tm_mday, ct->tm_mon + 1, ct->tm_year + 1900);

days = DaysInMon[month - 1] - days + 1;

/* leap year checking*/


if (isLeapYear(year, month))
{
days = days + 1;
}

/* calculating age in no of days, years and months */


days = days + ct->tm_mday;
month = (12 - month) + (ct->tm_mon);
year = (ct->tm_year + 1900) - year - 1;

/* checking for leap year feb - 29 days */


if (isLeapYear((ct->tm_year + 1900), (ct->tm_mon + 1)))
{
if (days >= (DaysInMon[ct->tm_mon] + 1))
{
days = days - (DaysInMon[ct->tm_mon] + 1);
month = month + 1;
}
}
else if (days >= DaysInMon[ct->tm_mon])
{
days = days - (DaysInMon[ct->tm_mon]);
month = month + 1;
}

if (month >= 12)


{
year = year + 1;
month = month - 12;
}

/* print age */
printf("\n## Hey you are %d years %d months and %d days old. ##\n",
year, month, days);

return 0;
}
C program to design a digital clock
PROGRAM
/*C program to design a digital clock.*/

#include <stdio.h>
#include <time.h> //for sleep() function
#include <unistd.h>
#include <stdlib.h>

int main()
{
int hour, minute, second;

hour=minute=second=0;

while(1)
{
//clear output screen
system("clear");

//print time in HH : MM : SS format


printf("%02d : %02d : %02d ",hour,minute,second);

//clear output buffer in gcc


fflush(stdout);

//increase second
second++;

//update hour, minute and second


if(second==60){
minute+=1;
second=0;
}
if(minute==60){
hour+=1;
minute=0;
}
if(hour==24){
hour=0;
minute=0;
second=0;
}

sleep(1); //wait till 1 second


}

return 0;
}
Program to calculate compound
interest
PROGRAM
/*C program to calculate compound interest.*/

#include <stdio.h>
#include <math.h>

int main()
{
float principal, rate, year, ci;

printf("Enter principal: ");


scanf("%f", &principal);

printf("Enter rate: ");


scanf("%f", &rate);

printf("Enter time in years: ");


scanf("%f", &year);

//calculate compound interest

ci=principal*((pow((1+rate/100),year)-1));

printf("Compound interest is: %f\n",ci);

return 0;
}
Output
Enter principal: 10000
Enter rate: 10.25
Enter time in years: 5
Compound interest is: 6288.943359
Program to check whether number
is Perfect Square or not
PROGRAM
/*C program to check number is perfect square or not.*/

#include <stdio.h>
#include <math.h>

int main()
{
int num;
int iVar;
float fVar;

printf("Enter an integer number: ");


scanf("%d",&num);

fVar=sqrt((double)num);
iVar=fVar;

if(iVar==fVar)
printf("%d is a perfect square.",num);
else
printf("%d is not a perfect square.",num);

return 0;
}

BY User Define Function


/*C program to check number is perfect square or not.*/

#include <stdio.h>
#include <math.h>

/*function definition*/
int isPerfectSquare(int number)
{
int iVar;
float fVar;

fVar=sqrt((double)number);
iVar=fVar;

if(iVar==fVar)
return 1;
else
return 0;
}
int main()
{
int num;
printf("Enter an integer number: ");
scanf("%d",&num);

if(isPerfectSquare(num))
printf("%d is a perfect square.",num);
else
printf("%d is not a perfect square.",num);

return 0;
}

Output
First Run:
Enter an integer number: 16
16 is a perfect square.

Second Run:
Enter an integer number: 26
26 is not a perfect square.
Program to print message without
using any semicolon in program
PROGRAM
/*Program to print "Hello C" using if and else
statement both.*/

#include <stdio.h>

int main()
{

if(!printf("Hello "))
;
else
printf("C\n");

return 0;
}
OUTPUT
Hello C
Sum of Series Programs / Examples
using C
1. 1+2+3+4+..N<

PROGRAM
/*This program will print the sum of all natural numbers from 1 to N.*/

#include<stdio.h>

int main()
{
int i,N,sum;

/*read value of N*/


printf("Enter the value of N: ");
scanf("%d",&N);

/*set sum by 0*/


sum=0;

/*calculate sum of the series*/


for(i=1;i<=N;i++)
sum= sum+ i;

/*print the sum*/

printf("Sum of the series is: %d\n",sum);

return 0;
}
Enter the value of N: 100
Sum of the series is: 5050

You might also like