Prog Lang Kapa Lung An

Embed Size (px)

Citation preview

  • 8/12/2019 Prog Lang Kapa Lung An

    1/11

    The Difference and Similarities of

    the following terms in C, C++ and

    JAVA

    Control Flow, Selection Statement and Iteration of:

    (a,e,and g)

    C C provides two sytles of flow control:

    Branching

    Looping

    Branching is deciding what actions to take and looping

    is deciding how many times to take a certain action.

    Branching:

    Branching is so called because the program chooses to

    follow one branch or another.

    if statement

    This is the most simple form of the branching

    statements.

    It takes an expression in parenthesis and an statementor block of statements. if the expression is true then the

    statement or block of statements gets executed

    otherwise these statements are skipped.

    switch statement:

    The switch statement is much like a nested if .. else

    statement. Its

    mostly a matter of preference which you use, switch

    statement can be slightly more efficient and easier to

    read.

    while loop

    The most basic loop in C is the while loop.A whilestatement is like a repeating if statement. Like an If

    statement, if the test condition is true: the statments

    get executed. The difference is that after the

    statements have been executed, the test condition is

    checked again. If it is still true the statements get

    executed again.This cycle repeats until the test

    condition evaluates to false.

    for loop

    for loop is similar to while, it's just written differently.

    for statements are often used to proccess lists such a

    range of numbers:

    C++ A simple C++ statement is each of the individual

    instructions of a program, like the variable declarations

    andexpressions seen in previous sections. They always

    end with a semicolon (;), and are executed in the same

    order in which they appear in a program.

    If and else

    The if keyword is used to execute a statement or block,

    if, and only if, a condition is fulfilled. Its syntax is:

    if (condition) statement

    Here, condition is the expression that is being

    evaluated. If this condition is true, statement is

    executed. If it is false, statement is not executed (it is

    simplyignored), and the program continues right afterthe entire selection statement.

    Selection statements with if can also specify what

    happens when the condition is not fulfilled, by using the

    elsekeyword to introduce an alternative statement. Its

    syntax is:

    if (condition) statement1 else statement2

    where statement1 is executed in case condition is true,

    and in case it is not, statement2 is executed.

    Loops repeat a statement a certain number of times, or

    while a condition is fulfilled. They are introduced by the

    keywords while, do, and for.

    Iteration

    The while loop

    The simplest kind of loop is the while-loop. Its syntax is:

    while (expression) statement

    The while-loop simply repeats statement while

    expression is true. If, after any execution of statement,

    expressionis no longer true, the loop ends, and theprogram continues right after the loop.

    The do-while loop

    A very similar loop is the do-while loop, whose syntax is

    do statement while (condition);

    It behaves like a while-loop, except that condition is

    evaluated after the execution of statement instead of

    before, guaranteeing at least one execution of

    statement, even if condition is never fulfilled.

    The for loopThe for loop is designed to iterate a number of times. Its

    syntax is:

    for (initialization; condition; increase) statement;

    Like the while-loop, this loop repeats statement while

    condition is true. But, in addition, the for loop provides

    specific locations to contain an initialization and an

    increase expression, executed before the loop begins

    the first time, and after each iteration, respectively.

  • 8/12/2019 Prog Lang Kapa Lung An

    2/11

    JAVA

    Java Control statements control the order of execution

    in a java program, based on data values and conditional

    logic. There are three main categories of control flow

    statements;Selection statements: if, if-else and switch.

    Loop statements: while, do-while and for.

    Transfer statements: break, continue, return, try-catch-

    finally and assert.

    We use control statements when we want to change

    the default sequential order of execution

    Selection Statements

    The If Statement

    The if statement executes a block of code only if the

    specified expression is true. If the value is false, then

    the if block is skipped and execution continues with the

    rest of the program. You can either have a single

    statement or a block of code within an if statement.

    Note that the conditional expression must be a Boolean

    expression.

    The simple if statement has the following syntax:

    if ()

    The If-else Statement

    The if/else statement is an extension of the if

    statement. If the statements in the if statement fails,

    thestatements in the else block are executed. You can

    either have a single statement or a block of code withinif-else blocks. Note that the conditional expression must

    be a Boolean expression.

    Expressions and Assignments of:

    C Operators are used with operands to

    build expressions. For example the following is an

    expression containing two operands and one oprator.

    4 + 5

    The following list of operators is probably not completebut does highlight the common operators and a few of

    the outrageous ones....

    C contains the following operator groups.

    Arithmetic

    Assignment

    Logical/relational

    Bitwise

    Odds and ends!

    Operator precedence table.

    The order (precedence) that operators are evaluated

    can be seen here.

    Arithmetic

    +

    -

    /

    *

    % modulo

    Decrement (post and pre)++ Increment (post and pre)

    Assignment

    These all perform an arithmetic operation on the lvalue

    and assign the result to the lvalue. So what does this

    mean in English? Here is an example:

    counter = counter + 1;

    can be reduced to

    counter += 1;

    Here is the full set.

    =

    *= Multiply

    /= Divide.

    %= Modulus.

    += add.

    -= Subtract.

    = Right shift.

    &= Bitwise AND.

    ^= bitwise exclusive OR (XOR).

    |= bitwise inclusive OR.

    Logical/Relational

    == Equal to

    != Not equal to>

    =

    >

    ~ one's complement

    Odds and ends!

    sizeof() size of objects and data types.

    strlen may also be of interest.

    & Address of (Unary operator)

    pointer (Unary operator)

    ? Conditional expressions

  • 8/12/2019 Prog Lang Kapa Lung An

    3/11

    : Conditional expressions

    , Series operator.

    C++ There are three types of expressions:

    Arithmetic expression

    Relational expression

    Logical expression

    Java An expression is a syntactic construction that

    has a value. Expressions are formed by combining

    variables, constants, and method returned values using

    operators. Java expressions can have side-effects, which

    are actions that are executed when the expression is

    evaluated. In particular, an assignment expression is

    usually used for its side effect of assigning a new value

    to a variable. Method invokations also frequently have

    side effects.

    Recursion, Data Types, Type CheckingC

    C Programming Recursion

    A function that calls itself is known as recursive function

    and the process of calling function itself is known

    asrecursion in C programming.

    In the C programming language, data types refer to an

    extensive system used for declaring variables or

    functions of different types. The type of a variable

    determines how much space it occupies in storage and

    how the bit pattern stored is interpreted.

    The types in C can be classified as follows:

    S.N. Types and Description

    Basic Types:

    They are arithmetic types and consists of the two types:

    (a) integer types and (b) floating-point types.

    2 Enumerated types:

    They are again arithmetic types and they are used to

    define variables that can only be assigned certain

    discrete integer values throughout the program.

    3 The type void:

    The type specifier void indicates that no value isavailable.

    4 Derived types:

    They include (a) Pointer types, (b) Array types, (c)

    Structure types, (d) Union types and (e) Function types.

    C++

    Simply put, recursion is when a function calls itself. That

    is, in the course of the function definition there is a call

    to that very same function. At first this may seem like a

    never ending loop, or like a dog chasing its tail. It can

    never catch it. So too it seems our function will never

    finish. This might be true is some cases, but in practice

    we can check to see if a certain condition is true and in

    that case exit (return from) our function. The case in

    which we end our recursion is called a base case .

    0down votefavorite

    I am trying to achieve type checking of template class

    parameters by disallowing implicit type conversionssuch as string->bool thereby throwing compile error.

    The specific scenario is a simple one as follows:

    #include

    #include

    using namespace std;

    template

    class myPair {

    T a, b;

    public:

    myPair(T first, T second ) {

    a = first;

    b = second;

    }

    void test();

    };

    typedef myPair boolParm;

    template

    void myPair::test() {

    if(a == true) {

    cout

  • 8/12/2019 Prog Lang Kapa Lung An

    4/11

    compile errors and disallowing string/int parameters to

    pass in the constructor. It should only allow bool. I tried

    by using an overloaded constructor myPair(bool first,

    string second) but it didn't match since I guess the

    implicit type conversion from string->bool happens

    before the constructor is called. Is there any solution

    using template specializations in this scenario? Any help

    is highly appreciated Thanks

    Java

    Recursion is a basic programming technique you can

    use in Java, in which a method calls itself to solve some

    problem. A method that uses this technique is

    recursive. Many programming problems can be solved

    only by recursion, and some problems that can be

    solved by other techniques are better solved by

    recursion.

    Primitive Data Types:

    There are eight primitive data types supported by Java.

    Primitive data types are predefined by thelanguage and

    named by a keyword. Let us now look into detail about

    the eight primitive data types.

    byte:

    Byte data type is an 8-bit signed two's complement

    integer.

    Minimum value is -128 (-2^7)

    Maximum value is 127 (inclusive)(2^7 -1)

    Default value is 0

    Byte data type is used to save space in large arrays,

    mainly in place of integers, since a byte is four times

    smaller than an int.Example: byte a = 100 , byte b = -50

    short:

    Short data type is a 16-bit signed two's complement

    integer.

    Minimum value is -32,768 (-2^15)

    Maximum value is 32,767 (inclusive) (2^15 -1)

    Short data type can also be used to save memory as

    byte data type. A short is 2 times smaller than an int

    Default value is 0.

    Example: short s = 10000, short r = -20000

    int:Int data type is a 32-bit signed two's complement

    integer.

    Minimum value is - 2,147,483,648.(-2^31)

    Maximum value is 2,147,483,647(inclusive).(2^31 -1)

    Int is generally used as the default data type for integral

    values unless there is a concern about memory.

    The default value is 0.

    Example: int a = 100000, int b = -200000

    long:

    Long data type is a 64-bit signed two's complement

    integer.

    Minimum value is -9,223,372,036,854,775,808.(-2^63)

    Maximum value is 9,223,372,036,854,775,807

    (inclusive). (2^63 -1)

    This type is used when a wider range than int is needed

    Default value is 0L.

    Example: long a = 100000L, int b = -200000L

    float:Float data type is a single-precision 32-bit IEEE 754

    floating point.

    Float is mainly used to save memory in large arrays of

    floating point numbers.

    Default value is 0.0f.

    Float data type is never used for precise values such as

    currency.

    Example: float f1 = 234.5f

    double:

    double data type is a double-precision 64-bit IEEE 754

    floating point.

    This data type is generally used as the default data type

    for decimal values, generally the default choice.

    Double data type should never be used for precise

    values such as currency.

    Default value is 0.0d.

    Example: double d1 = 123.4

    boolean:

    boolean data type represents one bit of information.

    There are only two possible values: true and false.

    This data type is used for simple flags that track

    true/false conditions.

    Default value is false.Example: boolean one = true

    char:

    char data type is a single 16-bit Unicode character.

    Minimum value is '\u0000' (or 0).

    Maximum value is '\uffff' (or 65,535 inclusive).

    Char data type is used to store any character.

    Example: char letterA ='A'

    Reference Data Types:

    Reference variables are created using defined

    constructors of the classes. They are used to access

    objects. These variables are declared to be of a specifictype that cannot be changed. For example, Employee,

    Puppy etc.

    Class objects, and various type of array variables come

    under reference data type.

    Default value of any reference variable is null.

    A reference variable can be used to refer to any object

    of the declared type or any compatible type.

    Example: Animal animal = new Animal("giraffe");

  • 8/12/2019 Prog Lang Kapa Lung An

    5/11

    Type System - C, C++ and Java

    type system is a collection of rules that assign a

    property called a type to the various constructssuch

    as variables, expressions, functions or modulesa

    computer program is composed of.[1] The main

    purpose of a type system is to reduce bugs in computer

    programs[2] by defining interfaces between different

    parts of a computer program, and then checking that

    the parts have been connected in a consistent way. Thischecking can happen statically (at compile time),

    dynamically (at run time), or it can happen as a a

    combination of static and dynamic checking

    Type Checking - C, C++ and Java

    Some object-oriented languages (notably Java) perform

    some type checking at runtime (dynamic type checking).

    If combined with static type checking, dynamic type

    checking is more powerful than static type checking

    alone. However, it also adds overhead to program

    execution.

    C++ uses static type checking because the language

    cannot assume any particular runtime support for bad

    operations. Static type checking notifies the

    programmer about misuses of types during compilation,

    and thus maximizes execution speed. As you learn C++,

    you will see that most of the language design decisions

    favor the same kind of high-speed, production-oriented

    programming the C language is famous for.

    Strings - C, C++ and Java

    Java strings are immutable, i.e. once created, their value

    cannot be changed without doing unnatural things in

    Java and/or native code.Java strings keep textual information in 2-byte unicode.

    Java strings are objects, i.e. like every other type, the

    String type extends the Object type.

    C-strings are simply pointers to memory holding single-

    byte char-typed or platform-specifc wchar_t-typed

    data.

    Programmers have to explicitly manage

    allocation/deallocation of character data.

    Different character encodings are provided at platform

    API level. Normally no support for different encodings

    within one application.Pointers - C, C++ and Java

    Java classes and arrays are reference types, and

    references to objects and arrays are akin to pointers in

    C. Unlike C pointers, however, references in Java are

    entirely opaque. There is no way to convert a reference

    to a primitive type, and a reference cannot be

    incremented or decremented. There is no address-of

    operator like &, dereference operator like * or >, or

    sizeof operator. Pointers are a notorious source of bugs.

    Eliminating them simplifies the language and makes

    Java programs more robust and secure

    Recursive types - C, C++ and Java

    After going back and forth, I am quite convinced that

    the declaration that you quote is actually the point of

    instantiation of the template. Had it been in a member

    function (including the constructor, whether user

    defined or implicitly generated) then the code would

    have been correct, since a class is considered completeinside the definition of the methods (i.e. if the point of

    instantiation where MoveTree::MoveTree() : variation()

    {} then the code would be correct (14.7.1 explains the

    rules for implicit instantiaitons for those curious enough

    to read on)

  • 8/12/2019 Prog Lang Kapa Lung An

    6/11

    Programs of C, C++, Java

    Conversion of Temperature

    C

    #include

    #include

    void main()

    {

    float celsius,fahrenheit;

    clrscr();

    printf("nEnter temp in Celsius : ");

    scanf("%f",&celsius);

    fahrenheit = (1.8 * celsius) + 32;

    printf("nTemperature in Fahrenheit : %f ",fahrenheit);

    getch();

    }

    C++

    #include

    #include

    void main()

    {

    //clear the screen.clrscr();

    //declare variable type float

    float a,b;

    //Input the Temperature in given unit

    save them in 'a'

    cout

  • 8/12/2019 Prog Lang Kapa Lung An

    7/11

    void main()

    {

    cout

  • 8/12/2019 Prog Lang Kapa Lung An

    8/11

    #define KEY "Enter the calculator Operation you want to

    do:"

    // Function prototype declaration

    void addition();

    void subtraction();

    void multiplication();

    void division();

    void modulus();void power();

    int factorial();

    void calculator_operations();

    // Start of Main Program

    int main()

    {

    int X=1;

    char Calc_oprn;

    // Function call

    calculator_operations();

    while(X)

    {

    printf("\n");

    printf("%s : ", KEY);

    Calc_oprn=getche();

    switch(Calc_oprn)

    {

    case '+': addition();break;

    case '-': subtraction();

    break;

    case '*': multiplication();

    break;

    case '/': division();

    break;

    case '?': modulus();

    break;

    case '!': factorial();

    break;

    case '^': power();

    break;

    case 'H':

    case 'h': calculator_operations();

    break;

    case 'Q':

    case 'q': exit(0);

    break;

    case 'c':

    case 'C': system("cls");

    calculator_operations();break;

    default : system("cls");

    printf("\n**********You have entered unavailable

    option");

    printf("***********\n");

    printf("\n*****Please Enter any one of below available

    ");

    printf("options****\n");

    calculator_operations();

    }

    }

    }

    C++

    // CalculatorFinal.cpp : Defines the entry point for the

    console application.

    //

    #include "stdafx.h" // Including header

    #include // Including ioStream

    using namespace std; // Namespace

    void calc (double x, double y);

    double result;

    double n1,n2; // Declaring Variables

    char q,operation;

    int main()

    {

    cout

  • 8/12/2019 Prog Lang Kapa Lung An

    9/11

    cout

  • 8/12/2019 Prog Lang Kapa Lung An

    10/11

    char name;

    double score1;

    double score2;

    int score3;

    int score4;

    int main()

    {

    cout > name;

    cout > score1;

    cout > score2;

    cout > score3;

    cout > score4;

    }

    C++

    1. #include

    2. using namespace std;

    3. int main()

    4.

    5. {

    6. char usergrade;

    7. int totalgrades = 0;

    int numgrade = 1;

    int count = 0;

    int average = 0;int A = 4, a = 4;

    int B = 3, b = 3;

    int C = 2, c = 2;

    int D = 1, d = 1;

    int F = 0, f = 0;

    16.

    cout > numgrade;

    19.

    while (count < numgrade){

    cout > usergrade;

    cout

  • 8/12/2019 Prog Lang Kapa Lung An

    11/11

    #include

    int Partition(int a[], int beg, int end) //Function to

    Find Pivot Point

    {

    int p=beg, pivot=a[beg], loc;

    for(loc=beg+1;loca[loc])

    {

    a[p]=a[loc];

    a[loc]=a[p+1];

    a[p+1]=pivot;

    p=p+1;

    }

    }

    return p;

    }

    Java

    import java.io.IOException;

    public class QuickSort {

    public static int[] compute(int[] array, int lower, int

    higher )throws IOException{

    if(lower1)

    compute(array, lower, pivot-1);

    if(pivot+1