Uploaded by Dhanush Mahesh

First C Program and its Structure

advertisement
First C Program and its Structure
The first program that you write in any programming language is the "Hello
World" program. And in this we will learn, how to write the basic Hello
World program in C language.
We will learn to write the first C program and then will understand its
structure. First of all, let's have a look at how to write the Hello
World(simple and most basic) program in C language. Let's get started.
#include <stdio.h>
int main()
{
printf("Hello, World"); //single line comment
return 0;
/*
multi
line
comments
/*
}
Hello, World
NOTE: If you have not installed the C compiler in you local machine, first
do that to be able to run this program - Setup C Compiler
To run the above program, you will have to create a New file, copy-paste
the code in that file and save it with some name and .c extension or you can
use Turbo C to run it.
After successfully running the example, you will see the above output to the
console. Now, let's understand it step by step.
Essential Parts of the C Program
Given below are some of the different parts of a C Program:






Pre-processor
Header file
main() function
Variables
Statements & expressions
Comments
All these are essential parts of a C language program.
Pre-processor
The #include is the first statement of any C program. It is known as a preprocessor. The task of a pre-processor is to initialize the environment of the
program, i.e to link the program with the header files required in the
program.
So, when we say #include<stdio.h>, it is to inform the compiler to include
the stdio.h header file, which is standard I/O library, to the program
before executing it.
The standard I/O library lets you read input from the keyboard(i.e
standard in) and then write the output to the screen (i.e. standard out) and it
is an extremely useful library.
Header file
A Header file is a collection of built-in(readymade) functions, which we
can directly use in our program. Header files contain definitions of the
functions which can be incorporated into any C program by using pre-
processor #include statement with the header file. Standard header files are
provided with each compiler and cover a range of areas like string handling,
mathematical functions, data conversion, printing, and reading of variables.
With time, you will have a clear picture of what header files are, for now
consider it as a readymade collection of functions that comes packaged with
the C language and you can use them without worrying about how they
work, all you have to do is include the header file in your program.
To use any of the standard functions, the appropriate header file must be
included. This is done at the beginning of the C source file.
For example, to use the printf() function in a program, which is used to
display anything on the screen, the line #include <stdio.h> is required because
the header file stdio.h contains the printf() function. All header files will
have an extension .h
main() Function
The main() function is a function that must be there in every C program.
Everything inside this function in a C program will be executed. In the above
example, int written before the main() function is the return type of main()
function. We will discuss it in detail later. The curly braces { } just after
the main() function encloses the body of the main() function.
We will learn what functions are in upcoming.
Comments
We can add comments in our program to describe what we are doing in the
program. These comments are ignored by the compiler and are not executed.
To add a single line comment, start it by adding two forward
slashes // followed by the comment.
To add a multiline comment, enclose text between /* ... */ these.
Return Statement
A return statement is used to return a response to the caller function. It is
the last statement of any C function.
Return statements will make more sense when we will learn about functions
in C language.
Compile and Run C Program
To compile and run a C language program, you need a C compiler. To setup
a C language compiler in your Computer/laptop, there are two ways:
1. Download a full fledged IDE like Turbo C or Microsoft Visual C++,
which comes along with a C language compiler.
2. Or, you use any text editor to edit the program files and download the
C compiler separately.
Here we have a simple video, explaining how to setup Tubrbo C/C++ for
writing, compiling and running C programs.
Using an IDE - Turbo C
We will recommend you to use Turbo C IDE, oldest IDE for c
programming. It is freely available over internet and is good for a beginner.
Step 1 : Open turbo C IDE(Integrated Development Environment), click
on File and then click on New
Step 2 : Write the above example as it is
Step 3 : Click on compile or press Alt+f9 to compile the code
Step 4 : Click on Run or press Ctrl+f9 to run the code
Step 5 : Output
Difference between Compile and Run
You must be thinking why it is a 2 step process, first we compile the code
and then we run the code. So, compilation is the process where the compiler
checks whether the program is correct syntax wise, and there are no errors
in the syntax.
When we run a compiled program, then it actually executes the statements
inside the main() function.
C Language Basic Syntax Rules
C language syntax specify rules for sequence of characters to be written in
C language. In simple language it states how to form statements in a C
language program - How should the line of code start, how it should end,
where to use double quotes, where to use curly brackets etc.
The rule specify how the character sequence will be grouped together, to
form tokens. A smallest individual unit in C program is known as C Token.
Tokens are either keywords, identifier, constants, Variables or any symbol
which has some meaning in C language. A C program can also be called as
a collection of various tokens.
In the following program,
#include
int main()
{
printf("Hello,World");
return 0;
}
if we take any one statement:
printf("Hello,World");
Then the tokens in this statement are→ printf, (, "Hello,World", ) and ;.
So C tokens are basically the building blocks of a C program.
Semicolon ;
Semicolon ; is used to mark the end of a statement and beginning of another
statement. Absence of semicolon at the end of any statement, will mislead
the compiler to think that this statement is not yet finished and it will add
the next consecutive statement after it, which may lead to
compilation(syntax) error.
#include
int main()
{
printf("Hello,World")
return 0;
}
In the above program, we have omitted the semicolon from
the printf("...") statement, hence the compiler will think that starting
from printf uptill the semicolon after return 0 statement, is a single statement
and this will lead to compilation error.
Comments
Comments are plain simple text in a C program that are not compiled by the
compiler. We write comments for better understanding of the program.
Though writing comments is not compulsory, but it is recommended to
make your program more descriptive. It make the code more readable.
There are two ways in which we can write comments.
1. Using // This is used to write a single line comment.
2. Using /* */: The statements enclosed within /* and */ , are used to write
multi-line comments.
Example of comments :
// This is a comment
/* This is a comment */
/* This is a long
and valid comment */
// this is not
a valid comment
Some basic syntax rule for C program

C is a case sensitive language so all C instructions must be written in
lower case letter.

All C statement must end with a semicolon.

Whitespace is used in C to describe blanks and tabs.

Whitespace is required between keywords and identifiers. We will
learn about keywords and identifiers.
Keywords and Identifiers C
Tokens in C are defined as the smallest individual element in C and are the
basic building blocks of creating a program. It is classified into the
following categories. Here, we will study keywords and identifiers. Before
proceeding further do check the following topics:


Basic C Rules
Compile and Run C program

C program and its structure
Here is a quick video to explain all about keywords and Identifiers. Click
Here.
C Keywords:
Keywords are reserved words that have special meaning in the C language.
The meaning of C language keywords has already been described in the C
compiler. These meanings cannot be changed. Thus, keywords cannot be
used as Variables names because that would try to change the existing
meaning of the keyword, which is not allowed. There is a total of 32
keywords in the C language.
Example of keyword:
int marks;
List of Keywords in C:
auto
double
int
struct
break
else
long
switch
case
enum
register
typedef
const
extern
return
union
char
float
short
unsigned
continue
for
signed
volatile
default
goto
sizeof
void
do
if
static
while
Note:


A keyword name can not be used as a variable name.
Keywords must be written in lower case.

It specifies the type/kind of entity.
What are C Identifiers?
In C language identifiers are the names given to variables,
constants, functions, and user-defined data. These identifiers are defined
against a set of rules.
Rules for an Identifier:





An Identifier can only have alphanumeric characters(a-z , A-Z , 0-9)
and underscore(_).
The first character of an identifier can only contain alphabet(a-z, AZ) or underscore (_).
Identifiers
are
also
case
sensitive
in
C.
For
example, name and Name are two different identifiers in C.
Keywords are not allowed to be used as Identifiers.
No special characters, such as a semicolon, period, whitespaces, slash,
or comma are permitted to be used in or as an Identifier.
When we declare a variable or any function in C language program, to use
it we must provide a name to it, which identified it throughout the program,
for example:
int myvariable = "Studytonight";
Here myvariable is the name or identifier for the variable which stores the
value "Studytonight" in it.
Example: C Valid Identifiers
total, avg1, difference_1
Example: C Invalid Identifiers
int , char(reserved word)
x+y (special character '+')
Example of Keywords and Identifiers:
int money;
double salary;
Here, money, salary are identifiers, and int, double are keywords.
C Character set
In C language characters are grouped into the following categories,


Letters(all alphabets a to z & A to Z).
Digits (all digits 0 to 9).


Special characters, ( such as colon :, semicolon ;, period .,
underscore _, ampersand & etc).
White spaces.
Operators in C Language
C language supports a rich set of built-in operators. An operator is a symbol
that tells the compiler to perform a certain mathematical or logical
manipulation. Operators are used in programs to manipulate data and
variables.
Before moving forward with Operators in C language, Learn these topics
out to understand better :


Compile and run C Program
Variables in C language
C operators can be classified into following types:

Arithmetic operators

Relational operators

Logical operators

Bitwise operators

Assignment operators

Conditional operators

Special operators
Arithmetic operators
C supports all the basic arithmetic operators. The following table shows all
the basic arithmetic operators.
Operator
Description
+
adds two operands
-
subtract second operands from first
*
multiply two operand
/
divide numerator by denominator
%
remainder of division
++
Increment operator - increases integer value by one
--
Decrement operator - decreases integer value by one
Relational operators
The following table shows all relation operators supported by C.
Operator
Description
==
Check if two operand are equal
!=
Check if two operand are not equal.
>
Check if operand on the left is greater than operand on the right
<
Check operand on the left is smaller than right operand
>=
check left operand is greater than or equal to right operand
<=
Check if operand on left is smaller than or equal to right operand
Logical operators
C language supports following 3 logical operators. Suppose a = 1 and b = 0,
Operator
Description
Example
&&
Logical AND
(a && b) is false
||
Logical OR
(a || b) is true
!
Logical NOT
(!a) is false
Bitwise operators
Bitwise operators perform manipulations of data at bit level. These
operators also perform shifting of bits from right to left. Bitwise operators
are not applied to float or double.
Operator
Description
&
Bitwise AND
|
Bitwise OR
^
Bitwise exclusive OR
<<
left shift
>>
right shift
Now lets see truth table for bitwise &, | and ^
a
b
a&b
a|b
a^b
0
0
0
0
0
0
1
0
1
1
1
0
0
1
1
1
1
1
1
0
The bitwise shift operator, shifts the bit value. The left operand specifies the
value to be shifted and the right operand specifies the number of positions
that the bits in the value have to be shifted. Both operands have the same
precedence.
Example :
a = 0001000
Operator Description
Example
=
assigns values from right side operands to left side operand
a=b
+=
adds right operand to the left operand and assign the result to a+=b is same as
left
a=a+b
-=
subtracts right operand from the left operand and assign the a-=b is same as a=aresult to left operand
b
*=
mutiply left operand with the right operand and assign the a*=b is same as
result to left operand
a=a*b
/=
divides left operand with the right operand and assign the result a/=b is same as
to left operand
a=a/b
%=
calculate modulus using two operands and assign the result to a%=b is same as
left operand
a=a%b
b=2
a << b = 0100000
a >> b = 0000010
Assignment Operators
Assignment operators supported by C language are as follows.
Conditional operator
The conditional operators in C language are known by two more names
1. Ternary Operator
2. ? : Operator
It is actually the if condition that we use in C language decision making, but
using conditional operator, we turn the if condition statement into a short
and simple operator.
The syntax of a conditional operator is :
expression 1 ? expression 2: expression 3
Explanation:

The question mark "?" in the syntax represents the if part.

The first expression (expression 1) generally returns either true or
false, based on which it is decided whether (expression 2) will be
executed or (expression 3)

If (expression 1) returns true then the expression on the left side of "
: " i.e (expression 2) is executed.

If (expression 1) returns false then the expression on the right side of "
: " i.e (expression 3) is executed.
Special operator
Operator Description
Example
sizeof
Returns the size of an variable
sizeof(x) return size of the variable x
&
Returns the address of an variable
&x ; return address of the variable x
*
Pointer to a variable
*x ; will be pointer to a variable x
Data types in C Language
Data types specify how we enter data into our programs and what type of
data we enter. C language has some predefined set of data types to handle
various kinds of data that we can use in our program. These datatypes have
different storage capacities.
C language supports 2 different type of data types:
1. Primary data types:
These are fundamental data types in C namely integer( int), floating
point(float), character(char) and void.
2. Derived data types:
Derived data types are nothing but primary datatypes but a little
twisted
or
grouped
together
like array, stucture, union and pointers. These are discussed in
details later.
Data type determines the type of data a variable will hold. If a variable x is
declared as int. it means x can hold only integer values. Every variable which
is used in the program must be declared as what data-type it is.
Integer type
Integers are used to store whole numbers.
Size and range of Integer type on 16-bit machine:
Type
Size(bytes)
Range
int or signed int
2
-32,768 to 32767
unsigned int
2
0 to 65535
short int or signed short int
1
-128 to 127
unsigned short int
1
0 to 255
long int or signed long int
4
-2,147,483,648 to 2,147,483,647
unsigned long int
4
0 to 4,294,967,295
Floating point type
Floating types are used to store real numbers.
Size and range of Integer type on 16-bit machine
Type
Size(bytes)
Range
Float
4
3.4E-38 to 3.4E+38
double
8
1.7E-308 to 1.7E+308
long double
10
3.4E-4932 to 1.1E+4932
Character type
Character types are used to store characters value.
Size and range of Integer type on 16-bit machine
Type
Size(bytes)
Range
char or signed char
1
-128 to 127
unsigned char
1
0 to 255
void type
void type means no value. This is usually used to specify the type of
functions which returns nothing. We will get acquainted to this datatype as
we start learning more advanced topics in C language, like functions,
pointers etc.
Variables in C Language
When we want to store any information(data) on our computer/laptop, we
store it in the computer's memory space. Instead of remembering the
complex address of that memory space where we have stored our data, our
operating system provides us with an option to create folders, name them,
so that it becomes easier for us to find it and access it.
Similarly, in C language, when we want to use some data value in our
program, we can store it in a memory space and name the memory space so
that it becomes easier to access it.
The naming of an address is known as variable. Variable is the name of
memory location. Unlike constant, variables are changeable, we can change
value of a variable during execution of a program. A programmer can
choose a meaningful variable name. Example : average, height, age, total
etc.
Datatype of Variable
A variable in C language must be given a type, which defines what type of
data the variable will hold.
It can be:

char: Can hold/store a character in it.

int: Used to hold an integer.

float: Used to hold a float value.

double: Used to hold a double value.

void
Rules to name a Variable
1. Variable name must not start with a digit.
2. Variable name can consist of alphabets, digits and special symbols
like underscore _.
3. Blank or spaces are not allowed in variable name.
4. Keywords are not allowed as variable name.
5. Upper and lower case names are treated as different, as C is casesensitive, so it is suggested to keep the variable names in lower case.
Declaring, Defining and Initializing a variable
Declaration of variables must be done before they are used in the program.
Declaration does the following things.
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
3. Until the variable is defined the compiler doesn't have to worry about
allocating memory space to the variable.
4. Declaration is more like informing the compiler that there exist a
variable with following datatype which is used in the program.
5. A variable is declared
the main() function.
using
the extern keyword,
outside
extern int a;
extern float b;
extern double c, d;
Defining a variable means the compiler has to now assign a storage to the
variable because it will be used in the program. It is not necessary to declare
a variable using extern keyword, if you want to use it in your program. You
can directly define a variable inside the main() function and use it.
To define a function we must provide the datatype and the variable name.
We can even define multiple variables of same datatype in a single line by
using comma to separate them.
int a;
float b, c;
Initializing a variable means to provide it with a value. A variable can be
initialized and defined in a single statement, like:
int a = 10;
Let's write a program in which we will use some variables.
#include <stdio.h>
// Variable declaration(optional)
extern int a, b;
extern int c;
int main () {
/* variable definition: */
int a, b;
/* actual initialization */
a = 7;
b = 14;
/* using addition operator */
c = a + b;
/* display the result */
printf("Sum is : %d \n", c);
return 0;
}
Sum is : 21
You must be thinking how does this printf() works, right? Do not worry, we
will learn about it along with other ways to input and output datain C
language.
Difference between Variable and Identifier?
An Identifier is a name given to any variable, function, structure, pointer or
any other entity in a programming language. While a variable, as we have
just learned is a named memory location to store data which is used in the
program.
Identifier
Variable
Identifier is the name given to a variable, While, variable is used to name a memory
function etc.
location which stores data.
An identifier can be a variable, but not all
All variable names are identifiers.
indentifiers are variables.
Example:
// a variable
int studytonight;
// or, a function
int studytonight() {
..
Example:
// int variable
int a;
// float variable
float a;
}
Another great analogy to understand the difference between Identifier and
Variable is:
You can think of an Identifier int x to be a variable's name, but it can also be
a function's name int x() { } and still be an identifier.
Just like Obama is a name of a person, but also the name of a foundation.
C Input and Output
Input means to provide the program with some data to be used in the
program and Output means to display data on screen or write the data to a
printer or a file.
C programming language provides many built-in functions to read any
given input and to display data on screen when there is a need to output the
result.
Before moving forward with input and output in C language, check these
topics out to understand the concept better :



Data Types in C
Variables in C
Function in C
we will learn about such functions, which can be used in our program to
take input from user and to output the result on screen.
All these built-in functions are present in C header files, we will also specify
the name of header files in which a particular function is defined while
discussing about it.
scanf() and printf() functions
The standard input-output header file, named stdio.h contains the definition
of the functions printf() and scanf(), which are used to display output on
screen and to take input from user respectively.
#include<stdio.h>
void main()
{
// defining a variable
int i;
/*
displaying message on the screen
asking the user to input a value
*/
printf("Please enter a value...");
/*
reading the value entered by the user
*/
scanf("%d", &i);
/*
displaying the number as output
*/
printf( "\nYou entered: %d", i);
}
When you will compile the above code, it will ask you to enter a value.
When you will enter the value, it will display the value you have entered on
screen.
You must be wondering what is the purpose of %d inside
the scanf() or printf() functions. It is known as format string and this informs
the scanf() function, what type of input to expect and in printf() it is used to
give a heads up to the compiler, what type of output to expect.
Format String Meaning
%d
Scan or print an integer as signed decimal number
%f
Scan or print a floating point number
%c
To scan or print a character
%s
To scan or print a character string. The scanning ends at whitespace.
We can also limit the number of digits or characters that can be input or
output, by adding a number with the format string specifier,
like "%1d" or "%3s", the first one means a single numeric digit and the
second one means 3 characters, hence if you try to input 42,
while scanf() has "%1d", it will take only 4 as input. Same is the case for
output.
In C Language, computer monitor, printer etc output devices are treated as
files and the same process is followed to write output to these devices as
would have been followed to write the output to a file.
NOTE : printf() function returns the number of characters printed by it,
and scanf() returns the number of characters read by it.
int i = printf("studytonight");
In this program printf("studytonight"); will return 12 as result, which will be
stored in the variable i, because studytonight has 12 characters.
getchar() & putchar() functions
The getchar() function reads a character from the terminal and returns it as
an integer. This function reads only single character at a time. You can use
this method in a loop in case you want to read more than one character.
The putchar() function displays the character passed to it on the screen and
returns the same character. This function too displays only a single character
at a time. In case you want to display more than one characters,
use putchar() method in a loop.
#include <stdio.h>
void main( )
{
int c;
printf("Enter a character");
/*
Take a character as input and
store it in variable c
*/
c = getchar();
/*
display the character stored
in variable c
*/
putchar(c);
}
When you will compile the above code, it will ask you to enter a value.
When you will enter the value, it will display the value you have entered.
gets() & puts() functions
The gets() function reads a line from stdin(standard input) into the buffer
pointed to by str pointer, until either a terminating newline or EOF (end of
file) occurs. The puts() function writes the string str and a trailing newline
to stdout.
str → This is the pointer to an array of chars where the C string is stored.
(Ignore if you are not able to understand this now.)
#include<stdio.h>
void main()
{
/* character array of length 100 */
char str[100];
printf("Enter a string");
gets( str );
puts( str );
getch();
}
When you will compile the above code, it will ask you to enter a string.
When you will enter the string, it will display the value you have entered.
Difference between scanf() and gets()
The main difference between these two functions is that scanf() stops reading
characters when it encounters a space, but gets() reads space as character too.
If you enter name as Study Tonight using scanf() it will only read and
store Study and will leave the part after space. But gets() function will read
it completely.
Decision making in C
Decision making is about deciding the order of execution of statements
based on certain conditions or repeat a group of statements until certain
specified conditions are met. C language handles decision-making by
supporting the following statements,

if statement

switch statement

conditional operator statement (? : operator)

goto statement
Decision making with if statement
The if statement may be implemented in different forms depending on the
complexity of conditions to be tested. The different forms are,
1. Simple if statement
2. if....else statement
3. Nested if....else statement
4. Using else if statement
Simple if statement
The general form of a simple if statement is,
if(expression)
{
statement inside;
}
statement outside;
If the expression returns true, then the statement-inside will be executed,
otherwise statement-inside is skipped and only the statement-outside is
executed.
Example:
#include <stdio.h>
void main( )
{
int x, y;
x = 15;
y = 13;
if (x > y )
{
printf("x is greater than y");
}
}
x is greater than y
if...else statement
The general form of a simple if...else statement is,
if(expression)
{
statement block1;
}
else
{
statement block2;
}
If the expression is true, the statement-block1 is executed, else statementblock1 is skipped and statement-block2 is executed.
Example:
#include <stdio.h>
void main( )
{
int x, y;
x = 15;
y = 18;
if (x > y )
{
printf("x is greater than y");
}
else
{
printf("y is greater than x");
}
}
y is greater than x
Nested if....else statement
The general form of a nested if...else statement is,
if( expression )
{
if( expression1 )
{
statement block1;
}
else
{
statement block2;
}
}
else
{
statement block3;
}
if expression is false then statement-block3 will be executed, otherwise the
execution continues and enters inside the first if to perform the check for the
next if block, where if expression 1 is true the statement-block1 is
executed otherwise statement-block2 is executed.
#include <stdio.h>
void main( )
{
int a, b, c;
printf("Enter 3 numbers...");
scanf("%d%d%d",&a, &b, &c);
if(a > b)
{
if(a > c)
{
printf("a is the greatest");
}
else
{
printf("c is the greatest");
}
}
else
{
if(b > c)
{
printf("b is the greatest");
}
else
{
printf("c is the greatest");
}
}
}
else if ladder
The general form of else-if ladder is,
if(expression1)
{
statement block1;
}
else if(expression2)
{
statement block2;
}
else if(expression3 )
{
statement block3;
}
else
default statement;
The expression is tested from the top(of the ladder) downwards. As soon as
a true condition is found, the statement associated with it is executed.
Example :
#include <stdio.h>
void main( )
{
int a;
printf("Enter a number...");
scanf("%d", &a);
if(a%5 == 0 && a%8 == 0)
{
printf("Divisible by both 5 and 8");
}
else if(a%8 == 0)
{
printf("Divisible by 8");
}
else if(a%5 == 0)
{
printf("Divisible by 5");
}
else
{
printf("Divisible by none");
}
}
Points to Remember
1. In if statement, a single statement can be included without enclosing
it into curly braces { ... }
2. int a = 5;
3. if(a > 4)
printf("success");
No curly braces are required in the above case, but if we have more
than one statement inside if condition, then we must enclose them
inside curly braces.
4. == must be used for comparison in the expression of if condition, if
you use = the expression will always return true, because it performs
assignment not comparison.
5. Other than 0(zero), all other values are considered as true.
6. if(27)
printf("hello");
In above example, hello will be printed.
Switch statement in C
When you want to solve multiple option type problems, for example: Menu
like program, where one value is associated with each option and you need
to choose only one at a time, then, switch statement is used.
Switch statement is a control statement that allows us to choose only one
choice among the many given choices. The expression in switch evaluates to
return an integral value, which is then compared to the values present in
different cases. It executes that block of code which matches the case value.
If there is no match, then default block is executed(if present). The general
form of switch statement is,
switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
case value-3:
block-3;
break;
case value-4:
block-4;
break;
default:
default-block;
break;
}
Rules for using switch statement
1. The expression (after switch keyword) must yield an integer value i.e
the expression should be an integer or a variable or an expression that
evaluates to an integer.
2. The case label values must be unique.
3. The case label must end with a colon(:)
4. The next line, after the case statement, can be any valid C statement.
Points to Remember
1. We don't use those expressions to evaluate switch case, which may
return floating point values or strings or characters.
2. break statements are used to exit the switch block. It isn't necessary to
use break after each block, but if you do not use it, then all the
consecutive blocks of code will get executed after the matching block.
3. int i = 1;
4. switch(i)
5. {
6.
case 1:
7.
printf("A");
8.
// No break
case 2:
9.
printf("B");
10.
// No break
case 3:
11.
printf("C");
12.
break;
}
ABC
The output was supposed to be only A because only the first case
matches, but as there is no break statement after that block, the next
blocks are executed too, until it a break statement in encountered or
the execution reaches the end of the switch block.
13.
default case is executed when none of the mentioned case
matches the switch expression. The default case can be placed
anywhere in the switch case. Even if we don't include the default
case, switch statement works.
14.
Nesting of switch statements are allowed, which means you can
have switch statements inside another switch block. However,
nested switch statements should be avoided as it makes the program
more complex and less readable.
Example of switch statement
#include<stdio.h>
void main( )
{
int a, b, c, choice;
while(choice != 3)
{
/* Printing the available options */
printf("\n 1. Press 1 for addition");
printf("\n 2. Press 2 for subtraction");
printf("\n Enter your choice");
/* Taking users input */
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter 2 numbers");
scanf("%d%d", &a, &b);
c = a + b;
printf("%d", c);
break;
case 2:
printf("Enter 2 numbers");
scanf("%d%d", &a, &b);
c = a - b;
printf("%d", c);
break;
default:
printf("you have passed a wrong key");
printf("\n press any key to continue");
}
}
}
Difference between switch and if

if statements can evaluate float conditions. switch statements cannot
evaluate float conditions.

if statement can evaluate relational operators. switch statement cannot
evaluate relational
in switch statement.
operators
i.e
they
are
not
allowed
Loops in C
In any programming language including C, loops are used to execute a set
of statements repeatedly until a particular condition is satisfied.
How it Works
The below diagram depicts a loop execution,
As per the above diagram, if the Test Condition is true, then the loop is
executed, and if it is false then the execution breaks out of the loop. After
the loop is successfully executed the execution again starts from the Loop
entry and again checks for the Test condition, and this keeps on repeating.
The sequence of statements to be executed is kept inside the curly braces {
} known as the Loop body. After every execution of the loop
body, condition is verified, and if it is found to be true the loop body is
executed again. When the condition check returns false, the loop body is not
executed, and execution breaks out of the loop.
Types of Loop
There are 3 types of Loop in C language, namely:
1. while loop
2. for loop
3. do while loop
while loop
while loop can be addressed as an entry control loop. It is completed in 3
steps.

Variable initialization.(e.g int x = 0;)

condition(e.g while(x <= 10))

Variable increment or decrement ( x++ or x-- or x = x + 2 )
Syntax :
variable initialization;
while(condition)
{
statements;
variable increment or decrement;
}
Example: Program to print first 10 natural numbers
#include<stdio.h>
void main( )
{
int x;
x = 1;
while(x <= 10)
{
printf("%d\t", x);
/* below statement means, do x = x+1, increment x by 1*/
x++;
}
}
1 2 3 4 5 6 7 8 9 10
for loop
for loop is used to execute a set of statements repeatedly until a particular
condition is satisfied. We can say it is an open ended loop.. General format
is,
for(initialization; condition; increment/decrement)
{
statement-block;
}
In for loop we have exactly two semicolons, one after initialization and
second after the condition. In this loop we can have more than one
initialization or increment/decrement, separated using comma operator. But
it can have only one condition.
The for loop is executed as follows:
1. It first evaluates the initialization code.
2. Then it checks the condition expression.
3. If it is true, it executes the for-loop body.
4. Then it evaluate the increment/decrement condition and again follows
from step 2.
5. When the condition expression becomes false, it exits the loop.
Example: Program to print first 10 natural numbers
#include<stdio.h>
void main( )
{
int x;
for(x = 1; x <= 10; x++)
{
printf("%d\t", x);
}
}
1 2 3 4 5 6 7 8 9 10
Nested for loop
We can also have nested for loops, i.e one for loop inside another for loop.
Basic syntax is,
for(initialization; condition; increment/decrement)
{
for(initialization; condition; increment/decrement)
{
statement ;
}
}
Example: Program to print half Pyramid of numbers
#include<stdio.h>
void main( )
{
int i, j;
/* first for loop */
for(i = 1; i < 5; i++)
{
printf("\n");
/* second for loop inside the first */
for(j = i; j > 0; j--)
{
printf("%d", j);
}
}
}
1
21
321
4321
54321
do while loop
In some situations it is necessary to execute body of the loop before testing
the condition. Such situations can be handled with the help of dowhile loop. do statement evaluates the body of the loop first and at the end,
the condition is checked using while statement. It means that the body of the
loop will be executed at least once, even though the starting condition
inside while is initialized to be false. General syntax is,
do
{
.....
.....
}
while(condition)
Example: Program to print first 10 multiples of 5.
#include<stdio.h>
void main()
{
int a, i;
a = 5;
i = 1;
do
{
printf("%d\t", a*i);
i++;
}
while(i <= 10);
}
5 10 15 20 25 30 35 40 45 50
Jumping Out of Loops
Sometimes, while executing a loop, it becomes necessary to skip a part of
the loop or to leave the loop as soon as certain condition becomes true. This
is known as jumping out of loop.
1) break statement
When break statement is encountered inside a loop, the loop is immediately
exited and the program continues with the statement immediately following
the loop.
2) continue statement
It causes the control to go directly to the test-condition and then continue
the loop process. On encountering continue, cursor leave the current cycle of
loop, and starts with the next cycle.
Arrays in C
In C language, arrays are reffered to as structured data types. An array is
defined as finite ordered collection of homogenous data, stored in
contiguous memory locations.
Here the words,

finite means data range must be defined.

ordered means data must be stored in continuous memory addresses.

homogenous means data must be of similar data type.
Example where arrays are used,

to store list of Employee or Student names,

to store marks of students,

or to store list of numbers or characters etc.
Since arrays provide an easy way to represent data, it is classified amongst
the data
structures in
C.
Other
data
structures
in
c
are structure, lists, queues, trees etc. Array can be used to represent not
only simple list of data but also table of data in two or three dimensions.
Declaring an Array
Like any other variable, arrays must be declared before they are used.
General form of array declaration is,
data-type variable-name[size];
/* Example of array declaration */
int arr[10];
Here int is the data type, arr is the name of the array and 10 is the size of
array. It means array arr can only contain 10 elements of int type.
Index of an array starts from 0 to size-1 i.e first element of arr array will be
stored at arr[0] address and the last element will occupy arr[9].
Initialization of an Array
After an array is declared it must be initialized. Otherwise, it will
contain garbage value(any random value). An array can be initialized at
either compile time or at runtime.
Compile time Array initialization
Compile time initialization of array elements is same as ordinary variable
initialization. The general form of initialization of array is,
data-type array-name[size] = { list of values };
/* Here are a few examples */
int marks[4]={ 67, 87, 56, 77 }; // integer array initialization
float area[5]={ 23.4, 6.8, 5.5 }; // float array initialization
int marks[4]={ 67, 87, 56, 77, 59 }; // Compile time error
One important thing to remember is that when you will give more
initializer(array elements) than the declared array size than
the compiler will give an error.
#include<stdio.h>
void main()
{
int i;
int arr[] = {2, 3, 4};
// Compile time array initialization
for(i = 0 ; i < 3 ; i++)
{
printf("%d\t",arr[i]);
}
}
2 3 4
Runtime Array initialization
An array can also be initialized at runtime using scanf() function. This
approach is usually used for initializing large arrays, or to initialize arrays
with user specified values. Example,
#include<stdio.h>
void main()
{
int arr[4];
int i, j;
printf("Enter array element");
for(i = 0; i < 4; i++)
{
scanf("%d", &arr[i]);
//Run time array initialization
}
for(j = 0; j < 4; j++)
{
printf("%d\n", arr[j]);
}
}
Two dimensional Arrays
C language supports multidimensional arrays also. The simplest form of a
multidimensional array is the two-dimensional array. Both the row's and
column's index begins from 0.
Two-dimensional arrays are declared as follows,
data-type array-name[row-size][column-size]
/* Example */
int a[3][4];
An array can also be declared and initialized together. For example,
int arr[][3] = {
{0,0,0},
{1,1,1}
};
Note: We have not assigned any row value to our array in the above
example. It means we can initialize any number of rows. But, we must
always specify number of columns, else it will give a compile time error.
Here, a 2*3 multi-dimensional matrix is created.
Runtime initialization of a two dimensional Array
#include<stdio.h>
void main()
{
int arr[3][4];
int i, j, k;
printf("Enter array element");
for(i = 0; i < 3;i++)
{
for(j = 0; j < 4; j++)
{
scanf("%d", &arr[i][j]);
}
}
for(i = 0; i < 3; i++)
{
for(j = 0; j < 4; j++)
{
printf("%d", arr[i][j]);
}
}
}
String and Character Array
String is a sequence of characters that are treated as a single data item and
terminated by a null character '\0'. Remember that the C language does not
support strings as a data type. A string is actually a one-dimensional array
of characters in C language. These are often used to create meaningful and
readable programs.
If you don't know what an array in C means, you can check the C Array to
know about Array in the C language. Before proceeding further, check the
following articles:




C Function Calls
C Variables
C Datatypes
C Syntax Rules
For example: The string "home" contains 5 characters including
the '\0' character which is automatically added by the compiler at the end of
the string.
Declaring and Initializing a string variables:
// valid
char name[13] = "StudyTonight";
char name[10] = {'c','o','d','e','\0'};
// Illegal
char ch[3] = "hello";
char str[4];
str = "hello";
String Input and Output:




%s format specifier to read a string input from the terminal.
But scanf() function, terminates its input on the first white space it
encounters.
edit set conversion code %[..] that can be used to read a line
containing a variety of characters, including white spaces.
The gets() function can also be used to read character string with white
spaces
char str[20];
printf("Enter a string");
scanf("%[^\n]", &str);
printf("%s", str);
char text[20];
gets(text);
printf("%s", text);
String Handling Functions:
C language supports a large number of string handling functions that can be
used to carry out many of the string manipulations. These functions are
packaged in the string.h library. Hence, you must include string.h header
file in your programs to use these functions.
The following are the most commonly used string handling functions.
Method
Description
strcat()
It is used to concatenate(combine) two strings
strlen()
It is used to show the length of a string
strrev()
It is used to show the reverse of a string
strcpy()
Copies one string into another
strcmp()
It is used to compare two string
strcat() function in C:
Syntax:
strcat("hello", "world");
strcat() will add the string "world" to "hello" i.e ouput = helloworld.
strlen() and strcmp() function:
strlen() will return the length of the string passed to it and strcmp() will return
the ASCII difference between first unmatching character of two strings.
int j = strlen("studytonight");
int i=strcmp("study ", "tonight");
printf("%d %d",j,i);
12 -1
strcpy() function:
It copies the second string argument to the first string argument.
Example of strcpy() function:
#include<stdio.h>
#include<string.h>
int main()
{
char s1[50], s2[50];
strcpy(s1, "StudyTonight");
strcpy(s2, s1);
printf("%s\n", s2);
return(0);
}
StudyTonight
strrev() function:
It is used to reverse the given string expression.
Code snippet for strrev():
#include <stdio.h>
int main()
{
char s1[50];
printf("Enter your string: ");
gets(s1);
printf("\nYour reverse string is: %s",strrev(s1));
return(0);
}
Enter your string: studytonight
Your reverse string is: thginotyduts
Storage classes in C
In C language, each variable has a storage class which decides the following
things:

scope i.e where the value of the variable would be available inside a
program.

default initial value i.e if we do not explicitly initialize that variable,
what will be its default initial value.

lifetime of that variable i.e for how long will that variable exist.
The following storage classes are most oftenly used in C programming,
1. Automatic variables
2. External variables
3. Static variables
4. Register variables
Automatic variables: auto
Scope: Variable defined with auto storage class are local to the function
block inside which they are defined.
Default Initial Value: Any random value i.e garbage value.
Lifetime: Till the end of the function/method block where the variable is
defined.
A variable declared inside a function without any storage class specification,
is by default an automatic variable. They are created when a function is
called and are destroyed automatically when the function's execution is
completed. Automatic variables can also be called local variables because
they are local to a function. By default they are assigned garbage value by
the compiler.
#include<stdio.h>
void main()
{
int detail;
// or
auto int details;
}
//Both are same
External or Global variable
Scope: Global i.e everywhere in the program. These variables are not bound
by any function, they are available everywhere.
Default initial value: 0(zero).
Lifetime: Till the program doesn't finish its execution, you can access
global variables.
A variable that is declared outside any function is a Global Variable.
Global variables remain available throughout the program execution. By
default, initial value of the Global variable is 0(zero). One important thing
to remember about global variable is that their values can be changed by
any function in the program.
#include<stdio.h>
int number;
// global variable
void main()
{
number = 10;
printf("I am in main function. My value is %d\n", number);
fun1();
//function calling, discussed in next topic
fun2();
//function calling, discussed in next topic
}
/* This is function 1 */
fun1()
{
number = 20;
printf("I am in function fun1. My value is %d", number);
}
/* This is function 1 */
fun2()
{
printf("\nI am in function fun2. My value is %d", number);
}
I am in function main. My value is 10
I am in function fun1. My value is 20
I am in function fun2. My value is 20
Here the global variable number is available to all three functions and thus,
if one function changes the value of the variable, it gets changed in every
function.
Note: Declaring the storage class as global or external for all the variables
in a program can waste a lot of memory space because these variables have
a lifetime till the end of the program. Thus, variables, which are not needed
till the end of the program, will still occupy the memory and thus, memory
will be wasted.
extern keyword
The extern keyword is used with a variable to inform the compiler that this
variable is declared somewhere else. The extern declaration does not allocate
storage for variables.
Problem when extern is not used
int main()
{
a = 10;
//Error: cannot find definition of variable 'a'
printf("%d", a);
}
Example using extern in same file
int main()
{
extern int x; //informs the compiler that it is defined somewhere else
x = 10;
printf("%d", x);
}
int x;
//Global variable x
Static variables
Scope: Local to the block in which the variable is defined
Default initial value: 0(Zero).
Lifetime: Till the whole program doesn't finish its execution.
A static variable tells the compiler to persist/save the variable until the end
of program. Instead of creating and destroying a variable every time when
it comes into and goes out of scope, static variable is initialized only once
and remains into existence till the end of the program. A static variable can
either be internal or external depending upon the place of declaration. Scope
of internal static variable remains inside the function in which it is
defined. External static variables remain restricted to scope of file in which
they are declared.
They are assigned 0 (zero) as default value by the compiler.
#include<stdio.h>
void test(); //Function declaration (discussed in next topic)
int main()
{
test();
test();
test();
}
void test()
{
static int a = 0;
a = a + 1;
printf("%d\t",a);
}
1 2 3
Register variable
//a static variable
Scope: Local to the function in which it is declared.
Default initial value: Any random value i.e garbage value
Lifetime: Till the end of function/method block, in which the variable is
defined.
Register variables inform the compiler to store the variable in CPU register
instead of memory. Register variables have faster accessibility than a
normal variable. Generally, the frequently used variables are kept in
registers. But only a few variables can be placed inside registers. One
application of register storage class can be in using loops, where the variable
gets used a number of times in the program, in a very short span of time.
NOTE: We can never get the address of such variables.
Syntax :
register int number;
Note: Even though we have declared the storage class of our
variable number as register, we cannot surely say that the value of the
variable would be stored in a register. This is because the number of
registers in a CPU are limited. Also, CPU registers are meant to do a lot of
important work. Thus, sometimes they may not be free. In such scenario,
the variable works as if its storage class is auto.
Which storage class should be used and when
To improve the speed of execution of the program and to carefully use the
memory space occupied by the variables, following points should be kept in
mind while using storage classes:

We should use static storage class only when we want the value of the
variable to remain same every time we call it using different function
calls.

We should use register storage class only for those variables that are
used in our program very oftenly. CPU registers are limited and thus
should be used carefully.

We should use external or global storage class only for those variables
that are being used by almost all the functions in the program.

If we do not have the purpose of any of the above mentioned storage
classes, then we should use the automatic storage class.
Functions in C
A function is a block of code that performs a particular task.
There are many situations where we might need to write same line
of code for more than once in a program. This may lead to
unnecessary repetition of code, bugs and even becomes boring for
the programmer. So, C language provides an approach in which you
can declare and define a group of statements once in the form of a
function and it can be called and used whenever required.
These functions defined by the user are also know as User-defined
Functions
C functions can be classified into two categories,
1. Library functions
2. User-defined functions
Library functions are those functions which are already defined in
C library, example printf(), scanf(), strcat() etc. You just need to include
appropriate header files to use these functions. These are already
declared and defined in C libraries.
A User-defined functions on the other hand, are those functions
which are defined by the user at the time of writing program. These
functions are made for code reusability and for saving time and
space.
Benefits of Using Functions
1. It provides modularity to your program's structure.
2. It makes your code reusable. You just have to call the function
by its name to use it, wherever required.
3. In case of large programs with thousands of code lines,
debugging and editing becomes easier if you use functions.
4. It makes the program more readable and easy to understand.
Function Declaration
General syntax for function declaration is,
returntype functionName(type1 parameter1, type2
parameter2,...);
Copy
Like any variable or an array, a function must also be declared
before its used. Function declaration informs the compiler about the
function name, parameters is accept, and its return type. The actual
body of the function can be defined separately. It's also called
as Function Prototyping. Function declaration consists of 4 parts.

returntype

function name

parameter list

terminating semicolon
returntype
When a function is declared to perform some sort of calculation or
any operation and is expected to provide with some result at the
end, in such cases, a return statement is added at the end of
function body. Return type specifies the type of
value(int, float, char, double) that function is expected to return to the
program which called the function.
Note: In case your function doesn't return any value, the return type
would be void.
functionName
Function name is an identifier and it specifies the name of the
function. The function name is any valid C identifier and therefore
must follow the same naming rules like other variables in C
language.
parameter list
The parameter list declares the type and number of arguments that
the function expects when it is called. Also, the parameters in the
parameter list receives the argument values when the function is
called. They are often referred as formal parameters.
Time for an Example
Let's write a simple program with a main() function, and a user
defined function to multiply two numbers, which will be called from
the main() function.
#include<stdio.h>
int multiply(int a, int b);
declaration
int main()
{
int i, j, result;
// function
printf("Please enter 2 numbers you want to
multiply...");
scanf("%d%d", &i, &j);
result = multiply(i, j);
call
// function
printf("The result of muliplication is: %d",
result);
return 0;
}
int multiply(int a, int b)
{
return (a*b);
// function defintion,
this can be done in one line
}
Copy
Function definition Syntax
Just like in the example above, the general syntax of function
definition is,
returntype functionName(type1 parameter1, type2
parameter2,...)
{
// function body goes here
}
Copy
The first line returntype functionName(type1 parameter1, type2
parameter2,...) is known as function header and the statement(s)
within curly braces is called function body.
Note: While defining a function, there is no semicolon(;) after the
parenthesis in the function header, unlike while declaring the
function or calling the function.
functionbody
The function body contains the declarations and the
statements(algorithm) necessary for performing the required task.
The body is enclosed within curly braces { ... } and consists of three
parts.

local variable declaration(if required).

function statements to perform the task inside the function.

a return statement to return the result evaluated by the
function(if return type is void, then no return statement is
required).
Calling a function
When a function is called, control of the program gets transferred
to the function.
functionName(argument1, argument2,...);
Copy
In the example above, the statement multiply(i, j); inside
the main() function is function call.
Passing Arguments to a function
Arguments are the values specified during the function call, for
which the formal parameters are declared while defining the
function.
It is possible to have a function with parameters but no return type.
It is not necessary, that if a function accepts parameter(s), it must
return a result too.
While declaring the function, we have declared two
parameters a and b of type int. Therefore, while calling that function,
we need to pass two arguments, else we will get compilation error.
And the two arguments passed should be received in the function
definition, which means that the function header in the function
definition should have the two parameters to hold the argument
values. These received arguments are also known as formal
parameters. The name of the variables while declaring, calling and
defining a function can be different.
Returning a value from function
A function may or may not return a result. But if it does, we must
use the return statement to output the result. return statement also
ends the function execution, hence it must be the last statement of
any function. If you write any statement after the return statement, it
won't be executed.
The datatype of the value returned using the return statement
should be same as the return type mentioned at function
declaration and definition. If any of it mismatches, you will get
compilation error.
In the next tutorial, we will learn about the different types of user
defined functions in C language and the concept of Nesting of
functions which is used in recursion.
ype of User-defined Functions in C
There can be 4 different types of user-defined functions, they are:
1. Function with no arguments and no return value
2. Function with no arguments and a return value
3. Function with arguments and no return value
4. Function with arguments and a return value
Below, we will discuss about all these types, along with program
examples.
Function with no arguments and no return value
Such functions can either be used to display information or they are
completely dependent on user inputs.
Below is an example of a function, which takes 2 numbers as input
from user, and display which is the greater number.
#include<stdio.h>
void greatNum();
// function declaration
int main()
{
greatNum();
return 0;
}
// function call
void greatNum()
// function definition
{
int i, j;
printf("Enter 2 numbers that you want to
compare...");
scanf("%d%d", &i, &j);
if(i > j) {
printf("The greater number is: %d", i);
}
else {
printf("The greater number is: %d", j);
}
}
Copy
Function with no arguments and a return value
We have modified the above example to make the
function greatNum() return the number which is greater amongst the
2 input numbers.
#include<stdio.h>
int greatNum();
// function declaration
int main()
{
int result;
result = greatNum();
// function call
printf("The greater number is: %d", result);
return 0;
}
int greatNum()
// function definition
{
int i, j, greaterNum;
printf("Enter 2 numbers that you want to
compare...");
scanf("%d%d", &i, &j);
if(i > j) {
greaterNum = i;
}
else {
greaterNum = j;
}
// returning the result
return greaterNum;
}
Copy
Function with arguments and no return value
We are using the same function as example again and again, to
demonstrate that to solve a problem there can be many different
ways.
This time, we have modified the above example to make the
function greatNum() take two int values as arguments, but it will not
be returning anything.
#include<stdio.h>
void greatNum(int a, int b);
declaration
int main()
{
// function
int i, j;
printf("Enter 2 numbers that you want to
compare...");
scanf("%d%d", &i, &j);
greatNum(i, j);
// function call
return 0;
}
void greatNum(int x, int y)
definition
// function
{
if(x > y) {
printf("The greater number is: %d", x);
}
else {
printf("The greater number is: %d", y);
}
}
Copy
Function with arguments and a return value
This is the best type, as this makes the function completely
independent of inputs and outputs, and only the logic is defined
inside the function body.
#include<stdio.h>
int greatNum(int a, int b);
declaration
// function
int main()
{
int i, j, result;
printf("Enter 2 numbers that you want to
compare...");
scanf("%d%d", &i, &j);
result = greatNum(i, j); // function call
printf("The greater number is: %d", result);
return 0;
}
int greatNum(int x, int y)
definition
// function
{
if(x > y) {
return x;
}
else {
return y;
}
}
Copy
Nesting of Functions
C language also allows nesting of functions i.e to use/call one
function inside another function's body. We must be careful while
using nested functions, because it may lead to infinite nesting.
function1()
{
// function1 body here
function2();
// function1 body here
}
Copy
If function2() also has a call for function1() inside it, then in that
case, it will lead to an infinite nesting. They will keep calling each
other and the program will never terminate.
Not able to understand? Lets consider that inside
the main() function, function1() is called and its execution starts,
then inside function1(), we have a call for function2(), so the control
of program will go to the function2(). But as function2() also has a
call to function1() in its body, it will call function1(), which will again
call function2(), and this will go on for infinite times, until you
forcefully exit from program execution.
What is Recursion?
Recursion is a special way of nesting functions, where a function
calls itself inside it. We must have certain conditions in the function
to break out of the recursion, otherwise recursion will occur infinite
times.
function1()
{
// function1 body
function1();
// function1 body
}
Copy
Example: Factorial of a number using Recursion
#include<stdio.h>
int factorial(int x);
function
//declaring the
void main()
{
int a, b;
printf("Enter a number...");
scanf("%d", &a);
b = factorial(a);
named factorial
//calling the function
printf("%d", b);
}
int factorial(int x) //defining the function
{
int r = 1;
if(x == 1)
return 1;
else
r = x*factorial(x-1);
since the function calls itself
//recursion,
return r;
}
Copy
Similarly, there are many more applications of recursion in C
language. Go to the programs section, to find out more programs
using recursion.
Now that we have learned about the Stack in Data Structure, you
can also check out these topics:


Types of Function calls
Passing Array to function
Download