C Tutorial
C Tutorial
C is a programming language invented in the early 1970s by Dennis Ritchie as a language for writing
operating systems.
The purpose of C is to precisely define a series of operations that a computer can perform to accomplish a
task. Most of these operations involve manipulating numbers and text, but anything that the computer can
physically do can be programmed in C.
Identifiers are names given to various elements of a program, such as variables, functions and arrays.
Identifiers consist of digits and letters, in any order but the rule is first character should be a letter.
keywords are certain reserved words that have standard, predefined meanings in C. These keywords can
be used only for their intended purpose; they cannot be used as programmer- defined identifiers. The
standard keywords are listed below:
auto extern size of break float static
case for struct const typedef if
switch char goto unsigned default long
continue int union void do register
volatile double return while else short
signed enum
It should be kept in mind that keywords are all in lowercase.
DATA TYPES: .
· FLOATING POINT
These are numbers which contain fractional parts, both positive and negative. The keyword used
to define float variables is,
C- TUTORIAL
float
An example of a float value is 34.12. An example of declaring a float variable called money is,
float money;
money = 0.12;
· DOUBLE
These are exponential numbers, both positive and negative. The keyword used to define double
variables is,
double
An example of a double value is 3.0E2. An example of declaring a double variable called big is,
double big;
big = 312E+7;
CHARACTER
These are single characters. The keyword used to define character variables is,
char
An example of a character value is the letter A. An example of declaring a character variable called letter
is,
char letter;
letter = 'A';
Note the assignment of the character A to the variable letter is done by enclosing the value in single
quotes. Remember the golden rule: Single character - Use single quotes.
For Ex : sum = a+b. In this equation sum, a and b are the identifiers or variable names representing the
numbers stored in the memory locations.
Variable Declaration:
Each variable used in a C program must be declared. Such declarations are necessary to indicate to the C
Compiler, the type of the variable used and specific number of memory locations required to hold
different constants or values. In other words, the variable name can store constants in its memory
locations belong to any four data types such as int, float, double and char.
Operators Introduction
An operator is a symbol which helps the user to command the computer to do a certain mathematical or
logical manipulations. Operators are used in C language program to operate on data and variables. C has a
rich set of operators which can be classified as
All the basic arithmetic operations can be carried out in C. All the operators have almost the same meaning as in
other languages. Both unary and binary operations are available in C language. Unary operations operate on a singe
operand, therefore the number 5 when operated by unary – will have the value –5.
Arithmetic Operators
Operator Meaning
+ Addition or Unary Plus
– Subtraction or Unary Minus
* Multiplication
/ Division
% Modulus Operator
C- TUTORIAL
Examples of arithmetic operators are
x+y
x-y
-x + y
a*b+c
-a * b
etc., here a, b, c, x, y are known as operands. The modulus operator is a special operator in C language which
evaluates the remainder of the operands after division.
2. Relational Operators
Often it is required to compare the relationship between operands and bring out a decision and program accordingly.
This is when the relational operator come into picture. C supports the following relational operators.
Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
It is required to compare the marks of 2 students, salary of 2 persons, we can compare them using relational
operators.
A simple relational expression contains only one relational operator and takes the following form.
Where exp1 and exp2 are expressions, which may be simple constants, variables or combination of them. Given
below is a list of examples of relational expressions and evaluated values.
Relational expressions are used in decision making statements of C language such as if, while and for statements to
decide the course of action of a running program.
3. Logical Operators
C has the following logical operators; they compare or evaluate logical and relational expressions.
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Example
C- TUTORIAL
a > b && x = = 10
The expression to the left is a > b and that on the right is x == 10 the whole expression is true only if both
expressions are true i.e., if a is greater than b and x is equal to 10.
Logical OR (||)
The logical OR is used to combine 2 expressions or the condition evaluates to true if any one of the 2 expressions is
true.
Example
a < m || a < n
The expression evaluates to true if any one of them is true or if both of them are true. It evaluates to true if a is less
than either m or n and when a is less than both m and n.
The logical not operator takes single expression and evaluates to true if the expression is false and evaluates to false
if the expression is true. In other words it just reverses the value of the expression.
For example
! (x >= y) the NOT expression evaluates to true only if the value of x is neither greater than or equal to y
4. Assignment Operators
The Assignment Operator evaluates an expression on the right of the expression and substitutes it to the value or
variable on the left of the expression.
Example
x=a +b
Here var is a variable, exp is an expression and oper is a C binary arithmetic operator. The operator oper = is known
as shorthand assignment operator
The increment and decrement operators are one of the unary operators which are very useful in C language. They are
extensively used in for and while loops. The syntax of the operators is given below
1. ++ variable name
2. variable name++
3. – –variable name
4. variable name– –
C- TUTORIAL
The increment operator ++ adds the value 1 to the current value of operand and the decrement operator – – subtracts
the value 1 from the current value of operand. ++variable name and variable name++ mean the same thing when
they form statements independently, they behave differently when they are used in expression on the right hand side
of an assignment statement.
m = 5;
y = ++m; (prefix)
In this case the value of y and m would be 6. Suppose if we rewrite the above statement as
m = 5;
y = m++; (post fix)
Then the value of y will be 5 and that of m will be 6. A prefix operator first adds 1 to the operand and then the result
is assigned to the variable on the left. On the other hand, a postfix operator first assigns the value to the variable on
the left and then increments the operand.
CONDITIONAL STATEMENTS:
1) Simple If statement
2) If-else statement
3) if-else if statement
4) Nested if statement
Syntax:
if(condition)
{
Statement1;
.....
Statement n;
}
Example:
void main()
{
int a,b;
printf(“Enter a,b values:”);
scanf(“%d %d”,&a,&b);
if(a>b)
printf(“\n a is greater than b”);
}
OUTPUT:
Enter a,b values:20
10
a is greater than b
C- TUTORIAL
IF-ELSE STATEMENT: It execute IF condition is TRUE.IF condition is FLASE it execute ELSE part
Syntax:
if(condition)
{
Statement1;
.....
Statement n;
}
else
{
Statement1;
.....
Statement n;
}
Example:
void main()
{
int a,b;
printf(“Enter a,b values:”);
scanf(“%d %d”,&a,&b);
if(a>b)
printf(“\n a is greater than b”);
else
printf(“\nb is greater than b”);
}
OUTPUT:
Enter a, b values:10
20
b is greater than a
IF-ELSE IF STATEMENT: It execute IF condition is TRUE.IF condition is FLASE it checks ELSE IF part .ELSE
IF is true then execute ELSE IF PART. This is also false it goes to ELSE part.
Syntax:
if(condition)
{
Statement1;
.....
Statementn;
}
else if
{
Statement1;
.....
Statementn;
}
else
{
Statement 1;
.....
Statement n;
}
Example:
void main()
{
C- TUTORIAL
int a,b;
printf(“Enter a,b values:”);
scanf(“%d %d”,&a,&b);
if(a>b)
printf(“\n a is greater than b”);
else if(b>a)
printf(“\nb is greater than b”);
else
printf(“\n a is equal to b”);
}
OUTPUT:
Enter a,b values:10
10
a is equal to b
NESTED IF STATEMENT: To check one condition within another. Take care of brace brackets within the
conditions.
Synatax:
if(condition)
{
if(condition)
{
Statement 1;
...
Statement n;
}
}
else
{
Statement 1;
....
Statement n;
}
Example:
void main()
{
int a,b;
printf(“\n Enter a and b values:”);
scanf(“%d %d ”,&a,&b);
if(a>b)
if((a!=0) && (b!=0))
printf(“\na and b both are +ve and a >b);
else
printf(“\n a is greater than b only”)
else
printf(“ \na is less than b”);
}
Output:
Enter a and b values:30
20
a and b both are +ve and a > b
C- TUTORIAL
LOOP STATEMENT: Loops are used to repeat a block of code. Being able to have your program repeatedly
execute a block of code is one of the most basic but useful tasks in programming
The “for loop” loops from one number to another number and increases by a specified value each time.
The “for loop” uses the following structure:
Example
#include<stdio.h>
void main()
{
int i;
for (i = 0; i < 10; i++)
{
printf ("Hello\n");
printf ("World\n");
}
return 0;
}
Note: A single instruction can be placed behind the “for loop” without the curly brackets.
Let’s look at the “for loop” from the example: We first start by setting the variable i to 0. This is where we start to
count. Then we say that the for loop must run if the counter i is smaller then ten. Last we say that every cycle i must
be increased by one (i++).
In the example we used i++ which is the same as using i = i +1. This is called incrementing. The instruction i++ adds
1 to i. If you want to subtract 1 from i you can use i–. It is also possible to use ++i or –i. The difference is is that with
++i the one is added before the “for loop” tests if i < 10. With i++ the one is added after the test i < 10.
The while loop:The while loop can be used if you don’t know how many times a loop must run. Here is an example:
#include<stdio.h>
void main()
{
int counter, howmuch;
scanf("%d", &howmuch);
counter = 0;
while ( counter < howmuch)
{
counter++;
printf("%d\n", counter);
C- TUTORIAL
}
return 0;
}
Let’s take a look at the example: First you must always initialize the counter before the while loop starts ( counter =
1). Then the while loop will run if the variable counter is smaller then the variable “how much”. If the input is ten,
then 1 through 10 will be printed on the screen. A last thing you have to remember is to increment the counter inside
the loop (counter++). If you forget this the loop becomes infinitive.
The do while loop: The “do while loop” is almost the same as the while loop. The “do while loop” has the following
form:
do
{
do something;
}
while (expression);
Do something first and then test if we have to continue. The result is that the loop always runs once. (Because the
expression test comes afterward). Take a look at an example:
#include<stdio.h>
void main()
{
int counter, howmuch;
scanf("%d", &howmuch);
counter = 0;
do
{
counter++;
printf("%d\n", counter);
}
while ( counter < howmuch);
return 0;
}
To exit a loop you can use the break statement at any time. This can be very useful if you want to stop running a loop
because a condition has been met other than the loop end condition. Take a look at the following example:
#include<stdio.h>
void main()
{
int i;
i = 0;
C- TUTORIAL
while ( i < 20 )
{
i++;
if ( i == 10)
break;
}
return 0;
}
In the example above, the while loop will run, as long i is smaller then twenty. In the while loop there is an if
statement that states that if i equals ten the while loop must stop (break).
With “continue;” it is possible to skip the rest of the commands in the current loop and start from the top again. (the
loop variable must still be incremented). Take a look at the example below:
#include<stdio.h>
void main()
{
int i;
i = 0;
while ( i < 20 )
{
i++;
continue;
printf("Nothing to see\n");
}
return 0;
}
In the example above, the printf function is never called because of the “continue;”.
What is a header file? Why do you need header files in C? Give examples
Header files are files that are included in other files prior to compilation by the C preprocessor. Some, such as
stdio.h , are defined at the system level and must included by any program using the standard I/O library. Header
files are also used to contain data declarations and defines that are needed by more than one program. Header
files should be functionally organized, i.e., declarations for separate subsystems should be in separate header files.
Also, if a set of declarations is likely to change when code is ported from one machine to another, those
declarations should be in a separate header file.
Information that is needed by several different files or functions is collected into a header file. A header file
contains C-language definitions and structures. Centralizing information into a header file facilitates the creation
and update of programs. Because #include statements are used to insert header files into a C-language program,
header files are often referred to as include files.
Preprocessor directives follow special syntax rules that are different from the normal syntax. They all begin
with the symbol # in column one and do not require a semicolon at the end. These preprocessor directives can
be grouped into three categories.
Ex : #include <math.h>
#include “string.h”
The filename can be specified with angle brackets or with a double quote. When the filename is included
within double quotes, the search for the file is made first in the current directory and then in the standard
directories. Alternatively, if filename is specified with angle brackets, the file is searched only in the standard
directories.
The compiler control directives are used for conditional compilation of the source program.
The following example illustrates the use of nested if else and switch statement for the same program.
C- TUTORIAL
Nested if – else Switch statement
{ {
{ case : 3
discount = 5; discount = 5;
} break;
24. When do you use a switch statement? Explain the syntax of switch with examples? 04
A switch statement is used when multiple branching is required in a program. Switch is a multi way branching
statement. The switch statement tests the value of a given variable against a list of case values and when a match is
found, a block of statements associated with that case is executed. The general form of the switch statement is as
follows.
Syntax:
switch (expr)
{
case value1 :
block1;
break;
case value2:
block2;
break;
------
------
default:
default-block;
break;
} Flow chart
C- TUTORIAL
The expr is an integer expression or character. value1, value2, …. are constant or constant expressions and are
known as case labels. Each of these values should be unique within a switch statement. block1, block2, …. are
statement lists and may contain zero or more statements.
When the switch statement is executed, the value of the expression is successively compared against the values
value1, value2…. If a case is found whose matches with the value of the expression, then the block of statements
that follows the case are executed.
Ex:
switch ( num)
{
case 1:
printf”(One”);
break;
case 2:
printf”(Two”);
break;
case 3:
printf(“Three”);
break;
…..
…..
}
What is an array? How are they declared ? What are the rules to be followed while using arrays,
Declaration of arrays:
An Array is declared as follows:
Type variable[n];
Where n is an integer indicating the maximum number of elements in the array.
Type refers to the data type of the array and variable is any valid C identifier used indicate the name of the array.
Example:
int marks[10];
float sales[50];
int purchase[10][20];
char name[20];
Rules to be followed while using arrays:
· Array subscript always starts with zero. So the first element will have the index as zero.
· The data type of all the elements of the array must be same.
· Array can be initialized at the time of declaration by specifying the value of each element within
braces. There must be an equal sign between the array name and braces and each value in the braces
must be separated by a comma.
· If all values are given in braces, the subscript in the array can be omitted.
· If an array is declared with subscript and fewer the number of values are given in the braces, the
cells are initialized from the beginning and remaining cells are left uninitialized.
· There is no way to initialize middle elements of the array.
· The compiler does not check for bounds of the array. While assigning values to the array elements,
the user has to see that the subscript value will be less than the maximum size of the array.
Distinguish between local and global variables
Local variables
These variables only exist inside the specific function that creates them. They are unknown to other functions and to
the main program. As such, they are normally implemented using a stack. Local variables cease to exist once the
function that created them is completed. They are recreated each time a function is executed or called.
Global variables
These variables can be accessed (i.e. known) by any function comprising the program. They are implemented by
associating memory locations with variable names. They do not get recreated if the function is recalled.
Example:
int x = 10; /* global variable */
main()
{
int a =5; /* local variable */
printf(“ A = %d x = %d”, a,x); /* output A = 5 x =10 */
f1();
C- TUTORIAL
printf(“ A = %d x = %d”, a,x); /* output A = 5 x =50 */
}
f1()
{
x = 50;
printf(“\n X = %d”, x); /* output X =50 */
}
Mention different categories of functions. Give examples.
Different categories of functions are as under:
A function can be defined as a subprogram which performs a particular sub task. Functions may be library
functions and user defined functions. Library functions are the built-in functions for performing certain operations
such as finding the sine of an angle, square root, printing and reading data values, etc. Example are printf(), scanf(),
sqrt(), abs(), etc. User defined function is a sub program written by the user for a particular task. They can be
codified and recalled whenever needed.
The user defined functions can be categorized as follows depending on the return type and arguments of the
function.
i) Functions with no arguments and no return type
When a function has no arguments, it does not receive any data from the calling function. Similarly, when it does not
have a return type, the calling function does not receive any data from the function. In effect, there is no data transfer
between the calling function and the called function.
function1() main()
{ {
------- printline();
------- printf(“KVGCE\n”);
function2(); printline();
} }
function2() printline()
{ {
------- printf(“--------------------“);
------ }
}
What are users defined functions? Why they are required for large and complex
programs.
A function is a self contained block of code that performs a particular task. Once a function has been designed and
packed, it can be treated as a “black box” that takes some data from the main program and returns a value. The inner
details of operation are invisible to the rest of the program.
Need of functions:
In a large and complex program, if the program is written with only a main() function, it leads to a number of
problems. The program may become too large and complex and as a result the task of debugging, testing and
maintaining becomes difficult. If a program is divided into functional parts, then each part may be independently
coded and later combined into a single unit. These functions are much easier to understand, debug, and test.
There are times when some type of operation is repeated at many points throughout a program. For instance,
factorial of a number. In such situations, we may repeat the statements wherever they are needed. Another approach
is to design a function that can be called and used wherever required. This saves both time and space.
The use of functions in C serves many advantages:
· It facilitates top-down modular programming . In this programming style, the high level of the overall
problem is solved first while the details of each lower-level function are addressed later.
· The length of a source program can be reduced by using functions at a appropriate places.
· It is easy to locate and isolate a faulty function for further investigations.
· A function may be used by many other programs. This means that a C programmer can build on what others
have already done, instead of starting from scratch.
ARRAY
Array by definition is a variable that hold multiple elements which has the same data type.
Declaring Arrays
We can declare an array by specify its data type, name and the number of elements the array holds between square brackets
immediately following the array name.
C- TUTORIAL
Here is the syntax:
data_type array_name[size];
For example, to declare an integer array which contains 100 elements we can do as follows:
int a[100];
There are some rules on array declaration. The data type can be any valid C data types including structure and
union. The array name has to follow the rule of variable and the size of array has to be a positive constant integer.
We can access array elements via indexes array_name[index]. Indexes of array starts from 0 not 1 so the highest
elements of an array is array_name[size-1].
Initializing Arrays
It is like a variable, an array can be initialized. To initialize an array, you provide initializing values which are
enclosed within curly braces in the declaration and placed following an equals sign after the array name. Here is an
example of initializing an integer array.
An array is a collection of similar data elements having a common name and the elements of the array are stored in
contiguous memory locations. The name of the array refers to the memory address of the first element of the array.
So with the help of name of array, all elements of the array can be accessed one after another in the memory
locations. So an array is similar to a pointer variable which holds the address of the memory location and can be used
for accessing the elements of the array.
An array cannot be used for storing address of another variable similar to a pointer and cannot be de-referenced with
* operator.
Example :
int marks[20]; is a array declaration statement used for storing marks of 20 students.