Anda di halaman 1dari 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 statement or 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 while statement 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:

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 after the 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 the program 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 loop The 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.

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

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-catchfinally 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 (<conditional expression>) <statement action> 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 within if-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 complete but 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. <<= left shift. >>= Right shift. &= Bitwise AND. ^= bitwise exclusive OR (XOR). |= bitwise inclusive OR. Logical/Relational == Equal to != Not equal to > < >= <= && Logical AND || Logical OR ! Logical NOT Bitwise & AND (Binary operator) | inclusive OR ^ exclusive OR << shift left. C ++ use of << >> shift right. C ++ use of >> ~ 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

: , C++

Conditional expressions Series operator. There are three types of expressions:

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 conversions such as string->bool thereby throwing compile error. The specific scenario is a simple one as follows: #include <iostream> #include <string> using namespace std; template <class T> class myPair { T a, b; public: myPair(T first, T second ) { a = first; b = second; } void test(); }; typedef myPair<bool> boolParm; template<class T> void myPair<T>::test() { if(a == true) { cout << "a is true" << endl; } else { cout << "a is false" << endl; } if(b == true) { cout << "b is true" << endl; } else { cout << "b is false" << endl; } } int main() { boolParm myObj(false, "false"); myObj.test(); return 0; } The output of the above scenario is undesirable since the user may inadvertently pass 2 different types: bool and string and receive the first one as false (correct since passed as bool) but the second one will be true (incorrect since implicit type conversion from string to bool). I wish to restrict the user code in main() to throw

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 Checking


C 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 is available. 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

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 specific type 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");

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. This checking 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 singlebyte 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 complete inside 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)

Programs of C, C++, Java


Conversion of Temperature C #include<stdio.h> #include<conio.h> 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<iostream.h> #include<conio.h> void <span class="v252as57ee" id="v252as57ee_13">main</span>() { //clear the screen. clrscr(); //declare <span class="v252as57ee" id="v252as57ee_11">variable</span> type float float a,b; //Input the Temperature in given <span class="v252as57ee" id="v252as57ee_8">unit</span> save them in 'a' cout<<"Enter the Temperature in Celsius"<<endl; cin>>a; //convert and save it in 'b' b=a+273; //show the output 'b' cout<<"Temperature in Kelvin is "<<b; //get character getch(); } Java import java.util.Scanner; public class TempConverter{

public static void main(String [] args) { float f, c; f = c = 0; int a; Scanner scan = new Scanner (System.in); System.out.println("Press 1 for C->F or 2 for F->C"); a = scan.nextInt(); if (a == 1) convertCtoFAndPrint(); else convertFtoCAndPrint(); } public static void convertFtoCAndPrint() { f = c = 0; Scanner scan = new Scanner (System.in); System.out.println("Please enter degrees F"); f = scan.nextFloat(); c = (5/9)*(f-32); System.out.println(f + " degrees F is " + c + " degrees C."); } public static void convertCtoFAndPrint() { Scanner scan = new Scanner (System.in); System.out.println("Please enter degrees C"); c = scan.nextFloat(); f = c*(9/5)+32; System.out.println(c + " degrees C is " + f + " degrees F."); } }

Hello World C #include<stdio.h> #include<conio.h> void main() { Printf(Hello World); getch(); } C++ #include<stdio.h> #include<conio.h>

void main() { cout<<Hello World!<<endl; getch(); } Java public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World"); } }

cin >> n; for (int i = 0; i < n; i++){ cout << num_next << " "; num_next = num1 + num2; num1 = num2; num_temp = num2; num2 = num_next - num1; num1 = num_temp; } return 0; } Java 1. /* 2. Fibonacci Series Java Example This Fibonacci Series Java Example shows how to create and print Fibonacci Series using Java. */ 6. public class JavaFibonacciSeriesExample { 8. public static void main(String[] args) { 10. 11. //number of elements to generate in a series 12. int limit = 20; 13. 14. long[] series = new long[limit]; 15. 16. //create first 2 series elements 17. series[0] = 0; 18. series[1] = 1; 19. 20. //create the Fibonacci series and store it in an array 21. for(int i=2; i < limit; i++){ 22. series[i] = series[i-1] + series[i-2]; 23. } 24. 25. //print the Fibonacci series numbers 26. Calculator

Fibonacci Series C /* Displaying Fibonacci sequence up to nth term where n is entered by user. */ #include <stdio.h> int main() { int count, n, t1=0, t2=1, display=0; printf("Enter number of terms: "); scanf("%d",&n); printf("Fibonacci Series: %d+%d+", t1, t2); /* Displaying first two terms */ count=2; /* count=2 because first two terms are already displayed. */ while (count<n) { display=t1+t2; t1=t2; t2=display; ++count; printf("%d+",display); } return 0; } C++ #include <iostream> using namespace std;

C int main() { int num1 = 0; int num2 = 1; int num_temp; int num_next = 1; int n; // Calculator example using C code #include<stdio.h> #include<conio.h> #include<math.h> #include<stdlib.h>

#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 <iostream> // 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<<"Welcome to My Calculator" <<endl; // Outputs welcome message cout<<""<<endl; // Blank Space cout<<"INSTRUCTIONS: Input a mathmatical equation" <<endl; // Outputs instruction cout<<" EX: 2 + 2" <<endl; // Outputs instruction cout<<""<<endl; // Blank Space cout<<"Operators:"<<endl; // Outputs operation header cout<<"For Addition, select '+'"<<endl // Outputs ADD instruction

cout<<"For Subtraction, select '-'"<<endl; // Outputs SUB instruction cout<<"For Multiplication, select '*'"<<endl; // Outputs MUL instruction cout<<"For Division, select '/'"<<endl; // Outputs DIV instruction cout<<""<<endl; // Blank Space cout<<"To clear, select 'c'"<<endl; // Outputs clear instruction cout<<"To quit, select 'q'"<<endl; // Outputs QUIT instruction cout<<""<<endl; // Blank Space cout<<"Input a mathmatical equation"<<endl; // Input instructions cin>>n1>>operation>>n2; calc:(n1,n2); cout<<"The answer is:"<<result<<endl; std::cin>>q; // Input "q" to "quit" return 0;} void calc(double x, double y) // Operator function { x=n1; y=n2; switch(operation) Operator swtich statement {case '+': result = x + y; break; case '-': result = x - y; break; case '*': result = x * y; break; case '/': result = x / y; break; default: cout<<"Improper equation. Please input a valid mathmatical equation"<<endl; cin>>n1>>operation>>n2; calc (n1,n2); } } //

Java import java.util.Scanner; public class Calculator { public static void main(String[] args) { Scanner input = new Scanner(System.in); Maths Maths = new Maths(); double answer = 0; double inputA, inputB; char operator; boolean done = false; while (done == false) { System.out.print("Please enter your sum: "); inputA = input.nextDouble(); operator = input.next().charAt(0); inputB = input.nextDouble(); switch (operator) { case '+': answer = Maths.add(inputA, inputB); break; case '-': answer = Maths.subtract(inputA, inputB); break; case '*': answer = Maths.multiply(inputA, inputB); break; case '/': answer = Maths.divide(inputA, inputB); break; case '^': answer = Maths.power(inputA, inputB); break; } System.out.println(answer); } input.close(); } }

Average Grade C #include <iostream> #include <cmath> using namespace std;

char name; double score1; double score2; int score3; int score4; int main() { cout << "Enter student's name: "; cin >> name; cout << "Enter test score 1: "; cin >> score1; cout << "Enter test score 2: "; cin >> score2; cout << "Enter test score 3: "; cin >> score3; cout << "Enter test score 4: "; cin >> score4; } C++ 1. #include <iostream> 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 << " Please enter the number of grades to average:\n"; cin >> numgrade; 19. while (count < numgrade) { cout << " Please enter grade in letter format:\n"; cin >> usergrade; cout << " You entered " << usergrade << ".\n"; totalgrades = usergrade + totalgrades; 26. 27. 28. 29. 30.

31. 32. 33. 34. 35.

count++; } average = totalgrades / numgrade; cout << " Your GPA is: " << average << ".\n";36. } 1. class Example1 { public static void main(String[] args) {

Java 2. 3. 4. 5. 6. 7. double total grade = int Korean(90) + English(85) + Mathematics(78) + Biology(65) + Chemistry(83); 8. 9. average= total/5; 10. { 11. 12. System.out.println("total grade :" + total); 13. System.out.println("average :" + average); 14. } 15. }16. }

Quick Sort C #include<stdio.h> void quicksort(int [10],int,int); int main(){ int x[20],size,i; printf("Enter size of the array: "); scanf("%d",&size); printf("Enter %d elements: ",size); for(i=0;i<size;i++) scanf("%d",&x[i]); quicksort(x,0,size-1); printf("Sorted elements: "); for(i=0;i<size;i++) printf(" %d",x[i]); return 0; } C++ #include<iostream.h>

#include<conio.h> int Partition(int a[], int beg, int end) Find Pivot Point { int p=beg, pivot=a[beg], loc; for(loc=beg+1;loc<=end;loc++) { if(pivot>a[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 { //Function to

lower++; while(array[higher]>pivot) higher--;

if(lower<higher){ int temp=array[higher]; array[higher]=array[lower]; array[lower]=temp; } else{ return higher; } } }

public static int[] compute(int[] array, int lower, int higher )throws IOException{ if(lower<higher){ int pivot=split(array,lower,higher); if(pivot>1) compute(array, lower, pivot-1); if(pivot+1<higher) compute(array, pivot+1, higher);

} return array; }

public static int split(int[] array, int lower, int higher){ while(true){ int pivot=array[lower]; while(array[lower]<pivot)

Anda mungkin juga menyukai