Lawrence Technological University
College of Arts and Science
Department of Mathematics and Computer Sciences

Introduction to C, MCS 1142

### Say it in C and the descendants of C

A Phrasebook for use in writing C, Perl, Python and Ruby programs.

EnglishCPerlPythonRuby
Write a program that...
```/* program.c
a program that...
by A. Student AS000012345
*/
#include <stdio.h>
main() // idiom for int main(void)
{
program-statement; // comment
.
.
.
program-statement;
}
```
```# program.pl
# a program that...
# by A. Student AS000012345
program-statement; # comment
.
.
.
program-statement;
```
```# program.py
# a program that...
# by A. Student AS000012345
program-statement # comment
.
.
.
program-statement
```
```# program.rb
# a program that...
# by A. Student AS000012345
program-statement # comment
.
.
.
program-statement
```
Write a function that...
```/* an example of a function that
takes 1 argument of type double
and returns 1 rounded integer
usage:
double x = 1.6;
int j = round_a_double(x); */
int round_a_double(double d)
{
int i;
i = (int)(d + 0.5);
return i;
}
```
```# an example of a function that
# takes 1 argument
# and returns 1 rounded integer
# usage:
# \$x = 1.6;
# \$j = round_to_int(x);
sub round_to_int {
my \$x = shift;
return int(\$x + 0.5);
}
```
```# an example of a function that
# takes 1 argument
# and returns 1 rounded integer
# usage:
# x = 1.6
# j = round_to_int(x)
def round_to_int(x):
return int(x + 0.5)
```
```# an example of a function that
# takes 1 argument
# and returns 1 rounded integer
# usage:
# x = 1.6
# j = round_to_int(x)
def round_to_int(x)
return Integer(x + 0.5)
end
```
The program is finished normally
```return 0; // returns an integer, 0
// return type must match
```
or, for void main()
```return;  // idiom for this is to
}        // omit the line entirely
```
```exit 0; # idiom for this is to
# omit the line entirely
```
```import sys
sys.exit(0) # idiom for this is to
# omit the line entirely
```
```exit 0 # idiom for this is to
# omit the line entirely
```
To abort the program because an error is identified from the main function
```return 1; // return any non 0 integer
```
or, from any function including main()
```#include <stdlib.h>
.
.
.
exit(1);  // returns (non 0 exit code)
```
```exit 1; # or any non 0 exit code
```
```import sys
sys.exit(1) # or any non 0 exit code
```
```exit 1 # or any non 0 exit code
```
if necessary, hold the output window open when working in the C++Builder IDE
```printf("Press Enter to continue...");
fflush(stdin);
getchar();
```
N/A N/A N/A
print the message
```printf("the message");
```
```print "the message";
```
```print "the message"
```
```print "the message"
```
print the result
```printf("the result is %d",x);
// use %d  for int x; in decimal
// use %x  for int x; in hexadecimal
// use %o  for int x; in octal
// use %f  for float x; or double x;
// use %c  for char x;
// use %s for char x[] = "label";
```
```print "the result is ", x; # simple or
printf("the result is %d",x);
```
```print "the result is ", x; # simple or
print "the result is %d" % (x)
```
```print "the result is ", x # simple or
printf("the result is %d",x)
```
```// first prompt
printf("Enter a number for x ==> ");
// discard any left over keystrokes
fflush(stdin);
// put the number into the
scanf("%d",&x);
// use %d  for int x;
// use %f  for float x;
// use %lf for double x;
// use %c  for char x;
```
```# first prompt
print "Enter a number for x ==> ";
\$x = <>;
```
```# separate prompt and read
import sys
print "Enter a number for x ==> "
x = int(x)
x = raw_input("Enter a number for x ==> ")
x = int(x)
```
```# first prompt
print "Enter a number for x ==> "
x = gets # gets returns a string
x = x.to_i
```
calculate
```// declare or reserve space
// then intialize
int y,a=0,b=1;
// make an expression
// and assign the result
y = a + b;
```
```\$a=0; # initialize
\$b=1;
// make an expression
// and assign the result
\$y = \$a + \$b;
```
```a=0 # initialize
b=1
# make an expression
# and assign the result
y = a + b;
```
```a=0 # intialize
b=1
# make an expression
# and assign the result
y = a + b;
```
a block or group or paragraph of statements to be done (executed) as a unit
```{ // start a block of statements
statement1;
statement2;
statement3;
} // end of a block
```
```{ # start a block of statements
statement1;
statement2;
statement3;
} # end of a block
```
```while-etc: # start a block of statements
statement1 # indentation marks block
statement2
statement3
# end of a block
```
```while-etc # start a block of statements
statement1
statement2
statement3
end # end of a block
```
x subscript i
```x[i]
```
```\$x[i]
```
```x[i]
```
```x[i]
```
increment x by y
```x += y; // or x++; when y is 1
```
```\$x += \$y; # or \$x++; when y is 1
```
```x += y # Ok in Python 2.0+
```
```x += y
```
decrement x by 1
```x--;
```
```x--;
```
N/A N/A
use the value x, and then increment x by 1
```y = x++;
```
```y = x++;
```
N/A N/A
increment x by 1, and then use the value x
```y = ++x;
```
```y = ++x;
```
N/A N/A
is a condition true or false
```// any non 0 number is true
// only 0 is false
true = 1;
true = -9;
false = 0;
false = !(5 < 6);
```
```# any non 0 number is true
# a non empty string is true
# 0, "", "0", undef are false
```
```# any non 0 number is true
# a non empty string is true
# 0, "", "0", None are false
```
```# only nil and false are false
# everthing else is true
# 0 and "" are true
```
both condition-a and condition-b are true
```true = a && b;
false = !a && b;
```
```true = a && b;
true = a and b;
false = !a && b;
false = not a and b;
```
```true = a and b
false = not a and b
```
```true = a && b
true = a and b
false = !a && b
false = not a and b
```
either condition-a or condition-b are true
```true = a || b;
false = !a && !b;
```
```true = a || b;
true = a or b;
false = !a && !b;
false = not a and not b;
```
```true = a or b
false = not a and not b
```
```true = a || b
true = a or b
false = !a && !b
false = not a and not b
```
if one-thing do this, otherwise do that
```if (one-thing)
this;
else
that;
```
```if (one-thing) { # mandatory {
this;
} else {
that;
}
```
```if (one-thing):
this
else:
that
```
```if (one-thing)
this
else
that
end
```
if one-thing do this, if second-thing do that, otherwise do something-else
```if (one-thing)
this;
else if (second-thing)
that;
else
something-else;
```
```if (one-thing) { # mandatory {
this;
} elsif (second-thing) {
that;
} else {
something-else;
}
```
```if (one-thing) :
this
elif (second-thing):
that
else:
something-else
```
```if (one-thing)
this
elsif (second-thing)
that
else
something-else
end
```
do this until something happens
```while (!something-happened) {
this;
}
```
```while (!something-happened) {
this;
}
```
```while (not something-happened):
this
```
```while (!something-happened)
this
end
```
do this n times, adding 2 to x each time
```for (i = 0;i < n;i++) {
this;
x += 2;
}
```
```for (\$i = 0;\$i < \$n;\$i++) {
this;
\$x += 2;
}
```
```for i in range(10):  # 0..9
this
x += 2
```
```n.times do
this
x += 2
end
```
the sum of the terms involving x sub i, from i = 0 to n - 1 (math symbol sigma)
```for (i=0,sum=0;i < n;i++)
sum = sum + x[i];
```
```for (\$i=0,\$sum=0;\$i < \$n;\$i++)
\$sum = \$sum + \$x[\$i];
```
```for i in range(10):  # 0..9
sum = sum + x[i]
```
```0.upto(9) do |i|
sum = sum + x[i]
end
```
To explain an input or output error to the user
```perror("Your explanation");
```
will print your explanation: followed by the operating system's explanation
```die("Your explanation");
```
Use exceptions Use exceptions
To open a file for reading
```FILE *infile;
infile = fopen("filename","r");
if (!infile) {
perror("File was not opened because");
exit(1);
}
```
```open InFile, "<filename"
or die "File was not opened";
# < for r, > for w, >> for a
# like on the command line
```
```infile = open("filename","r");
```
```infile = File.new("filename","r");
```
To fill an array of integers from a file
```FILE *infile;
int i,x[MAX_INTEGERS];
// infile must first be opened as above
while(
i < MAX_INTEGERS &&
fscanf(infile,"%d",&x[i]) > 0)
i++;
```
```# infile must first be opened as above
@x = (); # empty array
while(<InFile>) {
foreach \$integer (split) {
push @x,\$integer;
}
}
```
```# infile must first be opened as above
import string
x = []
while line:
for num in (line.split()):
x.append(int(num))
```
```# infile must first be opened as above
x = []
infile.each do |line|
(line.split()).each do |num|
x.push(Integer(num))
end
end
```
To fill an array of words (strings without spaces) from a file
```FILE *infile;
int i;
char x[MAX_WORDS][MAX_WORD_LEN];
// infile must first be opened as above
while(
i < MAX_WORDS &&
fscanf(infile,
"%MAX_WORD_LENs",x[i]) > 0)
i++;
```
```# infile must first be opened as above
@x = (); # empty array
while(<InFile>) {
foreach \$word (split) {
push @x,\$word;
}
}
```
```# infile must first be opened as above
import string
x = []
while line:
for wrd in (line.split()):
x.append(wrd)
```
```# infile must first be opened as above
x = []
infile.each do |line|
(line.split()).each do |wrd|
x.push(wrd)
end
end
```
To read an entire line, including the spaces from the keyboard
```char buffer[100];
fgets(buffer,sizeof(buffer),stdin);
// avoids the security weakness of gets
```
```\$line = <>;
```
```import sys
```
```line = gets
```
To open a file for writing
```FILE *outfile;
outfile = fopen("filename","w");
if (!outfile) {
perror("File was not opened because");
exit(1);
}
```
```open OutFile, ">filename"
or die "File was not opened";
# < for r, > for w, >> for a
# like on the command line
```
```outfile = open("filename","w");
```
```outfile = File.new("filename","w");
```
To write an array of integers to a file
```FILE *outfile;
int i,n,x[MAX_INTEGERS];
// outfile must first be opened as above
// and n is made to equal the number of
// integers to be written
for (i = 0;i < n;i++)
fprintf(outfile,"%d ",x[i]);
```
```# OutFile must first be opened as above
print OutFile join ' ',@x;
```
```# outfile must first be opened as above
for num in (x):
outfile.write(str(num) + ' ')
```
```# outfile must first be opened as above
x.each do |num|
outfile.print String(num) + ' '
end
```
To write an array of words or strings to a file
```FILE *outfile;
int i,n;
char x[MAX_INTEGERS][MAX_WORD_LEN];
// outfile must first be opened as above
// and n is made to equal the number of
// integers to be written
for (i = 0;i < n;i++)
fprintf(outfile,"%d ",x[i]);
```
```# OutFile must first be opened as above
print OutFile join ' ',@x;
```
```# outfile must first be opened as above
for wrd in (x):
outfile.write(wrd + ' ')
```
```# outfile must first be opened as above
x.each do |wrd|
outfile.print String(wrd) + ' '
end
```
To do something for each member of an array, e.g. find the largest number
```int i,numbers[N],maximum = 0;
for (i = 0;i < N;i++)
numbers[i] = func(i);
for (i = 0;i < N;i++)
if (numbers[i] > maximum)
maximum = numbers[i];
```
```\$maximum = 0;
foreach \$num (@numbers) {
if (\$num > \$maximum) {
\$maximum = \$num;
}
}
```
```maximum = 0
for num in (numbers):
if (num > maximum):
maximum = num;
```
```maximum = 0
numbers.each do |num|
if (num > maximum)
maximum = num
end
end
```
To Read the 3rd bit from the right
```int mask = 0x04; // 0000 0100
int bit,i = 5;   // 0000 0101
bit = i & mask;  // 0000 0100 on or true
```
```\$mask = 0x04;      # 0000 0100
\$i = 5;            # 0000 0101
\$bit = \$i & \$mask; # 0000 0100 on or true
```
```mask = 0x04     # 0000 0100
i = 5           # 0000 0101
bit = i & mask # 0000 0100 on or true
```
```mask = 0x04     # 0000 0100
i = 5           # 0000 0101
bit = i & mask # 0000 0100 on or true
```
To Set the 3rd bit from the right
```int mask = 0x04; // 0000 0100
int i = 1;       // 0000 0001
i = i | mask;    // 0000 0101
```
Similarly Similarly Similarly
To Clear the 3rd bit from the right
```int mask = 0x04; // 0000 0100
int i = 5;       // 0000 0101
i = i & ~mask;   // 0000 0001
```
Similarly Similarly Similarly
To Toggle the 3rd bit from the right
```int mask = 0x04; // 0000 0100
int i = 5;       // 0000 0101
i = i ^ mask;    // 0000 0001
i = i ^ mask;    // 0000 0101
```
Similarly Similarly Similarly

Revised April 17, 2003