Classic Computer Magazine Archive COMPUTE! ISSUE 72 / MAY 1986 / PAGE 117

BASIC Equivalents In C

Harly M. Templeton

One of the hottest programming topics these days is the C language. C is the language of choice for many professional programmers because it's easy to write and produces compact, efficient machine language code. Another plus is that C programs are easy to transport from one computer to another. For those who may be new to C, here's an article that describes similarities between BASIC and C. It's excerpted from a chapter in From BASIC To C, currently available from COMPUTE! Books.

From a beginner's viewpoint, one of the reassuring aspects of the C language is that it has many things in common with BASIC. You can write a large part of your C program using statements that are just like or very similar to BASIC statements. Of course, they have no line numbers, are written with lowercase letters, and end with a semicolon. But they use the same keywords as BASIC statements, and perform the same or nearly the same operations. These are the C language statements that are equivalent to BASIC statements:

1. Assignment statement
2. if statement
3. for loop
4. while loop
5. goto statement

Assignment Statement
The assignment statement assigns a value to a variable. The value may be that of a constant, another variable, an expression, or a function. An assignment statement in BASIC is:

100 ITEM = 4875

The C equivalent is:

item = 4875;

    Same thing ... almost. BASIC is very secretive about the type of a variable. ITEM is automatically as signed single-precision type, and the constant 4875 is assigned integer type. The integer is converted to single precision and stored as a single-precision variable.
    C does not assign a type to a variable automatically. The example shown would result in an error message unless it had been preceded by a declarator. This particular declarator assigns type float to variable item:

float item;

    C's float variable is identical to the single-precision variable in BASIC. It is a real number providing six to seven digits of precision. The constant is assigned integer type in C also. It's converted to float type and stored as the value of item.
    The statements are the same in both languages. The difference is that C requires you to declare variables, which shows you at a glance which variables you're using and what type they are. Automatic assignment of types in BASIC sometimes provides strange answers; specific declaration of variables in C puts you in the driver's seat.
    C, like some versions of BASIC, includes a type of assignment statement that assigns the same value to more than one variable:

sum1  =  sum2  =  sum3  =  0;

    This statement assigns the value of 0 to variable sum3 first. Then it assigns the value of sum3 to variable sum2. Last of all, it assigns the value of sum2 to variable sum1. You can use any variable or expression to the right of the rightmost equal sign (instead of the 0).
    Here's another example in BASIC:

380 AVE = (VAL1 + VAL2 + VAL3)/3

    The C language statement is:

ave = (val1 + val2 + val3) / 3;

    The BASIC statement adds three single-precision values, converts the integer 3 to single precision, and performs single-precision division. The result is stored as a single-precision variable.
    Assuming that val1, val2, val3, and ave have been declared as float type, the C statement provides the same result, but in a different way. A C program performs no float type computations. Instead, the program that contains this statement converts val1, val2, val3, and integer 3 to type double, and performs the computations. Type double is a real-number type that provides 16 to 17 digits of precision. When it's converted and stored, the result is more accurate (potentially, at least) than if the result had been type float.
    If val1, val2, and val3 are declared as integers, you should use a float type constant:

ave = (vall + val2 + val3) / 3.0;

    The program adds the integers, converts the sum and constant to type double, performs the computations, and converts the result to float. Using 3 instead of 3.0 would have caused all the numbers to be treated as integers, and an integer result would have been converted to float and stored. This would probably not be accurate enough.
    Here's a more complex BASIC statement that includes a function:

500 SIDE1 = SIN(A) * HYP

    The C equivalent is:

side1 = sin(a) * hyp;

    The BASIC example calls the SIN function. Some versions of the interpreter return a double precision result, but most return a single-precision result. The result is a single-precision value in variable SIDE1.
    In C, the result is the same, but the computations are double type. The function, however, is in one of the libraries that came with your C compiler. The statement causes the compiler to ask the link program to get the function from the library and include it in your program. The advantage is that you don't have to use the C compiler or libraries each time you run the program. The library function becomes as much a part of your program as the functions you write and compile.
    C assignment statements are very much like BASIC assignment statements. All you need to do is omit the line number, change the letters to lowercase, and add a semicolon.

If Statement
The C if statement never needs a "then" and cannot transfer control to another part of the program. It uses parentheses around the relational or logical expression. Otherwise, it is the BASIC IF in lowercase letters and ending with a semicolon. Here's an example in BASIC:

    ELSE FEB = 29

    In C, you'll need four statements:

if (year % 4)
    feb = 28;
   feb = 29;

    Both versions use modulo division to identify leap years. The percent sign (%) is the modulo division operator in C. When the result is not zero, the variable feb is set to 28. When the result is zero, feb is set to 29. Like BASIC, C considers a zero value as false and a nonzero value as true. C replaces the BASIC THEN by using parentheses. Whatever comes after the closing parentheses is considered to be the statement to be executed if the expression is true. Now for the bad news. C has no equivalent for this BASIC statement:

500 IF YEAR < 1984 THEN 600 ELSE 650

    But the news is really not that bad, because C has a better way to do the same thing. In BASIC, line 600 and lines following are statements to be executed for years prior to 1984. Lines 650 and following are statements that apply to subsequent years. In C, you can put those statements right in the if statement:

if (year < 1984) {
    rate = .25;
    base = 2500;
    surcharge = .50;
else {
    rate = .26;
    base = 2000;
    surcharge = .52;

    Whatever it is, it went up in 1984. The important thing to notice is the left brace following the parenthesis. This brace is the beginning of a compound statement, or block, that is executed for years prior to 1984. The right brace ends the block. All the statements you need for years prior to 1984 go right here instead of somewhere else in your program. Similarly, a block following else contains the statements for years 1984 and later-all right here together, where you can't miss them.
    In BASIC, you can leave off the ELSE when you don't need it:

400 IF YEAR > 1983 THEN RATE =
    RATE + .01:BASE
    = BASE - 500: SURCHARGE =
    SURCHARGE + .02

    You can in C, too:

if (year > 1983) {
    rate = rate + .01;
    base = base - 500;
    surcharge = surcharge + .02;

    You would have to set rate, base, and surcharge to the values that apply before 1984, or this statement would not give you the same answer. If you set the variables to the 1983 values (with assignment statements), this statement is more efficient in either language. In either version, the statement does nothing if the year is 1983 or earlier.
    C's if statement works like BASIC's IF statement, and it can make your program more readable by in cluding blocks of statements that otherwise would be in some other part of the program,

for Loop
C's for loop is much more versatile than BASIC's FOR-NEXT loop.
    The BASIC loop starts with a FOR statement and ends with a NEXT:

800 SQ=1:ODD=1
810 FOR R=1 TO 15
830 ODD=ODD+2
850 NEXT R

    The C loop has no need for NEXT:

sq = odd = 1;
for (r= 1;r <= 15; r = r + 1) {
   printf("%d    %d \ n",sq, r);
   odd = odd + 2;
   sq = sq + odd;

    Notice that the C statement consists of keyword for followed by three expressions enclosed in pa rentheses and separated by semicolons. The first expression initializes r, it corresponds to the FOR R = 1 portion of the BASIC statement. The next expression is evaluated before each repetition of the statements in the loop. This corresponds to the TO 15 portion of the BASIC statement. The third expression is executed for each repetition of the loop, after the last statement. This expression corresponds to the STEP 1 option implied in the BASIC statement.
    The loop itself is a block, described in the section on the if statement. The loop could consist of a single statement. The statements in this block print 15 perfect squares and their roots without multiplying or calling a square root function. How about that?
    Whether the loop consists of a single statement or a compound statement (block), no NEXT state ment is needed. Either the semicolon that ends the statement or the brace that encloses the block tells the compiler what belongs in the loop.
    The for statement of C does not look like the FOR statement of BASIC, but for statements like the one shown in this section work exactly like BASIC FOR-NEXT loops.

while Loop
The C while loop is similar to the WHILE-WEND loop of BASIC. The C version doesn't need the WEND statement for the same reason that the for loop does not need a NEXT. Here's an example from BASIC:

250 WHILE N <> 21
270 N=N+5
280 WEND

    The C version is:

while (n!= 21) {
  n = n + 5;

    The while keyword is followed by an expression within parentheses. In the example, the expression is a relational one, having a true value (1) or a false value (0). Notice that != means not equal to. The expression could be a numeric expression; in that case, it is considered true when its value is not equal to zero. A zero value is considered false. In either case, the loop is executed as long as the expression is true.
    In the C version, the statements of the loop are enclosed in braces and include the scanf( ) function to accept a decimal number that you type in. These statements are executed until the user types 21; then the loop terminates. In either language, it could happen that typing 21 would not get you out of the loop. This would happen if variable n were a real number type and the automatic type conversions introduced a fractional result (21.00001, for example). Declare n as an integer to avoid this problem.
    Notice the contrast between for and while loops. The for loop initializes, tests, and increments. The while loop only tests. The loop must include some way for the variable to acquire the value required for the test. Otherwise, the loop is repeated until you get tired of it and turn off your computer. Here's the while loop version of the for loop example:

r=sq=odd= 1;
while (r <= 15) {
  printf(°%d  %d\n",sq,r);
  odd = odd + 2;
  sq = sq + odd;
  r = r + 1;

    The initialization expression moved to the statement preceding the loop, the incrementing expression moved into the loop, and the keyword changed. Otherwise, the examples are identical.

goto Statement
BASIC's GOTO statement allows you to write unmanageable programs, yet it is unavoidable in many BASIC programs. C's goto statement is seldom required. You should avoid using the goto statement to keep your programs understandable.
    Here's the culprit in BASIC:

400 GOTO 450

    In C:

goto there;

    Since C has no line numbers, the goto statement has to be different, but it works the same. However, the program must include a statement with "there" as its label:

there:year = year + 1; /* You may
   label any statement */

    Leave the goto statement for use only in dire emergencies.

A Program Example
You can program solutions for many problems using only these statements along with input/output functions. Program 1 demonstrates this with a very simple checkbook balancer.
    Notice the first line of the program. It is a compiler control line, required for the input/output statements in the example. The number sign (#) of a compiler control line must be in column 1 of the line, the leftmost character position.
    The input/output functions required are printf( ), which displays prompting messages on the screen, scanf( ), which accepts the numbers you type in, and getche( ), which accepts a single character from the keyboard and displays it on the screen. The other executable statements, except return, are all like BASIC statements. The return statement just returns control to the operating system.
    The program first asks for the balance and stores it after you type it in. Then it asks if there are any outstanding deposits. Using the familiar if statement and the character input function, the program accepts the first character you type and requests a deposit amount if you have typed Y. After displaying the prompting message, the program stores the deposit value and enters a while loop. Until you type 0 for the deposit amount, the loop is repeated, adding the deposit to the balance and getting another deposit value.
    When you type any letter other than Y (and that includes y), the  program skips to process the checks, subtracting each check from the previous balance. When you type 0 (for no more checks), the program displays the balance.
    The program is not very userfriendly, because it skips the processing of deposits if you type any letter but Y. It should at least recognize y. It could reject all letters but Y, y, N, and n, telling you to try again.
    This program shows that it's possible to program solutions to common problems using only the statements described in this article. But you can do a lot more with C: things that are done differently from BASIC and things you cannot do in BASIC.

Program 1: Checkbook In C

*include <stdio.h>
main () /* Balance your checkbook? */
double bal, chk, dep;
char in[12];
int c;

printf("Type in statement balance:"); /* Display function */
scanf("%lf",&bal);/* Formatted input function */
printf("Any outstanding deposits? (Y or N) ");
if ((c = getche()) = = 'Y') { /* Character input function */
    printf(" \ nType outstanding deposit: $");
    scanf("%lf", &dep);
    while (dep > 0) {
     bal = bal + dep;
     printf("Type outstanding deposit: $");
     scanf("%lf", &dep);
printf("\nType outstanding check: $");
scanf("%lf", &chk);
while (chk > 0) {
  bal = bal - chk;
  printf("Type outstanding check: $");
  scanf("%lf", &chk);
printf("Your checkbook balance should be $%.21f",bal);