Anda di halaman 1dari 16

15 Programming Languages

1. Java- is a class-based, object-oriented programming language developed by Sun


Microsystems in the 1990s. It's one of the most in-demand programming languages, a
standard for enterprise software, web-based content, games and mobile apps, as well as
the Android operating system. Java is designed to work across multiple software platforms,
meaning a program written on Mac OS X, for example, could also run on Windows.

Sample Codes
#1
import java.util.Scanner;
class SwapNumbers
{
public static void main(String args[])
{
int x, y, temp;
System.out.println("Enter x and y");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
System.out.println("Before Swapping\nx = "+x+"\ny = "+y);
temp = x;
x = y;
y = temp;
System.out.println("After Swapping\nx = "+x+"\ny = "+y);
}

#2

import java.util.Scanner;
class ReverseNumberWhile
{
public static void main(String args[])
{
int num=0;
int reversenum =0;
System.out.println("Input your number and press enter: ");
//This statement will capture the user input
Scanner in = new Scanner(System.in);
//Captured input would be stored in number num
num = in.nextInt();
//While Loop: Logic to find out the reverse number
while( num != 0 )
{
reversenum = reversenum * 10;
reversenum = reversenum + num%10;
num = num/10;
}
System.out.println("Reverse of input number is: "+reversenum);
}

2. C Language- A general-purpose, imperative programming language developed in the

early '70s, C is the oldest and most widely used language, providing the building blocks for
other popular languages, such as C#, Java, JavaScript and Python. C is mostly used for
implementing operating systems and embedded applications.

Sample Codes
#1
#include <stdio.h>
int main()
{
int firstNumber, secondNumber, sumOfTwoNumbers;
printf("Enter two integers: ");
// Two integers entered by user is stored using scanf() function
scanf("%d %d",&firstNumber, &secondNumber);
// sum of two numbers in stored in variable sumOfTwoNumbers
sumOfTwoNumbers = firstNumber + secondNumber;
// Displays sum
printf("%d + %d = %d", firstNumber, secondNumber, sumOfTwoNumbers);
}

return 0;

#2
#include <stdio.h>
int main()
{
double firstNumber, secondNumber, temporaryVariable;
printf("Enter first number: ");
scanf("%lf", &firstNumber);
printf("Enter second number: ");
scanf("%lf",&secondNumber);
// Value of firstNumber is assigned to temporaryVariable
temporaryVariable = firstNumber;
// Value of secondNumber is assigned to firstNumber
firstNumber = secondNumber;
// Value of temporaryVariable (which contains the initial value of firstNumber) is
assigned to secondNumber
secondNumber = temporaryVariable;
printf("\nAfter swapping, firstNumber = %.2lf\n", firstNumber);
printf("After swapping, secondNumber = %.2lf", secondNumber);
}

return 0;

3. C++- is an intermediate-level language with object-oriented programming features,

originally designed to enhance the C language. C++ powers major software like Firefox,
Winamp and Adobe programs. It's used to develop systems software, application software,
high-performance server and client applications and video games.

Sample Codes
#1
// function example
#include <iostream>
using namespace std;
int addition (int a, int b)
{
int r;
r=a+b;
return r;
}
int main ()
{
int z;
z = addition (5,3);
cout << "The result is " << z;
}

#2
// my first pointer
#include <iostream>
using namespace std;
int main ()
{
int firstvalue, secondvalue;
int * mypointer;
mypointer = &firstvalue;
*mypointer = 10;
mypointer = &secondvalue;
*mypointer = 20;
cout << "firstvalue is " << firstvalue << '\n';
cout << "secondvalue is " << secondvalue << '\n';
return 0;
}

4. C#- Pronounced "C-sharp," C# is a multi-paradigm language developed by Microsoft as

part of its .NET initiative. Combining principles from C and C++, C# is a general-purpose
language used to develop software for Microsoft and Windows platforms.

Sample Codes
#1
// Hello1.cs
// arguments: A B C D
using System;
public class Hello3
{
public static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
Console.WriteLine("You entered the following {0} command line arguments:",
args.Length );
for (int i=0; i < args.Length; i++)
{
Console.WriteLine("{0}", args[i]);
}
}
}

#2
* C# Program to get the Length of the Array
*/
using System;
class Program
{
static void Main()
{

}
}

int[] arrayA = new int[5];


int lengthA = arrayA.Length;
Console.WriteLine("Length of ArrayA : {0}", +lengthA);
long longLength = arrayA.LongLength;
Console.WriteLine("Length of the LongLength Array : {0}",longLength);
int[,] twoD = new int[5, 10];
Console.WriteLine("The Size of 2D Array is : {0}",twoD.Length);
Console.ReadLine();

5. Objective-C- is a general-purpose, object-oriented programming language used by the

Apple operating system. It powers Apple's OS X and iOS, as well as its APIs, and can be
used to create iPhone apps, which has generated a huge demand for this once-outmoded
programming language.

Sample Codes
#1
#include <stdio.h>
@implementation Greeter
- (void)greet
{
printf("Hello, World!\n");
}
@end
#include <stdlib.h>
int main(void)
{
id myGreeter;
myGreeter=[Greeter new];
[myGreeter greet];
[myGreeter free];
return EXIT_SUCCESS;
}

#2

#include <stdio.h>
#include "Integers.h"
@implementation Integers
- (void)integers
{
short int i;
short int j;
float s;
i = 1;
j = 5;
s = (float) i / j;
if (s < 0)
printf("s=%f is less then 0\n", s);
else if (s == 0)
printf("s=%f is equal to 0\n", s);
else
printf("s=%f is greater then 0\n", s);
}
@end

6. PHP- Hypertext Processor) is a free, server-side scripting language designed for dynamic

websites and app development. It can be directly embedded into an HTML source
document rather than an external file, which has made it a popular programming language
for web developers. PHP powers more than 200 million websites, including Word press,
Digg and Facebook.

Sample Codes
#1
<html>

<head>
<title>A File Upload Script</title>
</head>
<body>
<div>
<?php
if ( isset( $_FILES['fupload'] ) ) {
print
print
print
print
print

"name: ".
$_FILES['fupload']['name']
."<br />";
"size: ".
$_FILES['fupload']['size'] ." bytes<br />";
"temp name: ".$_FILES['fupload']['tmp_name'] ."<br />";
"type: ".
$_FILES['fupload']['type']
."<br />";
"error: ". $_FILES['fupload']['error']
."<br />";

if ( $_FILES['fupload']['type'] == "image/gif" ) {
$source = $_FILES['fupload']['tmp_name'];
$target = "upload/".$_FILES['fupload']['name'];
move_uploaded_file( $source, $target );// or die ("Couldn't copy");
$size = getImageSize( $target );
$imgstr = "<p><img width=\"$size[0]\" height=\"$size[1]\" ";
$imgstr .= "src=\"$target\" alt=\"uploaded image\" /></p>";
print $imgstr;
}
}
?>
</div>
<form enctype="multipart/form-data"
action="<?php print $_SERVER['PHP_SELF']?>" method="post">
<p>
<input type="hidden" name="MAX_FILE_SIZE" value="102400" />
<input type="file" name="fupload" /><br/>
<input type="submit" value="upload!" />
</p>
</form>
</body>
</html
>

#2
<?
function bin2text($bin_str)
{
$text_str = '';
$chars = explode("\n", chunk_split(str_replace("\n", '', $bin_str), 8));
$_I = count($chars);
for($i = 0; $i < $_I; $text_str .= chr(bindec($chars[$i])), $i );
return $text_str;
}
function text2bin($txt_str)
{
$len = strlen($txt_str);
$bin = '';
for($i = 0; $i < $len; $i )
{
$bin .= strlen(decbin(ord($txt_str[$i]))) < 8 ? str_pad(decbin(ord($txt_str[$i])), 8, 0,
STR_PAD_LEFT) : decbin(ord($txt_str[$i]));
}
return $bin;
}
print text2bin('How are you gentlements?');

7. Python- is a high-level, server-side scripting language for websites and mobile apps. It's

considered a fairly easy language for beginners due to its readability and compact syntax,
meaning developers can use fewer lines of code to express a concept than they would in
other languages. It powers the web apps for Instagram, Pinterest and Rdio through its
associated web framework, Django, and is used by Google, Yahoo! and NASA.

Sample Code
#1

# This program adds two numbers provided by the user


# Store input numbers
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
# Add two numbers
sum = float(num1) + float(num2)
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

#2

# Python Program to find the area of triangle


# Three sides of the triangle a, b and c are provided by the user
a = float(input('Enter first side: '))
b = float(input('Enter second side: '))
c = float(input('Enter third side: '))
# calculate the semi-perimeter
s = (a + b + c) / 2
# calculate the area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)

8. Ruby- a dynamic, object-oriented scripting language for developing websites and mobile

apps, Ruby was designed to be simple and easy to write. It powers the Ruby on Rails (or
Rails) framework, which is used on Scribd, GitHub, Groupon and Shopify. Like Python, Ruby
is considered a fairly user-friendly language for beginners.

Sample Code
#1

#2

a = [ 45, 3, 19, 8 ]
b = [ 'sam', 'max', 56, 98.9, 3, 10,
'jill' ]
print (a + b).join(' '), "\n"
print a[2], " ", b[4], " ", b[-2], "\n"
print a.sort.join(' '), "\n"
a << 57 << 9 << 'phil'
print "A: ", a.join(' '), "\n"

# Simple for loop using a range.


for i in (1..4)
print i," "
end
print "\n"

b << 'alex' << 48 << 220


print "B: ", b.join(' '), "\n"
print "pop: ", b.pop, "\n"
print "shift: ", b.shift, "\n"
print "C: ", b.join(' '), "\n"
b.delete_at(2)
b.delete('alex')
print "D: ", b.join(' '), "\n"

for i in (1...4)
print i," "
end
print "\n"
# Running through a list (which is what
they do).
items = [ 'Mark', 12, 'goobers', 18.45 ]
for it in items
print it, " "
end
print "\n"
# Go through the legal subscript values of
an array.
for i in (0...items.length)
print items[0..i].join(" "), "\n"
end

9. JavaScript- is a client and server-side scripting language developed by Netscape that

derives much of its syntax from C. It can be used across multiple web browsers and is
considered essential for developing interactive or animated web functions. It is also used
in game development and writing desktop applications. JavaScript interpreters are
embedded in Google's Chrome extensions, Apple's Safari extensions, Adobe Acrobat and
Reader, and Adobe's Creative Suite.

Sample Code
#1
// Create three variables to store the information needed.
var price;
var quantity;
var total;
// Assign values to the price and quantity variables.
price = 5;
quantity = 14;
// Calculate the total by multiplying the price by quantity.
total = price * quantity;
// Get the element with an id of cost.
var el = document.getElementById('cost');
el.textContent = '$' + total;

#2
var compare = {
name: function(a, b) {
a = a.replace(/^the /i, '');
b = b.replace(/^the /i, '');

//
//
//
//

Declare compare object


Add a method called name
Remove The from start of parameter
Remove The from start of parameter

if (a < b) {
return -1;
} else {
return a > b ? 1 : 0;
}

//
//
//
//
//

If value a is less than value b


Return -1
Otherwise
If a is greater than b return 1 OR
if they are the same return 0

},
duration: function(a, b) {
a = a.split(':');
b = b.split(':');

// Add a method called duration


// Split the time at the colon
// Split the time at the colon

a = Number(a[0]) * 60 + Number(a[1]); // Convert the time to seconds


b = Number(b[0]) * 60 + Number(b[1]); // Convert the time to seconds
return a - b;
},
date: function(a, b) {
a = new Date(a);
b = new Date(b);

// Return a minus b
// Add a method called date
// New Date object to hold the date
// New Date object to hold the date

return a - b;

// Return a minus b

};
$('.sortable').each(function() {
var $table = $(this);
var $tbody = $table.find('tbody');
var $controls = $table.find('th');
var rows = $tbody.find('tr').toArray();
$controls.on('click', function() {
var $header = $(this);
var order = $header.data('sort');
var column;

//
//
//
//

This sortable table


Store table body
Store table headers
Store array containing rows

//
//
//
//

When user clicks on a header


Get the header
Get value of data-sort attribute
Declare variable called column

// If selected item has ascending or descending class, reverse contents


if ($header.is('.ascending') || $header.is('.descending')) {
$header.toggleClass('ascending descending');
// Toggle to other class
$tbody.append(rows.reverse());
// Reverse the array
} else {
// Otherwise perform a sort
$header.addClass('ascending');
// Add class to header
// Remove asc or desc from all other headers
$header.siblings().removeClass('ascending descending');
if (compare.hasOwnProperty(order)) { // If compare object has method
column = $controls.index(this);
// Search for columns index no
rows.sort(function(a, b) {
a = $(a).find('td').eq(column).text();
b = $(b).find('td').eq(column).text();
return compare[order](a, b);
});
}

//
//
//
//

Call sort() on rows array


Get text of column in row a
Get text of column in row b
Call compare method

$tbody.append(rows);

}
});
});

10. SQL- is a special-purpose language for managing data in relational database

management systems. It is most commonly used for its "Query" function, which searches
informational databases. SQL was standardized by the American National Standards
Institute (ANSI) and the International Organization for Standardization (ISO) in the 1980s.

Sample Code
#1

DECLARE
x NUMBER := 100;
BEGIN
FOR i IN 1..10 LOOP
IF MOD(i,2) = 0 THEN
-- i is even
INSERT INTO temp VALUES (i, x, 'i is even');
ELSE
INSERT INTO temp VALUES (i, x, 'i is odd');
END IF;
x := x + 100;
END LOOP;
COMMIT;
END;

#2
DECLARE
acct_balance NUMBER(11,2);
acct
CONSTANT NUMBER(4) := 3;
debit_amt
CONSTANT NUMBER(5,2) := 500.00;
BEGIN
SELECT bal INTO acct_balance FROM accounts
WHERE account_id = acct
FOR UPDATE OF bal;
IF acct_balance >= debit_amt THEN
UPDATE accounts SET bal = bal - debit_amt
WHERE account_id = acct;
ELSE
INSERT INTO temp VALUES
(acct, acct_balance, 'Insufficient funds');
-- insert account, current balance, and message
END IF;
COMMIT;
END;

11. Perl- is also a well-accepted programming language that offers distinct tools for various

obscure setbacks such as system programming. Though this programming language is a


bit puzzling, but it is really a strong one that you can learn for this year, and renew your
knowledge. Perl is mainly used for sites and web app expansion, desktop app development
and system administration, and test automation that can be applied for testing databases,
web apps, networking devices, and many more.

Sample Code
#1

#2

# Simple array constructs.


@fred = ("How", "are", "you", "today?");
print "\@fred contains (@fred).\n";

use strict;

$mike = $fred[1];
print "$mike $fred[3]\n";
# The array name in a scalar context gives
the size.
$fredsize = @fred;
print '@fred has ', "$fredsize
elements.\n";
# The $#name gives the max subscript (size
less one).
print "Max sub is $#fred\n";

sub parg {
my($a, $b, $c) = @_;
print "A: $a $b $c\n";
print "B: $#_ [@_]\n\n";
}
parg("Hi", "there", "fred");
my @a1 = ("Today", "is", "the", "day");
parg(@a1);
parg("Me", @a1, "too");
my $joe = "sticks";
&parg ("Pooh $joe");
parg;
my @a2 = ("Never", "Mind");

parg @a2, "Boris", @a1, $joe;

12. Swift- is reflected upon as the trendiest program language for expanding apps for Apple
products. This language can be utilized by you for building up apps for iOS activated
devices and Apples MAC in quick and simple method. When you are keen to expand a
superb iOS application, then it is better for you to gain knowledge of Swift programming
language.

Sample Code
#1

import Cocoa
var someInts = [Int]()
someInts.append(20)
someInts.append(30)
someInts += [40]
// Modify last element
someInts[2] = 50
var someVar = someInts[0]
println( "Value of first element is \(someVar)" )
println( "Value of second element is \(someInts[1])" )
println( "Value of third element is \(someInts[2])" )

#2

func ls(array: [Int]) -> (large: Int, small: Int) {


var lar = array[0]
var sma = array[0]
for i in array[1..<array.count] {
if i < sma {
sma = i
}else if i > lar {
lar = i
}
}
return (lar, sma)
}
let num = ls([40,12,-5,78,98])
println("Largest number is: \(num.large) and smallest number is: \(num.small)")

13. COBOL- is primarily used in business, finance, and administrative systems for
companies and governments.

Sample Code
#1
IDENTIFICATION DIVISION.
PROGRAM-ID. AcceptAndDisplay.
AUTHOR. Michael Coughlan.
* Uses the ACCEPT and DISPLAY verbs to
accept a student record
* from the user and display some of the
fields. Also shows how
* the ACCEPT may be used to get the system
date and time.
* The YYYYMMDD in "ACCEPT CurrentDate
FROM DATE YYYYMMDD."
* is a format command that ensures that
the date contains a
* 4 digit year. If not used, the year
supplied by the system will
* only contain two digits which may cause
a problem in the year 2000.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 StudentDetails.
02 StudentId
PIC
02 StudentName.
03 Surname
PIC
03 Initials
PIC
02 CourseCode
PIC
02 Gender
PIC
* YYMMDD
01 CurrentDate.
02 CurrentYear
02 CurrentMonth
02 CurrentDay

9(7).
X(8).
XX.
X(4).
X.

PIC 9(4).
PIC 99.
PIC 99.

* YYDDD
01 DayOfYear.
02 FILLER
02 YearDay

PIC 9(4).
PIC 9(3).

* HHMMSSss
s = S/100
01 CurrentTime.
02 CurrentHour
PIC 99.
02 CurrentMinute
PIC 99.
02 FILLER
PIC 9(4).
PROCEDURE DIVISION.
Begin.
DISPLAY "Enter student details using
template below".
DISPLAY "Enter ID,Surname,Initials,CourseCode,Gender"
DISPLAY "SSSSSSSNNNNNNNNIICCCCG".
ACCEPT StudentDetails.
ACCEPT CurrentDate FROM DATE
YYYYMMDD.
ACCEPT DayOfYear FROM DAY YYYYDDD.
ACCEPT CurrentTime FROM TIME.
DISPLAY "Name is ", Initials SPACE
Surname.
DISPLAY "Date is " CurrentDay SPACE
CurrentMonth SPACE CurrentYear.
DISPLAY "Today is day " YearDay " of
the year".
DISPLAY "The time is " CurrentHour ":"
CurrentMinute.
STOP RUN.

#2
IDENTIFICATION DIVISION.
PROGRAM-ID. Iteration-If.
AUTHOR. Michael Coughlan.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1
PIC 9
01 Num2
PIC 9
01 Result
PIC 99
01 Operator
PIC X

VALUE
VALUE
VALUE
VALUE

ZEROS.
ZEROS.
ZEROS.
SPACE.

PROCEDURE DIVISION.
Calculator.
PERFORM 3 TIMES
DISPLAY "Enter First Number
" WITH NO ADVANCING

ACCEPT Num1
DISPLAY "Enter Second Number
:
" WITH NO ADVANCING
ACCEPT Num2
DISPLAY "Enter operator (+ or *) :
" WITH NO ADVANCING
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING
Result
END-IF
DISPLAY "Result is = ", Result
END-PERFORM.

14. Scala- is a general purpose programming language. Scala has full support for
functional programming and a very strong static type system.

Sample Code
#1

> scala
This is a Scala shell.
Type in expressions to have them
evaluated.
Type :help for more information.
scala> object HelloWorld {
|
def main(args: Array[String]) {
|
println("Hello, world!")
|
}
| }
defined module HelloWorld
scala> HelloWorld.main(null)
Hello, world!
unnamed0: Unit = ()
scala>:q

#2

object abstractTypes extends Application {


abstract class Buffer {
type T; val element: T
}
abstract class SeqBuffer {
type T; val element: Seq[T]; def
length = element.length
}
def newIntBuffer(el: Int) = new Buffer {
type T = Int; val element = el
}
def newIntBuffer(el: Int*) = new
SeqBuffer {
type T = Int; val element = el
}
println(newIntBuffer(1).element)
println(newIntBuffer(1, 2, 3).length)
}

15. Visual Basic- is a third-generation event-driven programming language and integrated


development environment (IDE) from Microsoft for its COM programming model first
released in 1991 and declared legacy in 2008.

Sample Code
#1

Private Sub cmdClear_Click()


txtShow.Text = ""
End Sub
Private Sub cmdExit_Click()
If MsgBox("Are you sure you want to close the application?", vbQuestion + vbYesNo, "Confirm") =
vbYes Then
End
Else
cmdShow.SetFocus
End If
End Sub
Private Sub cmdShow_Click()
txtShow.Text = "Hello World!"
End Sub

#2
//Enter number
Private Sub Form_Load()
n = InputBox("Enter a number")
MsgBox "You entered " & n
End Sub

Sources
http://mashable.com/2014/01/21/learn-programming-languages/#SzpYIPCmFaqR
http://9gag.com/gag/aDwN219/the-different-uses-of-programming-languages
http://www.programmingsimplified.com/java-source-codes
http://www.programmingsimplified.com/c-program-examples
http://www.programiz.com/python-programming/examples

http://sandbox.mc.edu/~bennet/ruby/code/
http://javascriptbook.com/code/
https://docs.oracle.com/cd/A97630_01/appdev.920/a96624/a_samps.htm
http://sandbox.mc.edu/~bennet/perl/leccode/
http://www.csis.ul.ie/cobol/examples/default.htm

Anda mungkin juga menyukai