Professional Documents
Culture Documents
1. Mother language
2. System programming language
3. Procedure-oriented programming language
4. Structured programming language
5. Mid level programming language
1) C as a mother language
C language is considered as the mother language of all the modern
languages because most of the compilers, JVMs, Kernals etc. are
written in C language and most of languages follows c syntax e.g. C++,
Java etc.
It provides the core concepts like array, functions, file handling etc. that
is being used in many languages like C++, java, C# etc.
High Level language is not specific to one machine i.e. machine independent. It is
easy to understand.
History of C Language
Features of C
C is the widely used language. It provides a lot of features that are given below.
Simple
Portability
Powerful
Platform dependent
Structure oriented
Case sensitive
Compiler based
Modularity
Use of Pointers
1) Simple
C is a simple language in the sense that it provides structured approach (to
break the problem into parts), rich set of library functions, data types etc.
5) Rich Library
C provides a lot of inbuilt functions that makes the development fast.
6) Memory Management
It supports the feature of dynamic memory allocation. In C language, we can
free the allocated memory at any time by calling the free() function.
7) Speed
The compilation and execution time of C language is fast.
8) Platform dependent
A language is said to be platform dependent whenever the program is execute in the
same operating system where that was developed and compiled but not run and
execute on other operating system. C is platform dependent programming language.
When we can copy .exe file to any other computer which contain window operating
system then it works properly, because the native code of application an operating
system is same. But this exe file is not execute on other operation system
8) Pointer
C provides the feature of pointers. We can directly interact with the memory by
using the pointers. We can use pointers for memory, structures, functions,
array etc.
9) Recursion
In c, we can call the function within the function. It provides code reusability
for every function.
10) Extensible
C language is extensible because it can easily adopt new features.
Installation of TC
Installation of TC is very simple just download turbo C or C++ and run .exe files
When you install the Turbo C compiler on your system, then TC directory is created on the hard disk and various sub directories
Previously Turbo C are not work properly on Window 7 and its above versions. Here you can get Turbo C for Window 7 and its
above versions.
Source Code
Object Code
Compiler in C
A compiler is system software which converts programming language code into binary format in single steps. In other words
Compiler is a system software which can take input from other any programming language and convert it into lower level machine
dependent language.
Interpreter
It is system software which is used to convert programming language code into binary format in step by step process.
Assembler
An assembler is system software which is used to convert the assembly language instruction into binary format in step by step
process. An assembler is system software which is used to convert the assembly language instruction into binary format.
Compiler Vs Interpreter
No Compiler Interpreter
Interpreter
takes Single
1 Compiler takes Entire program as input at a time. instruction as
input at a
time.
No
Intermediate
2
Object code is
generated
It execute
conditional
control
3 It execute conditional control statements fastly.
statements
slower than
Compiler
Less memory
4 More memory is required.
is required.
Every time
higher level
program is
5 Program need not to be compiled every time
converted into
lower level
program
It display error
after each
6 It display error after entire program is checked instruction
interpreted (if
any)
Example:
7 Example: C
BASIC
First C Program -
Before starting the abcd of C language, you need to learn how to write, compile and run the first c
program. To write the first c program, open the C console and write the following code:
Different parts of C program
Pre-processor
Header file
Function
Variables
Comments
Pre-processor- #include is the first word of any C program. It is also known as a pre-processor. 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.
So, when we say #include <stdio.h> it is to inform the compiler to include the stdio.h header file to the program
before executing it.
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 covers
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, as of now consider as a readymade piece of function
which 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:
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 about it in detail later. The curly braces { } just after
the main() function encloses the body of main() function.
We will learn what functions are in upcoming tutorials.
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 slashses // followed by the comment.
To add multiline comment, enclode it between /* .... */, just like in the program above.
NOTE –1. Comments are not case sensitive.
2. Nested Comments are not possible, that means comments within comments.
Example
void main()
/*
/* comments */
*/
Flow of C Program
The C program follows many steps in execution. To understand the flow of C program well, let us see a simple
program first.
File: simple.c
#include <stdio.h>
int main(){
printf("Hello C Language"); return 0;
Execution Flow:
Let's try to understand the flow of above program by the figure given below.
2) Expanded source code is sent to compiler which compiles the code and converts
it into assembly code.
Machine
or object
code
Assembler
3) The assembly code is sent to assembler which assembles the code and converts
it into object code. Now a simple.obj file is generated.
4) The object code is sent to linker which links it to the library such as header files.
Then it is converted into executable code. A simple.exe file is generated.
5) The executable code is sent to loader which loads it into memory and then it is
executed. After execution, output is sent to console.
Moduler Approach:
It is better to divide a large system into modules. In terms of programming, module is logically a welldefined
part of program. Each module is a separate part of the program. It is easy to modify a program
written with modular approach because changes in one module don't affect other modules of program.
It is also easy to check bugs in the program in module level programming.
Programming Languages:
The programming languages can be classified into
Two types-
1. High level languages
2. Low level languages
High-Level Languages:
High-level languages are designed keeping in mind the features of portability i.e. these languages are
machine independent. These are English like languages, so it is easy to write and understand the programs
of high-level language. While programming in a high level languag\e, the programmer is not concerned
with the low level details, and so the whole attention can be paid to the logic of the problem being
solved. For translating a high-level language program into machine language, compiler or interpreter is
used. Every language has its own compiler or interpreter. Some languages in this category are- FORTRAN,
COBOL, BASIC, Pascal etc.
Assembly Language:
The modified form Of machine level language called assembly language. In assembly language instructions are
given in English
Like words, such as MOV, ADD, and SUB etc. So it is easier to write and understand assembly programs,
Since a computer can understand only machine level language, hence assembly language program must
be translated into machine language. The translator that is used for translating is called "assembler"
Although writing programs in assembly language is a bit easier, but still the programmer has to know
all the low level details related with the hardware of a computer. In assembly language, data is stored
in computer registers and each computer has different set of registers. Hence the assembly language
program is also not portable. Since the low level languages are related with the hardware, hence the
execution of a low-level program is faster.
Translators :
We know that computers can understand only machine level language, which is in binary 1 or O. It
Is difficult to write and maintain programs in machine level language. So the need to convert
the code of high-level and low-level languages into machine level language and translators are used for
this purpose.
The three types of translators used are-
• Assembler
• Compiler
• Interpreter
Assembler: Assembler is used for converting the code of low-level language (assembly language) into
machine level Language.
Compilers and interpreters are used to convert the code of high-level language into machine language.
Compiler and interpreter perform the same task. But difference in their working. A compiler searches all the
errors of program and lists them. If the program is error free then it converts the code of program into machine
code.
An interpreter checks the errors of program statement by statement. After checking one statement, it
converts that statement into machine code and then executes that statement. This process continues
until the last statement of program or an errorless statement occurs.
keywords has already been described to the C compiler. These meaning cannot be changed. Thus, keywords
A variable is a name of memory location. It is used to store data. Its value can be changed and it can be reused many times.
NOTE (1.
If no input values are assigned by the user than system will gives a default value called
garbage value.
Example - a
1. An Identifier can only have alphanumeric characters(a-z , A-Z , 0-9) and underscore(_).
2. The first character of an identifier can only contain alphabet(a-z , A-Z) or underscore (_).
3. Identifiers are also case sensitive in C. For example name and Name are two different identifiers in C.
4. Keywords are not allowed to be used as Identifiers.
5. No special characters, such as semicolon, period, whitespaces, slash or comma are permitted to be used in or as
6. Maximum length of variable is 8 characters depend on compiler and operation system. Ansi
7. Every variable name always should exist in the left hand side of assignment operator (invalid ->
Identifier.
Example -
1. int a;
2. int _ab;
3. int a30;
Types of Variables in C
1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable
Local Variable
A variable that is declared inside the function or block is called local variable.
1. void function1(){
2. int x=10;//local variable
3. }
Global Variable
A variable that is declared outside the function or block is called global variable. Any function can
change the value of the global variable. It is available to all the functions.
Static Variable
1. void function1(){
2. int x=10;//local variable
3. static int y=10;//static variable
4. x=x+1;
5. y=y+1;
6. printf("%d,%d",x,y);
7. }
If you call this function many times, local variable will print the same value for each function call
e.g, 11,11,11 and so on. But static variable will print the incremented value in each function call
e.g. 11, 12, 13 and so on.
Automatic Variable
All variables in C that is declared inside the block, are automatic variables by default. By we can
explicitly declare automatic variable using auto keyword.
1. void main(){
2. int x=10;//local variable (also automatic)
3. auto int y=20;//automatic variable
4. }
External Variable
We can share a variable in multiple C source files by using external variable. To declare a external
variable, you need to use extern keyword.
myfile.h
1. #include "myfile.h"
2. #include <stdio.h>
3. void printValue(){
4. printf("Global variable: %d", global_variable);
5. }
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.
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
% remainder of division
Relational operators
The following table shows all relation operators supported by C .
Operator Description
> Check if operand on the left is greater than operand on the right
|| Logical OR (a || b) is true
Operator Description
| Bitwise OR
^ Bitwise exclusive OR
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
b = 2
a << b = 0100000
a >> b = 0000010
Assignment Operators
Assignment operators supported by C language are as follows.
= 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
result to left operand a=a-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 a/=b is same as
result 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
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 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
A data type specifies the type of data that a variable can store such as integer, floating, character
etc.
The basic data types are integer-based and floating-point based. C language supports both signed
and unsigned literals.
The memory size of basic data types may change according to 32 or 64 bit operating system.
Let's see the basic data types. Its size is given according to 32 bit architecture.
float 4 byte
double 8 byte
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.
Types of Constant in C
It is an identifier whose value can not be changed at the execution time of program. In general constant can be used to represent
If set of characters are enclosed between double cotes " " known as string character constant.
Declare constant
Example
#include<stdio.h>
#include<conio.h>
void main()
printf("%d",a);
getch();
}
1. int value=10+20*10;
The value variable will contain 210 because * (multiplicative operator) is evaluated before + (additive
operator).
Escape Sequence in C
Escape Sequence Meaning
Backslash \a Alarm or
Beep
\b Backspace
\f Form Feed
\n New Line
\r Carriage
Return
\t Tab
(Horizontal)
\v Vertical Tab
\\ Backslash
\' Single
Quote
\" Double
Quote
1. #include<stdio.h>
2. int main(){
3. int number=50;
4. printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");
5. return 0;
} Output:
You
are
learning
'c' language
"Do you know C language"
6.
\? Question
Mark
\nnn octal
number
\xhh hexadecimal
number
\0 Null
List of Constants in C
Constant Example
Register variables are also local variables, but stored in register memory. Whereas, auto variables are stored in
Advantages: The register variables are faster than remaining variables, because register variable are stored in
Limitation: But, only limited variables can be used as register since register size is very low. (16 bits, 32 bits or 64
bits).
Example
void main()
++a;
printf("Enter a value:");
scanf("%d",&a);
--a;
getch();
Output
Explanation
In scanf() function if address is provided for the register variable then it will give error, if addition is not provided it normally work.
Register storage class specifier just recommended to the compiler to hold the variable in CPU register if the memory is available or else stored in
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.
1. Automatic variables
2. External variables
3. Static variables
4. Register variables
#include<stdio.h>
void main()
{
int detail;
// or
auto int details; //Both are same
}
#include<stdio.h>
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);
}
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);
}
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, staticvariable is initialized only once and remains into existence till the end of the program. A staticvariable 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>
int main()
{
test();
test();
test();
}
void test()
{
static int a = 0; //a static variable
a = a + 1;
printf("%d\t",a);
}
1 2 3
Register 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 :
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.
Function
A function is a group of statements that together perform a specific task. Every C program has at least one function, which is
main().
Function are used for divide a large code into module, due to this we can easily debug and maintain the code. For
example if we write a calculator programs at that time we can write every logic in a separate function (For addition
sum(), for subtraction sub()). Any function can be called many times.
Advantage of Function
Code Re-usability
Type of Function
Library function
Library functions are those which are predefined in C compiler. The implementation part of pre-defined functions is
available in library files that are .lib/.obj files. .lib or .obj files are contained pre-compiled code. printf(), scanf(),
All predefined function are contained limited task only that is for what purpose function is designed
In implementation whenever a predefined function is not supporting user requirement then go for
These functions are created by programmer according to their requirement for example suppose you want to
create a function for add two number then you create a function with name sum() this type of function is called user
defined function.
calling a function.
When we call any function control goes to function body and execute entire code. For call any function just write name of function and if any parameter is
#include<stdio.h>
#include<conio.h>
clrsct();
int a=10,b=20, c;
c=a+b;
void main()
{
Output
Sum: 30
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
goto statement
1. Simple if statement
2. if....else 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 statement-block1 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
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.
Example:
#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 ifcondition, 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
6. if(27)
printf("hello");
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, switchstatement 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.
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
3. int i = 1;
4. switch(i)
5. {
6. case 1:
7. printf("A"); // No break
8. case 2:
9. printf("B"); // No break
10. case 3:
11. printf("C");
12. break;
}
A B C
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.
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");
}
}
}
if statements can evaluate float conditions. switch statements cannot evaluate floatconditions.
if statement can evaluate relational operators. switch statement cannot evaluate relational operators i.e they are not allowed in switch statement.
How to use 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.
Syntax :
variable initialization;
while(condition)
{
statements;
variable increment or decrement;
}
#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,
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.
#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
#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);
}
}
}
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 do-
while 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)
#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
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,
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.
#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]);
}
}
Output - 2 3 4
next>><<prev
char str[4];
str = "hell"; // Illegal
#include<stdio.h>
#include<string.h>
void main()
{
char str[20];
printf("Enter a string");
scanf("%[^\n]", &str); //scanning the whole string, including the white spaces
printf("%s", str);
}
Another method to read character string with white spaces from terminal is by using the gets()function.
char text[20];
gets(text);
printf("%s", text);
Method Description
strcat() function
strcat("hello", "world");
strcat() function will add the string "world" to "hello" i.e it will ouput helloworld.
strlen() function
strlen() function will return the length of the string passed to it.
int j;
j = strlen("studytonight");
printf("%d",j);
12
strcmp() function
strcmp() function will return the ASCII difference between first unmatching character of two strings.
int j;
j = strcmp("study", "tonight");
printf("%d",j);
-1
strcpy() function
It copies the second string argument to the first string argument.
#include<stdio.h>
#include<string.h>
int main()
{
char s1[50];
char s2[50];
printf("%s\n", s2);
return(0);
}
StudyTonight
strrev() function
It is used to reverse the given string expression.
#include<stdio.h>
int main()
{
char s1[50];
printf("Enter your string: ");
gets(s1);
printf("\nYour reverse string is: %s",strrev(s1));
return(0);
}
C continue statement
The continue statement in C language is used to continue the execution of loop (while,
do while and for). It is used with if condition within the loop.
Syntax:
1. jump-statement;
2. continue;
Output
1
2
3
4
6
7
8
9
10
As you can see, 5 is not printed on the console because loop is continued at i==5.
1. #include<stdio.h>
2. int main(){
3. int i=1,j=1;//initializing a local variable
4. for(i=1;i<=3;i++){
5. for(j=1;j<=3;j++){
6. if(i==2 && j==2){
7. continue;//will continue loop of j only
8. }
9. printf("%d %d\n",i,j);
10. }
11. }//end of for loop
12. return 0;
13. }
Output
1 1
1 2
1 3
2 1
2 3
3 1
3 2
3 3
As you can see, 2 2 is not printed on the console because inner loop is continued at i==2 and j==2.
C goto statement
The goto statement is known as jump statement in C language. It is used to unconditionally jump to other label. It
transfers control to other parts of the program.
It is rarely used today because it makes program less readable and complex.
Syntax:
1. goto label;
goto example
Let's see a simple example to use goto statement in C language.
1. #include <stdio.h>
2. int main() {
3. int age;
4. ineligible:
5. printf("You are not eligible to vote!\n");
6.
7. printf("Enter you age:\n");
8. scanf("%d", &age);
9. if(age<18)
10. goto ineligible;
11. else
12. printf("You are eligible to vote!\n");
13.
14. return 0;
15. }
Output:
Type Casting in C
Type casting allows us to convert one data type into other. In C language, we use cast operator for
type casting which is denoted by (type).
Syntax:
1. (type)value;
Note: It is always recommended to convert lower value to higher for avoiding data loss.
1. int f= 9/4;
2. printf("f : %d\n", f );//Output: 2
1. #include<stdio.h>
2. int main(){
3. float f= (float)9/4;
4. printf("f : %f\n", f );
5. return 0;
6. }
Output:
f : 2.250000