C Programming Notes
C Programming Notes
Easy to learn
Structured language
It produces efficient programs
It can handle low-level activities
It can be compiled on a variety of computer platforms
A C program basically consists of the following parts −
Preprocessor Commands
Functions
Variables
Statements & Expressions
Comments
Let us look at a simple code that would print the words "Hello World" −
#include<stdio.h>
int main()
{
/* my first program in C */
printf("Hello, World! \n");
return0;
}
The first line of the program #include<stdio.h> is a preprocessor command, which
tells a C compiler to include stdio.h file before going to actual compilation.
The next line intmain() is the main function where the program execution begins.
The next line /*...*/ will be ignored by the compiler and it has been put to add
additional comments in the program. So such lines are called comments in the
program.
The next line printf(...) is another function available in C which causes the message
"Hello, World!" to be displayed on the screen.
The next line return 0; terminates the main() function and returns the value 0.
Semicolons
In a C program, the semicolon is a statement terminator. That is, each individual statement
must be ended with a semicolon.
Comments
Comments are like helping text in your C program and they are ignored by the compiler.
They start with /* and terminate with the characters */
Keywords
The following list shows the reserved words in C. These reserved words may not be used
as constants or variables or any other identifier names.
Integer Types
The following table provides the details of standard integer types with their storage sizes
and value ranges −
To get the exact size of a type or a variable on a particular platform, you can use
the sizeof() operator.
Floating-Point Types
The following table provide the details of standard floating-point types with storage sizes
and value ranges and their precision −
A variable is nothing but a name given to a storage area that our programs can manipulate.
Each variable in C has a specific type. The name of a variable can be composed of letters,
digits, and the underscore character. It must begin with either a letter or an underscore.
Upper and lowercase letters are distinct because C is case-sensitive.
#include<stdio.h>
#define LENGTH 10
#defineWIDTH 5
#define NEWLINE '\n'
int main(){
int area;
area= LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return0;
}
When the above code is compiled and executed, it produces the following result −
value of area : 50
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. C language is rich in built-in operators and provides the following types of
operators −
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
Misc Operators
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language.
Assume variable A holds 10 and variable B holds 20 then −
Relational Operators
The following table shows all the relational operators supported by C. Assume
variable A holds 10 and variable B holds 20 then −
== Checks if the values of two operands are equal or not. If yes, then (A == B) is not
the condition becomes true. true.
!= Checks if the values of two operands are equal or not. If the (A != B) is
values are not equal, then the condition becomes true. true.
> Checks if the value of left operand is greater than the value of (A > B) is not
right operand. If yes, then the condition becomes true. true.
< Checks if the value of left operand is less than the value of right (A < B) is true.
operand. If yes, then the condition becomes true.
>= Checks if the value of left operand is greater than or equal to the (A >= B) is not
value of right operand. If yes, then the condition becomes true. true.
<= Checks if the value of left operand is less than or equal to the (A <= B) is
value of right operand. If yes, then the condition becomes true. true.
Logical Operators
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then −
&& Called Logical AND operator. If both the operands are non-zero, then (A && B)
the condition becomes true. is false.
! Called Logical NOT Operator. It is used to reverse the logical state of its !(A &&
operand. If a condition is true, then Logical NOT operator will make it B) is
false. true.
Assignment Operators
The following table lists the assignment operators supported by the C language −
sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 4.
The ? : Operator
Syntax:
Exp1 ?Exp2 : Exp3;
Where Exp1, Exp2, and Exp3 are expressions. The value of a ?expression is determined
like this −
Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the
entire ?expression.
If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the
expression.
The getchar() and putchar() Functions
The int getchar(void) function reads the next available character from the screen
and returns it as an integer. This function reads only single character at a time. You
can use this method in the loop in case you want to read more than one character
from the screen.
The int putchar(int c) function puts the passed character on the screen and returns
the same character. This function puts only single character at a time. You can use
this method in the loop in case you want to display more than one character on the
screen.
1 if statement
An if statement consists of a boolean expression followed by one or more statements.
2 if...else statement
An if statement can be followed by an optional else statement, which executes when
the Boolean expression is false.
3 nested if statements
You can use one if or else if statement inside another if or else if statement(s).
4 switch statement
A switch statement allows a variable to be tested for equality against a list of values.
Loops
1 while loop
Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.
2 for loop
Executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
3 do...while loop
It is more like a while statement, except that it tests the condition at the end of the
loop body.
4 nested loops
You can use one or more loops inside any other while, for, or do..while loop.
1 break statement
Terminates the loop or switch statement and transfers execution to the statement
immediately following the loop or switch.
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.
3 goto statement
Transfers control to the labeled statement.
Arrays
Arrays a kind of data structure that can store a fixed-size sequential collection of elements
of the same type. An array is used to store a collection of data, but it is often more useful to
think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99,
you declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables. A specific element in an array is accessed
by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the
first element and the highest address to the last element.
Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number
of elements required by an array as follows −
typearrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be an integer constant
greater than zero and type can be any valid C data type. For example, to declare a 10-
element array called balance of type double, use this statement −
double balance[10];
Here balance is a variable array which is sufficient to hold up to 10 double numbers.
Initializing Arrays
You can initialize an array in C either one by one or using a single statement as follows −
balance[4] = 50.0;
The above statement assigns the 5th element in the array with a value of 50.0. All arrays
have 0 as the index of their first element which is also called the base index and the last
index of an array will be total size of the array minus 1. Shown below is the pictorial
representation of the array we discussed above −
#include<stdio.h>
int main ()
{
int n[10];/* n is an array of 10 integers */
inti,j;
/* initialize elements of array n to 0 */
for(i=0;i<10;i++){
n[i]=i+100;/* set element at location i to i + 100 */
}
/* output each array element's value */
for(j =0; j <10; j++){
printf("Element[%d] = %d\n", j, n[j]);
}
return0;
}
When the above code is compiled and executed, it produces the following result −
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
Multi Dimensional Arrays
type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional integer array −
intthreedim[5][10][4];
Two-dimensional Arrays
The simplest form of multidimensional array is the two-dimensional array. A two-
dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-
dimensional integer array of size [x][y], you would write something as follows −
typearrayName [ x ][ y ];
Where type can be any valid C data type and arrayName will be a valid C identifier. A
two-dimensional array can be considered as a table which will have x number of rows and
y number of columns. A two-dimensional array a, which contains three rows and four
columns can be shown as follows –
Thus, every element in the array a is identified by an element name of the form a[ i ][ j ],
where 'a' is the name of the array, and 'i' and 'j' are the subscripts that uniquely identify
each element in 'a'.
int a[3][4]={
{0,1,2,3},/* initializers for row indexed by 0 */
{4,5,6,7},/* initializers for row indexed by 1 */
{8,9,10,11}/* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following
initialization is equivalent to the previous example −
intval = a[2][3];
The above statement will take the 4th element from the 3rd row of the array. You can
verify it in the above figure. Let us check the following program where we have used a
nested loop to handle a two-dimensional array −
#include<stdio.h>
int main (){
/* an array with 5 rows and 2 columns*/
int a[5][2]={{0,0},{1,2},{2,4},{3,6},{4,8}};
inti, j;
/* output each array element's value */
for(i=0;i<5;i++){
for( j =0; j <2; j++){
printf("a[%d][%d] = %d\n",i,j, a[i][j]);
}
}
return0;
}
When the above code is compiled and executed, it produces the following result −
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
As explained above, you can have arrays with any number of dimensions, although it is
likely that most of the arrays you create will be of one or two dimensions.
Arrays allow to define type of variables that can hold several data items of the same kind.
Similarly structure is another user defined data type available in C that allows to combine
data items of different kinds.
Structures:
C Structure is collection of different datatypes ( variables ) which are grouped together.
Whereas, array of structures is nothing but collection of structures. This is also called as
structure array in C.
Structures are used to represent a record. Suppose you want to keep track of your books
in a library. You might want to track the following attributes about each book −
Title
Author
Subject
Book ID
Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines a
new data type, with more than one member. The format of the struct statement is as
follows −
member definition;
member definition;
...
member definition;
The structure tag is optional and each member definition is a normal variable definition,
such as int i; or float f; or any other valid variable definition. At the end of the structure's
definition, before the final semicolon, you can specify one or more structure variables but
it is optional. Here is the way you would declare the Book structure −
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} book;