Skip to main content

Lets learn C

The C Journey

Lesson One : Introduction
C is everywhere, though .net, java, python is taking the world by storm. It is still one of the fundamental language to learn beginning programming. Though some may argue the case to be otherwise, but this is the way which worked best for me.

Lets get to the heart of the matter. Every C program begins with a main() function. main() is the entry point for a C program.

Let's write our first program, which is a hello world.


#include stdio.h
/* This program prints "Hello World" on the console. */
void main()
{
printf("Hello World\n");
}


The above program highlights many important features of C. Note the include file "stdio.h". The printf() function is located in this header file. You can treat stdio.h as a library containing many input/output functions. Later on we will see how to write our own such library.

Compile this program in your favorite editor and run it. You will be greeted with a "Hello World".

The "\n" at the end of "Hello World\n" string indicates a new line character. This instructs the compiler to postion the cursor on the next line.

And also note every C statement ends with a semicolon.
Also every block of statement is enclosed in a curly brace {...}.

Text written between /*.. */ are comments. This is for programmers reference. Comments are ignored by the compiler. Comments can also be represented by two forward slashes (//)
eg. // this line is a comment

The "void" indicates that the function doesn't return a value. This warrants an explanation as what a function is, which we will see in further section.

Lesson Two: Data Types
Objective: The objective of this section is to understand the following.
Memory Concepts
Data Types
Variables
Constants
Naming Conventions
scanf function
Arithmetic in C
Operator Precedence

Memory Concepts:
A computer has both short-term and long-term memory. A computer's long-term memory is called nonvolatile memory and is generally associated with mass storage devices, such as hard drives, large disk arrays, diskettes, and CD-ROMs. In later lessons, we will learn how to use nonvolatile memory for storing data.

This chapter concentrates on short-term, or volatile, memory. Volatile memory loses its data when power is removed from the computer. It's commonly referred to as RAM (random access memory).

RAM is made up of fixed-sized cells with each cell number referenced through an address. In later lessons, "Arrays," we will discuss memory cell reference through address pointers.

Generally Programmers reference memory cells through the use of variables. There are many types of variables, depending on the programming language, but all variables share similar characteristics, as described below

Name : The name of the variable used to reference data in program code

Type : The data type of the variable (number, character, and so on)

Value : The data value assigned to the memory location

Address: The address assigned to a variable, which points to a memory cell location

Data Types
We will look up at some of the data types such as strings, Boolean, arrays, objects, and data structures.

Let's concentrate on the following important data types
Integers
Floating-point numbers
Characters

Integers
Integers are whole numbers that represent positive and negative numbers, such as -3, -2, -1, 0, 1, 2, and 3, but not decimal or fractional numbers. Integer data types hold a maximum of four bytes of information and are declared with the int (short for integer) keyword as shown in the following line of code.

int x;

In C, you can declare more than one variable on the same line using a single int declaration statement, as demonstrated next. This preceding variable declaration declares three integer variables named x, y, and z.

int x, y, z;

Floating-Point Numbers
Floating-point numbers are all numbers, including signed and unsigned decimal and fractional numbers. Signed numbers include positive and negative numbers whereas unsigned numbers can only include positive values. Examples of floating-point numbers are shown in the following list.

09.4543
3428.27
112.34329
-342.66
-55433.33281

Use the keyword float to declare floating-point numbers, as shown next. This code has three floating-point variable data types called operand1, operand2, and result.

float operand1;
float operand2;
float result;

Characters
Character data types are representations of integer values known as character codes. For example, the character code 90 represents the letter Z. Note that the letter Z is not the same as the character code 122, which represents letter z (lowercase letter z).

Characters represent more than the letters of the alphabet; they also represent numbers 0 through 9, special characters, such as the asterisk (*), and keyboard keys, such as the Del (delete) key and Esc (escape) key. In all, there are a total of 128 common character codes (0 through 127), which make up the most commonly used characters of a keyboard.

Character codes are most notably organized through the ASCII (American Standard Code for Information Interchange) character set. For a listing of common ASCII character codes, see Appendix E, "Common ASCII Character Codes."

DEFINITION ASCII or American Standard Code for Information Interchange is noted for its character set, which uses small integer values to represent character or keyboard values.


In C, character variables are created using the char (short for character) keyword as demonstrated next.

char firstInitial;
char middleInitial;
char lastInitial;

Character data assigned to character variables must be enclosed in single quotes ('), also known as tick marks or apostrophes. As you'll see in the next section, the equals sign (=) is used for assigning data to the character variable.


Initializing Variables and the Assignment Operator
When variables are first declared, the program assigns the variable name (address pointer) to an available memory location. It is never safe to assume that the newly assigned variable location is empty. It's possible that the memory location contains previously used data (or garbage). To prevent unwanted data from appearing in your newly created variables, initialize new variables, as shown here.

int x;
char firstInitial;

x = 0;
firstInitial = '\0';

The preceding code declares two variables: one integer and one character data type. After creating the two variables, I initialize them to a particular value. For the integer variable, I assign the value zero (0), and for the character data type, I assign the character set \0, which is known as the NULL character. I enclosed the NULL character in single quotes. Single quotes are required when assigning data to the character data type.


Printing Variable Contents
To print the contents of variables, use the printf function with new formatting options, as demonstrated in the following code block. First, I declare three variables (one integer, one float, and one character), and then I initialize each of them. After initializing the variables, I use the printf statement to output each variable's contents to the computer's screen.


#include

main()

{

//variable declarations
int x;
float y;
char c;

//variable initializations
x = -4443;
y = 554.21;
c = 'M';

//printing variable contents to standard output
printf("\nThe value of integer variable x is %d", x);
printf("\nThe value of float variable y is %f", y);
printf("\nThe value of character variable c is %c\n", c);

}


Conversion Specifiers
Because data is stored as unreadable data in the computer's memory, programmers in C must specifically tell input or output functions, such as printf, how to display the data as information. You can accomplish this seemingly difficult task using character sets known as conversion specifiers.

Conversion specifiers are made up of two characters: The first character is the percent sign (%), and the second is a special character, which tells the program how to convert the data. Table 2.2 describes the most common conversion specifiers for the data types discussed in this chapter.

Common Conversion Specifiers Used with Printf Conversion Specifier Description

%d
Displays integer value

%f
Displays floating-point numbers

%c
Displays character


Displaying Integer Data Types with printf
Integer data types can easily be displayed using the %d conversion specifier with a printf statement as shown next.

printf("%d", 55);

The output of the preceding statement prints the following text:

55

The %d conversion specifier can also be used to output the contents of a variable declared as integer data type, as demonstrated next.

int operand1;
operand1 = 29;
printf("The value of operand1 is %d", operand1);

In the preceding statements, I declare a new integer variable called operand1. Next, I assign the number 29 to the newly created variable and display its contents using the printf function with the %d conversion specifier. Each variable displayed using a printf function must be outside the parentheses and separated with a comma (,).

Displaying Floating-Point Data Types with printf
To display floating-point numbers, use the %f conversion specifier demonstrated next.

printf("%f", 55.55);

Here's another example of the %f conversion specifier, which prints the contents of a floating-point variable:

float result;
result = 3.123456;
printf("The value of result is %f", result);

Although the %f conversion specifier displays floating-point numbers, it may not be enough to display the floating-point number with correct or wanted precision. The following printf statement demonstrates the precision problem.

printf("%f", 55.55);

This printf example outputs a floating-point number with a six-digit precision to the right of the decimal point, as shown next.

55.550000

To create precision with floating-point numbers, adjust the conversion specifier using numbering schemes between the % sign and the f character conversion specifier.


printf("%.1f", 3.123456);
printf("\n%.2f", 3.123456);
printf("\n%.3f", 3.123456);
printf("\n%.4f", 3.123456);
printf("\n%.5f", 3.123456);
printf("\n%.6f", 3.123456);

The preceding code block produces the following output:

3.1
3.12
3.123
3.1234
3.12345
3.123456

I included the escape sequence \n in each of the preceding printf statements (except the first line of code). Without the new line (\n) escape sequence, each statement's output would generate on the same line, making it difficult to read.

Displaying Character Data Types with printf
Characters are also easy to display using the %c conversion specifier, as shown next.

printf ("%c", 'M');

The output of this statement is simply the single letter M. Like the other conversion specifiers, you can output the contents of a character variable data type using the %c conversion specifier and a printf statement as demonstrated next.

char firstInitial;
firstInitial= 'S';
printf("The value of firstInitial is %c", firstInitial);

You can use multiple conversion specifiers in a single printf statement as shown next.

char firstName, middleName, lastName;
firstName= 'R';
middleName= 'R';
lastName= 'P';
printf("My Initials are %c.%c.%c.", firstName, middleName, lastName);

The output of the preceding program statements is as follows.

My Initials are R.R.P
Notice in the statement below that each variable displayed with the printf statement is outside the double quotes and is separated with a single comma.

printf("My Initials are %c.%.c.%c.", firstName, middleName, lastName);

Text inside printf's double quotes is reserved for displayable text, conversion specifiers, and escape sequences.

Comments

Anonymous said…
hi rajesh...

what are u upto..??
is this a freely downloadable chapter from your forthcoming C book :)

/chetan
Rajesh Pillai said…
no yaar..
It's just for reference...
and thought of going back to basics :) for a change..[by the way the contents of this particular entry has been indirectly extracted from multiple sources with some changes]

Popular posts from this blog

JavaScript Function Spaghetti Code

In this post we will have a look at the spaghetti code created by functions and how to avoid them. First lets quickly go through why this is a cause of concern.


Problems with Function Spaghetti Code

Variables/ functions are added to the global scope
The code is not modular
There's potential for duplicate function names
Difficult to maintain
No namespace sense.
Let's take for example the following set of functions and check whats the issue with them.
// file1.js
function saveState(obj) {     // write code here to saveState of some object     alert('file1 saveState'); }
// file2.js (remote team or some third party scripts) function saveState(obj, obj2) {      // further code...     alert('file2 saveState"); }
Now the problem here is if your application is using saveState() then the execution of saveState() which one to call is determined by the script loading.  The later script overrides same functions already defined by earlier script.
For e.g.

If this script is refer…

JavaScript - The this keyword

"this" is one of the most misunderstood construct in JavaScript.  To understand this first lets go through how to create a construction function in JavaScript.  A constructor function is a function which is used to create instances of objects in JavaScript.

You define a constructor function using the same notation that you use to define a normal JavaScript function.  The convention to follow is to capitalize the first letter of the function name.

This requirement is not enforced by the JavaScript language but it is a generally accepted practice and there are many benefits which we will shortly discuss.

Let's define a constructor function to hold our menu information.

function Menu() { }
So, in the above snippet you have a constructor function named Menu defined. At present this function doesn't do anything good.

Let's see how to invoke this function

var menu = new Menu();
Let's add some public properties to this function.
function Menu() { this.menuName = &q…