Skip to main content

The Basics Of C Programming - Part 2.

A variable is just a named area of storage that can hold a single value (numeric or character). C is very fussy about how you create variables and what you store in them. It demands that you declare the name of each variable that you are going to use and its type, or class, before you actually try to do anything with it.

There are five basic data types associated with variables:
int - integer: a whole number.
float - floating point value: i.e. a number with a fractional part.
double - a double-precision floating point value.
char - a single character.
void - valueless special purpose type.

One of the confusing things about the C language is that the range of values and the amount of storage that each of these types takes is not defined. This is because in each case the 'natural' choice is made for each type of machine. You can call variables what you like, although it helps if you give them sensible names that give you a hint of what they're being used for - names like sum, total, average and so on.

Integer Number Variables
The first type of variable we need to know about is of class type int - short for integer. An int variable can store a value in the range -32768 to +32767. You can think of it as a largish positive or negative whole number: no fractional part is allowed. To declare an int, you can use the instruction:
int variable_name;


For example:
int a;
declares that you want to create an int variable called a.

To assign a value to our integer variable we use the following statement:
a=10;

The C programming language uses the "=" character for assignment. A statement of the form a=10; should be interpreted as take the numerical value 10 and store it in a memory location associated with the integer variable a. The "=" character should not be seen as an equality otherwise writing statements of the form:
a=a+10;

This statement should be interpreted as take the current value stored in a memory location associated with the integer variable a; add the numerical value 10 to it and then replace this value in the memory location associated with a.

Decimal Number Variables
C uses two keywords to declare a variable that is to be associated with a decimal number: float and double. They each offer a different level of precision as outlined below:

float: A float, or floating point, number has about seven digits of precision and a range of about 1.E-36 to 1.E+36. A float takes four bytes to store.

double: A double, or double precision, number has about 13 digits of precision and a range of about 1.E-303 to 1.E+303. A double takes eight bytes to store.

For example:
float total;
double sum;

To assign a numerical value to our floating point and double precision variables we would use the following C statement:

total=0.0;
sum=12.50;

Character Variables
To declare a variable of type character we use the keyword char - a single character stored in one byte. For example:
char c;

If c is a char variable you can store the letter A in it using the C statement:
c='A'
Notice that you can only store a single character in a char variable.

Assignment Statement
Consider four very simple mathematical operations: add, subtract, multiply and divide. Let us see how C uses these operations on two float variables a and b.

add: a+b
subtract: a-b
multiply: a*b
divide: a/b

Be careful with the arithmetic! What is the answer to this simple calculation?
a=10/3

The answer depends upon how a was declared. If it was declared as type int the answer will be 3; if a is of type float then the answer will be 3.333.

Two points to note from the above calculation:
1)   C ignores fractions when doing integer division!
2)   When doing float calculations, integers will be converted into float.

Arithmetic Ordering
Consider the following calculation:
a=10.0 + 2.0 * 5.0 - 6.0 / 2.0

A computer has its own set of rules when performing an arithmetic calculation. In the above calculation the multiplication and division parts will be evaluated first and then the addition and subtraction parts. This gives an answer of 17.

You can freely mix int, float and double variables in expressions. In nearly all cases the lower precision values are converted to the highest precision values used in the expression. For example, the expression f*i, where f is a float and i is an int, is evaluated by converting the int to a float and then multiplying. The final result is, of course, a float but this may be assigned to another data type and the conversion will be made automatically. If you assign to a lower precision type then the value is truncated and not rounded. In other words, in nearly all cases you can ignore the problems of converting between types.

This is very reasonable but more surprising is the fact that the data type char can also be freely mixed with ints, floats and doubles. A character is represented as an ASCII or some other code in the range 0 to 255 and if you want you can use this integer code value in arithmetic. Another way of thinking about this is that a char variable is just a single-byte integer variable that can hold a number in the range 0 to 255, which can optionally be interpreted as a character. Consider the following instruction:

int x=10;
int y=25;
char z=x+y;
printf("Sum of x+y = %c", z);

produces the following output:
Sum of x+y= #
because the ASCII code of # is 35.

Something To Declare
You must declare the variable name before using it anywhere in the program, otherwise it will produce compilation error. You can declare any number of variables of the same type with a single statement. 
For example:
int a, b, c;

declares three integers: a, b and c. Exactly where you declare a variable makes a difference but for now you should put variable declarations after the opening curly bracket of the main program.

Here is an example program that includes some of the concepts outlined above. 

#include <stdio.h>
main()
{
int a,b,average;
a=10;
b=6;
average = ( a+b ) / 2 ;
printf("Here ");
printf("is ");
printf("the ");
printf("answer... ");
printf("\n");
printf("%d.",average);
}

You can assign an initial value to a variable when you declare it. 
For example:
int i=1;
sets the int variable to one as soon as it's created. 

This is just the same as:
int i;
i=1;  
but the compiler may be able to speed up the operation if you initialize the variable as part of its declaration.

Variable names:
a)    should be lowercase for local variables.
b)   should be uppercase for symbolic constants.
c)    only the first 31 characters of a variables name are significant.
d) must begin with a letter or _ (under score) character.

Popular posts from this blog

Screenshots from Windows 1.01

Windows 1.0 is a graphical personal computer operating environment developed by Microsoft, released on November 20, 1985, as the first version of the Microsoft Windows line. Version 1.01 , also released in 1985, was the first point-release after Windows 1.00.   Screenshots from Windows 1.01: ⇰ Desktop  First Run Empty Desktop Desktop With Applications ⇰  Office Applications Notepad Text Editor Calculator Calendar Clock Address Book ⇰  Multimedia Applications Media player, CD player, Volume level, and Sound: This GUI doesn’t have these features. ⇰  Networking Applications Terminal Phone Dialer: This GUI doesn’t have this feature. ⇰  Internet Applications Browser, and Mail: This GUI doesn’t have these features. ⇰  Accessibility Applications Keyboard Map:  This GUI doesn’t have this feature. ⇰  Settings Desktop themes,  Display,  S...

The C Programming Language, 2nd Edition*

This book is meant to help the reader learn how to program in C. It is the definitive reference guide, now in a second edition. Although the first edition was written in 1978, it continues to be a worldwide best-seller. This second edition brings the classic original up to date to include the ANSI standard. For evolution of the planet earth and our modern understanding of biology, there was Darwin's Origin of the Species. For mathematics, there was Newton's PhilosophiƦ Naturalis Principia Mathematica. Well, for the internet, for Facebook, for LinkedIn, Twitter, Instgram, Snapchat, WhatsApp, Pornhub and even the odious website for Justin Bieber would never have existed without Kernigan and Ritchie (more affectionately known as K&R)'s classic, The C Programming Language. What language was TCP/IP written in? C. What language inspired both C++ and Java (and the abominable C#)? C. What language are most libraries on most operating systems written in if not assembler? C. ...

C++ Program To Implement Casino Number Guessing Game.

#include <iostream> #include <string> #include <cstdlib> #include <ctime> using namespace std; void drawLine(int n, char symbol); void rules(); int main() { string playerName; int amount; int bettingAmount; int guess; int dice; char choice; srand(time(0)); drawLine(70,'_'); cout << "\n\n\n\t\tCASINO GAME\n\n\n\n"; drawLine(70,'_'); cout << "\n\nEnter Your Name : "; getline(cin, playerName); cout << "\n\nEnter Deposit Amount To Play Game : $"; cin >> amount;

Java: The Complete Reference, 9th Edition

This is Herb's most popular book on Java, fully updated and expanded to cover Java SE 8 (JDK 8).    Whether you're an experienced pro or just starting out, this one-stop guide will help you master this important language.  Inside you'll find comprehensive coverage of the Java language, its keywords, syntax, and fundamental programming principles.  Of course, descriptions of Java's newest features, such as lambda expressions, default interface methods, and the stream API are included. This lasting resource also describes key elements of the Java API library, such as the Collections Framework, concurrency, applets, servlets, Beans, event handling,  AWT,  Swing, and more. Coverage of JavaFX, Java's newest GUI framework, is also included. *** TO REVIEW BOOK ***  (click below) *** TO REVIEW SOURCE CODE PROBLEM  SOLUTIONS, VISIT   THIS   LINK ***

Java: A Beginner's Guide, 6th Edition

This is Herb's step-by-step introduction to Java, updated for Java SE 8 (JDK 8). If you are just learning Java, then this is the book for you.  It starts at the beginning, explaining the history of Java, why it's important to the Web, and how it relates to the world of programming at large.  You then learn how to obtain the Java Development Kit (JDK) and write your first Java program. Next, it's on to the Java fundamentals, including data types, operators, control statements, classes, objects, and methods.  You'll then progress to more advanced topics, such as inheritance, exception handling, the I/O system, multithreading,  applets, and lambda expressions. Also included is coverage of some of Java's most powerful features, such as generics, autoboxing, enumerations, and static import.  An introduction to JavaFX, Java's newest GUI framework, is also included. *** TO REVIEW BOOK *** (click below) *** TO REVIEW SOURCE CODE PROBLEM  SO...