// Count in Java import java.io.* ; import java.util.Scanner ; public class Count { public static void main(int argc, String[] argv) { Scanner stdin = new Scanner(System.in) ; int count = stdin.nextInt() ; PrintStream stdout = new PrintStream(System.out) ; while (count >= 0) { stdout.format("%3d\n", count) ; --count ; } stdout.println("Hello World!") ; } }
/* CountDown in ANSI C -- and consequently C++ */ #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int count ; (void) scanf("%d", &count) ; while (count >= 0) { printf("%3d\n", count) ; --count ; } puts("Hello World!") ; return (EXIT_SUCCESS) ; }
// CountDown in C++ #include <iostream> #include <iomanip> using namespace std ; int main(int argc, char *argv[]) { int count ; cin >> count ; while (count >= 0) { cout << setw(3) << count << endl ; --count ; } cout << "Hello world!" << endl ; return (EXIT_SUCCESS) ; }
ANSI C does not allow //
as a way to start comments.
Only /*
and */
pairs are allowed.
char
short
int
long
float
double
long double
byte
char
short
int
long
float
double
boolean
C and Java have the same set of arithmetic, relational, logical, and bit
operators except for Java's >>>
logical
right shift which isn't needed in C because right shifts of unsigned
integer are always logical.
In C logical and relational operators always return integers, either 0 or 1.
Logical operators can also be applied to values other than 0 and 1.
For example, 5 || 0
is 1,
5 && 0
is 0, and
5 > 4 > 3
is 0.
For the most part, the major control structures
if
, if
-then
,
while
, do
-while
,
and for
are the same in Java and C.
Even the switch
construct has the same
need for break
.
However, in ANSI C, all variables must be declared at the beginning
of statment blocks (statements enclosed by {
and
}
).
This means that the following section of code are not
legal ANSI C. However, since they are both allowed in
C++, many C compilers will accept them.
if (x != 3) { int n = 2*x ; ++x ; int m = 3*b ; /* Can't declare m here in C */ y = n+m ; }
for (int i=0; i<10; ++i) { /* Can't declare i here in C */ sum = sum + i ; }
C is not an object oriented programming language. It does not have classes. It does not have methods. It does not have inheritence. It does not have interfaces.
C++ has classes and inheritence. It supports multiple inheritence rather than interfaces.