| Intermediate Programming
with C
Table of Contents
Introduction
Basics
Variables
Input and Output
Boolean Expressions and Branching
Loops
Functions
Files
Arrays and Pointers
C Programming Final Test
|
Chapter 3
Variables
Variables in C are declared differently than in Pascal. The format for
variable declarations in C is:
So the following would declare an integer variable named "x".
C allows multiple variables to be declared on the same line.
int x, y, z; /* declare x, y, and z */
|
C also allows a value to be assigned to the variable when it
is declared. Unlike Pascal, the C assignment statement is "="
instead of ":="
int x = 10; /*assign 10 to x */
|
The following program shows examples of how variables can be used. Please
note that the comments explain how the program works
#include <stdio.h>
int a, x;
float y;
char z;
void main(void) {
x = 1; /* assign 1 to x */
printf(" %d \n", x);
y = 2.5;
printf(" %f \n", y); /* assign 2.5 to y */
z = 'R';
printf(" %c \n", z);
a = x;
printf(" %d \n", a);
a = 2 * x;
printf(" %d \n", a);
}
Data Types
C defines several datatypes these are the most common.
| int |
Integer - holds whole numbers from -32,768 to 32,767 |
| float |
Floating point - holds numbers with digits after the decimal |
| double |
Double Precision floating point - same as float but with greateer precision |
| char |
Character - holds single ASCII characters. |
Math Operators
| Modulus (remainder) |
| x = 5 % 2; |
Other math operators.
The following make common operations faster.
| Addition "++" |
i++; /* increment i by one */
|
| Subtraction "--" |
i--; /* decrement i by one */
|
| Addition "+=" |
i += 10; /* same as i = 1 + 10;
|
| Subtraction "-=" |
i -= 10; /*same as i = 1 - 10
|
| Multiplication "*=" |
i *= 10; /* same as i = i * 10; */
|
| Division "/=" |
i /= 10; /* same as i = i / 10; */
|
  |