You are on page 1of 37

Features of C Language

C is the widely used language. It provides many features that are given below.

1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible

1) Simple
C is a simple language in the sense that it provides a structured approach (to break the problem
into parts), the rich set of library functions, data types, etc.

2) Machine Independent or Portable


Unlike assembly language, c programs can be executed on different machines with some
machine specific changes. Therefore, C is a machine independent language.

3) Mid-level programming language


Although, C is intended to do low-level programming. It is used to develop system applications
such as kernel, driver, etc. It also supports the features of a high-level language. That is why it is
known as mid-level language.

4) Structured programming language


C is a structured programming language in the sense that we can break the program into parts
using functions. So, it is easy to understand and modify. Functions also provide code reusability.

5) Rich Library
C provides a lot of inbuilt functions that make 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 since there are lesser inbuilt functions
and hence the lesser overhead.

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.
Recursion enables us to use the approach of backtracking.

10) Extensible
C language is extensible because it can easily adopt new features.

Structure of a C program
The structure of a C program means the specific structure to start the programming in the C
language. Without a proper structure, it becomes difficult to analyze the problem and the solution.
It also gives us a reference to write more complex programs.

Let's first discuss about C programming.

C programming
C language combines the power of a low-level language and a high-level language. The low-
level languages are used for system programming, while the high-level languages are used for
application programming. It is because such languages are flexible and easy to use. Hence, C
language is a widely used computer language.

It supports various operators, constructors, data structures, and loop constructs. The features of C
programming make it possible to use the language for system programming, development of
interpreters, compilers, operating systems, graphics, general utilities, etc. C is also used to write
other applications, such as databases, compilers, word processors, and spreadsheets.

The essential features of a C program are as follows:

Pointers: it allows reference to a memory location by the name assigned to it in a program.

Memory allocation: At the time of definition, memory is assigned to a variable name, allowing
dynamic allocation of the memory. It means that the program itself can request the operating
system to release memory for use at the execution time.

Recursion: When a function calls itself, it is known as recursion.

Bit-manipulation: It refers to the manipulation of data in its lowest form. It is also known as bits.
The computer stores the information in binary format (0 and 1).

Let's start with the importance of specifying the structure of a C program.

Importance of structure of a C program


Sometimes, when we begin with a new programming language, we are not aware about the basic
structure of a program. The sections of a program usually get shuffled and the chance of omission
of error rises. The structure of a language gives us a basic idea of the order of the sections in a
program. We get to know when and where to use a particular statement, variable, function,
curly braces, parentheses, etc. It also increases our interest in that programming language.

Thus, the structure helps us analyze the format to write a program for the least errors. It gives
better clarity and the concept of a program.

Here, we will discuss the sections of a C program, some practical examples with explanations,
steps to compile and execute a C program.

Let's start.

Sections of a C program

The sections of a C program are listed below:

1. Documentation section
2. Preprocessor section
3. Definition section
4. Global declaration
5. Main function
6. User defined functions

Let's discuss it in detail.


Documentation section
It includes the statement specified at the beginning of a program, such as a program's name,
date, description, and title. It is represented as:

1. //name of a program  

Or

1. /* 
2. Overview of the code 
3. . 
4. */  

Both methods work as the document section in a program. It provides an overview of the program.
Anything written inside will be considered a part of the documentation section and will not
interfere with the specified code.

Preprocessor section
The preprocessor section contains all the header files used in a program. It informs the system to
link the header files to the system libraries. It is given by:

1. #include<stdio.h>  
2. #include<conio.h>  

The #include statement includes the specific file as a part of a function at the time of the
compilation. Thus, the contents of the included file are compiled along with the function being
compiled. The #include<stdio.h> consists of the contents of the standard input output files,
which contains the definition of stdin, stdout, and stderr. Whenever the definitions stdin, stdout,
and stderr are used in a function, the statement #include<stdio.h> need to be used.

There are various header files available for different purposes. For example, # include
<math.h>. It is used for mathematic functions in a program.

Define section
The define section comprises of different constants declared using the define keyword. It is given
by:

1. #define a = 2  
Global declaration
The global section comprises of all the global declarations in the program. It is given by:

1. float num = 2.54;  
2.  int a = 5;  
3. char ch ='z';  

The size of the above global variables is listed as follows:

char = 1 byte

float = 4 bytes

int = 4 bytes

We can also declare user defined functions in the global variable section.

Main function
main() is the first function to be executed by the computer. It is necessary for a code to include the
main(). It is like any other function available in the C library. Parenthesis () are used for passing
parameters (if any) to a function.

The main function is declared as:

1. main()  

We can also use int or main with the main (). The void main() specifies that the program will not
return any value. The int main() specifies that the program can return integer type data.

1. int main()  

Or

1. void main()  

Main function is further categorized into local declarations, statements, and expressions.

Local declarations
The variable that is declared inside a given function or block refers to as local declarations.

1. main()  
2. {  
3. int i = 2;  
4. i++;  
5. }  

Statements

The statements refers to if, else, while, do, for, etc. used in a program within the main function.

Expressions
An expression is a type of formula where operands are linked with each other by the use of
operators. It is given by:

1. a - b;  
2. a +b;  
User defined functions
The user defined functions specified the functions specified as per the requirements of the user.
For example, color(), sum(), division(), etc.

The program (basic or advance) follows the same sections as listed above.

Return function is generally the last section of a code. But, it is not necessary to include. It is used
when we want to return a value. The return function returns a value when the return type other
than the void is specified with the function.

Return type ends the execution of the function. It further returns control to the specified calling
function. It is given by:

1. return;  

Or

1. return expression ;  

For example,

return 0;

Examples
Let's begin with a simple program in C language.

Example 1: To find the sum of two numbers given by the user

It is given by:

1. /* Sum of two numbers */  
2. #include<stdio.h>   
3. int main()  
4. {  
5. int a, b, sum;  
6. printf("Enter two numbers to be added ");  
7.     scanf("%d %d", &a, &b);  
8.     // calculating sum  
9.     sum = a + b;      
10.     printf("%d + %d = %d", a, b, sum);  
11.     return 0;  // return the integer value in the sum  
12. }  

Output

The detailed explanation of each part of a code is as follows:

/* Sum of the two It is the comment section. Any statement described in it is not considered as a code.
numbers */ It is a part of the description section in a code.
The comment line is optional. It can be in a separate line or part of an executable line.

#include<stdio.h> It is the standard input-output header file. It is a command of the preprocessor


section.

int main() main() is the first function to be executed in every program. We have used int with
the main() in order to return an integer value.

{… The curly braces mark the beginning and end of a function. It is mandatory in all the
} functions.

printf() The printf() prints text on the screen. It is a function for displaying constant or
variables data. Here, 'Enter two numbers to be added' is the parameter passed to it.

scanf() It reads data from the standard input stream and writes the result into the specified
arguments.

sum = a + b The addition of the specified two numbers will be passed to the sum parameter in
the output.

return 0 A program can also run without a return 0 function. It simply states that a program is
free from error and can be successfully exited.

Example 2: To draw a box by accepting a number from the user

It is given by:

1. /* a simple code to draw a box by accepting a number from the user */  
2.   
3. #include<stdio.h>  // preprocessor section that contains header files  
4. #include<conio.h>  
5. void main()  // main section  
6. {  
7. char num;  //local statements  
8. puts(" Enter number of lines of a box (1 to 3) \n");   
9. /* puts accepts, as parameter, a string constant, or a variable enclosed within the double quotes for 
display on the standard output*/  
10.   
11. num = getchar(); // getchar() is also equal to getc(stdin) in C programming.  
12. /* It accepts a parameter and allows the character to be read during the program execution. */  
13. fflush(stdin); // clears the buffer  
14. if(num=='1')  // beginning of if-else condition  
15. {  
16. puts("-----------");  
17. puts("|         |");  
18. puts("-----------");  
19. }  
20. else if(num=='2') /*if-else performs two different operations depending on the true or false conditio
n of the expression.*/  
21. {  
22. puts("-----------");  
23. puts("|         |");  
24. puts("|         |");  
25. puts("-----------");  
26. }  
27. else if(num=='3')  
28. {  
29. puts("-----------");  
30. puts("|         |");  
31. puts("|         |");  
32. puts("|         |");  
33. puts("-----------");  
34. }  
35. else  
36. {  
37. puts("Invalid input");  
38. }  
39. }  

We have saved the file with the name boxexample.c. Let's compile and execute the code with the
help of the command prompt. The file was created in the Notepad.

Output
The steps to create, compile, and execute the code from the beginning have been explained later
in the topic. It will help us compile any type of C code with the help of text editor (Notepad here)
and cmd (Command Prompt).

We can collectively say that the program includes preprocessor commands, variables, functions,
statements, expressions, and comments.

Compile and execution of a C program


Here, we will discuss the method to compile and run the C program with the help of the command
prompt.

The steps involved in a complete program execution are as follows:

1. Create a program
2. Compile a program
3. Run or execute a program
4. Output of the program

Create a program
It refers to the code created in any text editor. We can also compile and run the C code in any
software, such as Visual studio.

Compile a program
If refers to the process of checking the errors in the code. The computer displays all the errors (if
any) found in our specified C code. We can make further changes to correct those errors.

Run or execute a program


The next step is the run or execution part. A program is assembled and linked without any error.
The computer performs different operations, such as decoding, ALU operations to run a program.
Output of the program
It is the last part of the program where the output of the specified code is produced as the result.

But, where to write a program and how to open a command prompt to run that program. Do not
worry; it is very easy to do all these steps. Let's start with the step to compile and run a C program.

Step to compile and run a C program


We need first to ensure that the gcc compiler is already present on our PC or not. If it is not
installed, we need first to install the gcc compiler. We can also try other methods to run a C
program. But here, we have used the gcc compiler.

Step: 1 - gcc complier installation


We can directly install the latest gcc complier through the link: https://jmeubank.github.io/tdm-
gcc/

Complete all the steps during the installation till the process gets completed.

Step: 2 - creating a C program


Create a C program using the simple text editor. Here, we have used notepad. It is shown below:

1. #include<stdio.h>  
2. main()  
3. {  
4.     printf("Hello, Welcome to the C programming \n");  
5.     return;  
6. }  

Now, save the file in any directory with the extension (.c). For example, we have saved the file with
the name 'welcome.c' on the desktop.

Step: 3 - Opening the command prompt


Open the cmd or command prompt on our computer. We can simply type cmd on the search or
the run option. The Command prompt will appear.

Step: 4 - rechecking the gcc complier


After the command prompt opens, type 'gcc -v' and press Enter. It will appear as the image shown
below:
It shows that gcc is successfully installed on our PC.

Step: 5 - go to the source directory


We now need to specify the source directory on the cmd. Type 'cd space source directory' and
press Enter. Since, we have saved our text editor file on the desktop, so we will specify the source
directory as desktop. It is given by:

1. cd desktop  
Step: 6 - compile the source code
Run the command 'gcc space full name of the file saved with the extension (.c)' and press Enter, as
shown below:

1. gcc welcome.c  

If there is any error in our file, it will appear. Otherwise, move on to the step 7.

Step: 7 - Compile the source code


The executable file is not yet named because we have not told the compiler to perform any such
task. So, we will first name the executable file by running the command 'gcc space -o space (name
of executable file) space (name of the original file with the extension)' and press Enter. It is given
by:
1. gcc -o hello welcome.c  

Here, we have given the executable name as hello. We can define the name as per our
convenience.

Step: 8 - Run the program


It is the last step to run a program. We will run the program in the command prompt only. Here,
we will type the name of the executable file without any extension. The executable name will be
the same as specified in step 7. It is given by:

1. hello  

Press Enter. The output will appear on the command prompt, as shown below:

Similarly, we can run multiple C programs using the same steps, as discussed above.

C as a procedural language
A procedure is known as a function, method, routine, subroutine, etc. A procedural
language specifies a series of steps for the program to solve the problem.

A procedural language breaks the program into functions, data structures, etc.

C is a procedural language. In C, variables and function prototypes must be declared before being
used.

Tokens in C
Tokens in C is the most important element to be used in creating a program in C. We can define
the token as the smallest individual element in C. For `example, we cannot create a sentence
without using words; similarly, we cannot create a program in C without using tokens in C.
Therefore, we can say that tokens in C is the building block or the basic component for creating
a program in C language.

Classification of tokens in C

Tokens in C language can be divided into the following categories:


o Keywords in C
o Identifiers in C
o Strings in C
o Operators in C
o Constant in C
o Special Characters in C

Let's understand each token one by one.

Keywords in C

Keywords in C can be defined as the pre-defined or the reserved words having its own


importance, and each keyword has its own functionality. Since keywords are the pre-defined words
used by the compiler, so they cannot be used as the variable names. If the keywords are used as
the variable names, it means that we are assigning a different meaning to the keyword, which is
not allowed. C language supports 32 keywords given below:

auto double int struct

break else long switch

case enum register typedef

char extern return union

const float short unsigned

continue for signed void

default goto sizeof volatile


do if static while

Identifiers in C

Identifiers in C are used for naming variables, functions, arrays, structures, etc. Identifiers in C are
the user-defined words. It can be composed of uppercase letters, lowercase letters, underscore, or
digits, but the starting letter should be either an underscore or an alphabet. Identifiers cannot be
used as keywords. Rules for constructing identifiers in C are given below:

o The first character of an identifier should be either an alphabet or an underscore, and then it
can be followed by any of the character, digit, or underscore.
o It should not begin with any numerical digit.
o In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say that
identifiers are case sensitive.
o Commas or blank spaces cannot be specified within an identifier.
o Keywords cannot be represented as an identifier.
o The length of the identifiers should not be more than 31 characters.
o Identifiers should be written in such a way that it is meaningful, short, and easy to read.

Strings in C

Strings in C are always represented as an array of characters having null character '\0' at the end of
the string. This null character denotes the end of the string. Strings in C are enclosed within double
quotes, while characters are enclosed within single characters. The size of a string is a number of
characters that the string contains.

Now, we describe the strings in different ways:

char a[10] = "javatpoint"; // The compiler allocates the 10 bytes to the 'a' array.

char a[] = "javatpoint"; // The compiler allocates the memory at the run time.

char a[10] = {'j','a','v','a','t','p','o','i','n','t','\0'}; // String is represented in the form of characters.

Operators in C

Operators in C is a special symbol used to perform the functions. The data items on which the
operators are applied are known as operands. Operators are applied between the operands.
Depending on the number of operands, operators are classified as follows:

Unary Operator

A unary operator is an operator applied to the single operand. For example: increment operator (+
+), decrement operator (--), sizeof, (type)*.

Binary Operator
The binary operator is an operator applied between two operands. The following is the list of the
binary operators:

o Arithmetic Operators
o Relational Operators
o Shift Operators
o Logical Operators
o Bitwise Operators
o Conditional Operators
o Assignment Operator
o Misc Operator

Constants in C

A constant is a value assigned to the variable which will remain the same throughout the program,
i.e., the constant value cannot be changed.

There are two ways of declaring constant:

o Using const keyword


o Using #define pre-processor

Types of constants in C

Constant Example

Integer constant 10, 11, 34, etc.

Floating-point constant 45.6, 67.8, 11.2, etc.

Octal constant 011, 088, 022, etc.

Hexadecimal constant 0x1a, 0x4b, 0x6b, etc.

Character constant 'a', 'b', 'c', etc.

String constant "java", "c++", ".net", etc.

Special characters in C

Some special characters are used in C, and they have a special meaning which cannot be used for
another purpose.

o Square brackets [ ]: The opening and closing brackets represent the single and
multidimensional subscripts.
o Simple brackets ( ): It is used in function declaration and function calling. For example,
printf() is a pre-defined function.
o Curly braces { }: It is used in the opening and closing of the code. It is used in the opening
and closing of the loops.
o Comma (,): It is used for separating for more than one statement and for example,
separating function parameters in a function call, separating the variable when printing the
value of more than one variable using a single printf statement.
o Hash/pre-processor (#): It is used for pre-processor directive. It basically denotes that we
are using the header file.
o Asterisk (*): This symbol is used to represent pointers and also used as an operator for
multiplication.
o Tilde (~): It is used as a destructor to free memory.
o Period (.): It is used to access a member of a structure or a union.

Data Types in C
A data type specifies the type of data that a variable can store such as integer, floating, character, etc.

There are the following data types in C language.

Types Data Types

Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type enum


Void Data Type void

Basic Data Types


The basic data types are integer-based and floating-point based. C language supports both signed and
unsigned literals.

The memory size of the 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.

Data Types Memory Size Range

char 1 byte −128 to 127

signed char 1 byte −128 to 127

unsigned char 1 byte 0 to 255

short 2 byte −32,768 to 32,767

signed short 2 byte −32,768 to 32,767

unsigned short 2 byte 0 to 65,535

int 2 byte −32,768 to 32,767

signed int 2 byte −32,768 to 32,767

unsigned int 2 byte 0 to 65,535

short int 2 byte −32,768 to 32,767

signed short int 2 byte −32,768 to 32,767

unsigned short int 2 byte 0 to 65,535

long int 4 byte -2,147,483,648 to 2,147,483,647

signed long int 4 byte -2,147,483,648 to 2,147,483,647

unsigned long int 4 byte 0 to 4,294,967,295


float 4 byte

double 8 byte

long double 10 byte

Formatted I/O functions in C


printf() and scanf() in C
The printf() and scanf() functions are used for input and output in C language. Both functions are
inbuilt library functions, defined in stdio.h (header file).

printf() function
The printf() function is used for output. It prints the given statement to the console.

The syntax of printf() function is given below:

1. printf("format string",argument_list);  

The format string can be %d (integer), %c (character), %s (string), %f (float) etc.

scanf() function
The scanf() function is used for input. It reads the input data from the console.

1. scanf("format string",argument_list);  
Program to print cube of given number
Let's see a simple example of c language that gets input from the user and prints the cube of the
given number.

1. #include<stdio.h>    
2. int main(){    
3. int number;    
4. printf("enter a number:");    
5. scanf("%d",&number);    
6. printf("cube of number is:%d ",number*number*number);    
7. return 0;  
8. }    

Output

enter a number:5
cube of number is:125

The scanf("%d",&number) statement reads integer number from the console and stores the
given value in number variable.

The printf("cube of number is:%d ",number*number*number) statement prints the cube of


number on the console.

Program to print sum of 2 numbers


Let's see a simple example of input and output in C language that prints addition of 2 numbers.

1. #include<stdio.h>    
2. int main(){    
3. int x=0,y=0,result=0;  
4.   
5. printf("enter first number:");  
6. scanf("%d",&x);  
7. printf("enter second number:");  
8. scanf("%d",&y);  
9.   
10. result=x+y;  
11. printf("sum of 2 numbers:%d ",result);  
12.   
13. return 0;  
14. }    

Output

enter first number:9


enter second number:9
sum of 2 numbers:18

Difference between Formatted and Unformatted


Functions

Formatted I/O functions allow to supply input or display output in user desired
format.
Unformatted I/O functions are the most basic form of input and output and
they do not allow to supply input or display output in user desired format.

printf() and scanf() are examples for formatted input and output


functions.

getch(), getche(), getchar(), gets(), puts(), putchar() etc.


are examples of unformatted input output functions.

Formatted input and output functions contain format specifier in their syntax.

Unformatted input and output functions do not contain format specifier in


their syntax.

Formatted I/O functions are used for storing data more user friendly.

Unformatted I/O functions are used for storing data more compactly.

Formatted I/O functions are used with all data types.

Unformatted I/O functions are used mainly for character and string data types.

Formatted I/O Example:


#include<stdio.h>
#include<conio.h>

void main()
{
int a;
clrscr();
printf(“Enter value of a:”);
scanf(“%d”, &a);
printf(“ a = %d”, a);
getch();
}

Output of the above program is:

Enter value of a:5↲


a = 5

Unformatted I/O Example:

#include<stdio.h>
#include<conio.h>

void main()
{
char ch ;
clrscr();
printf(“Press any character:”);
ch = getche();
printf(“\nYou pressed :”
putchar(ch);
getch();
}

Output of the above program is:

Press any character: L


You pressed: L

C Operators
An operator is simply a symbol that is used to perform operations. There can be many types of
operations like arithmetic, logical, bitwise, etc.

There are following types of operators to perform different types of operations in C language.

o Arithmetic Operators
o Relational Operators
o Shift Operators
o Logical Operators
o Bitwise Operators
o Ternary or Conditional Operators
o Assignment Operator
o Misc Operator

Precedence of Operators in C
The precedence of operator species that which operator will be evaluated first and next. The
associativity specifies the operator direction to be evaluated; it may be left to right or right to left.

Let's understand the precedence by the example given below:

1. int value=10+20*10;  

The value variable will contain 210 because * (multiplicative operator) is evaluated before +


(additive operator).

The precedence and associativity of C operators is given below:

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right


Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

Different forms of if statements


Conditional statements help you to make a decision based on certain conditions. These
conditions are specified by a set of conditional statements having boolean expressions
which are evaluated to a boolean value true or false. There are following types of
conditional statements in C.
1. If statement
2. If-Else statement
3. Nested If-else statement
4. If-Else If ladder
5. Switch statement

If statement
The single if statement in C language is used to execute the code if a condition is true. It is
also called one-way selection statement.

Syntax
if(expression)

//code to be executed
}

How "if" statement works..


 If the expression is evaluated to nonzero (true) then if block statement(s) are
executed.
 If the expression is evaluated to zero (false) then Control passes to the next
statement following it.

Note
"Expression must be scalar type" i.e evaluated to a single value.

if Statement Example
#include<stdio.h>

#include<conio.h>

void main()

int num=0;

printf("enter the number");


scanf("%d",&num);

if(n%2==0)

printf("%d number in even",num);

getch();

If-else statement
The if-else statement in C language is used to execute the code if condition is true or false.
It is also called two-way selection statement.

Syntax
if(expression)

//Statements

else

//Statements

}
How "if..else" statement works..
 If the expression is evaluated to nonzero (true) then if block statement(s) are
executed.
 If the expression is evaluated to zero (false) then else block statement(s) are
executed.

if..else Statement Example


#include<stdio.h>

#include<conio.h>

void main()

int num=0;

printf("enter the number");

scanf("%d",&num);

if(n%2==0)

printf("%d number in even", num);


}

else

printf("%d number in odd",num);

getch();

Nested If-else statement


The nested if...else statement is used when a program requires more than one test
expression. It is also called a multi-way selection statement. When a series of the decision
are involved in a statement, we use if else statement in nested form.

Syntax
if( expression )

if( expression1 )

statement-block1;

else

statement-block 2;

else

statement-block 3;

}
Example
#include<stdio.h>

#include<conio.h>

void main( )

int a,b,c;

clrscr();

printf("Please Enter 3 number");

scanf("%d%d%d",&a,&b,&c);

if(a>b)

if(a>c)

printf("a is greatest");

else

printf("c is greatest");

else

if(b>c)

printf("b is greatest");

else

printf("c is greatest");
}

getch();

If..else If ladder
The if-else-if statement is used to execute one code from multiple conditions. It is also
called multipath decision statement. It is a chain of if..else statements in which each if
statement is associated with else if statement and last would be an else statement.

Syntax
if(condition1)

//statements

else if(condition2)

//statements

else if(condition3)

//statements

else

//statements

}
If..else If ladder Example
#include<stdio.h>

#include<conio.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");

getch();

C Loops
The looping can be defined as repeating the same process multiple times until a specific condition
satisfies. There are three types of loops used in the C language. In this part of the tutorial, we are
going to learn all the aspects of C loops.

Why use loops in C language?


The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of
the program so that instead of writing the same code again and again, we can repeat the same
code for a finite number of times. For example, if we need to print the first 10 natural numbers
then, instead of using the printf statement 10 times, we can print inside a loop which runs up to 10
iterations.

Advantage of loops in C
1) It provides code reusability.

2) Using loops, we do not need to write the same code again and again.

3) Using loops, we can traverse over the elements of data structures (array or linked lists).

Types of C Loops
There are three types of loops in C language that is given below:

1. do while
2. while
3. for

do-while loop in C
The do-while loop continues until a given condition satisfies. It is also called post tested loop. It is
used when it is necessary to execute the loop at least once (mostly menu driven programs).

The syntax of do-while loop in c language is given below:

1. do{  
2. //code to be executed  
3. }while(condition);  

Flowchart and Example of do-while loop

while loop in C
The while loop in c is to be used in the scenario where we don't know the number of iterations in
advance. The block of statements is executed in the while loop until the condition specified in the
while loop is satisfied. It is also called a pre-tested loop.

The syntax of while loop in c language is given below:

1. while(condition){  
2. //code to be executed  
3. }  

Flowchart and Example of while loop

for loop in C
The for loop is used in the case where we need to execute some part of the code until the given
condition is satisfied. The for loop is also called as a per-tested loop. It is better to use for loop if
the number of iteration is known in advance.

The syntax of for loop in c language is given below:

1. for(initialization;condition;incr/decr){  
2. //code to be executed  
3. }  
Fibonacci Series in C without recursion
Let's see the fibonacci series program in c without recursion.

1. #include<stdio.h>    
2. int main()    
3. {    
4.  int n1=0,n2=1,n3,i,number;    
5.  printf("Enter the number of elements:");    
6.  scanf("%d",&number);    
7.  printf("\n%d %d",n1,n2);//printing 0 and 1    
8.  for(i=2;i<number;++i)//loop starts from 2 because 0 and 1 are already printed    
9.  {    
10.   n3=n1+n2;    
11.   printf(" %d",n3);    
12.   n1=n2;    
13.   n2=n3;    
14.  }  
15.   return 0;  
16.  }    

Output:

Enter the number of elements:15


0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

C Array
An array is defined as the collection of similar type of data items stored at contiguous memory
locations. Arrays are the derived data type in C programming language which can store the
primitive type of data such as int, char, double, float, etc. It also has the capability to store the
collection of derived data types, such as pointers, structure, etc. The array is the simplest data
structure where each data element can be randomly accessed by using its index number.

C array is beneficial if you have to store similar elements. For example, if we want to store the
marks of a student in 6 subjects, then we don't need to define different variables for the marks in
the different subject. Instead of that, we can define an array which can store the marks in each
subject at the contiguous memory locations.

By using the array, we can access the elements easily. Only a few lines of code are required to
access the elements of the array.

Two Dimensional Array in C


The two-dimensional array can be defined as an array of arrays. The 2D array is organized as
matrices which can be represented as the collection of rows and columns. However, 2D arrays are
created to implement a relational database lookalike data structure. It provides ease of holding the
bulk of data at once which can be passed to any number of functions wherever required.

Declaration of two dimensional Array in C


The syntax to declare the 2D array is given below.

1. data_type array_name[rows][columns];  

Consider the following example.

1. int twodimen[4][3];  

Here, 4 is the number of rows, and 3 is the number of columns.

Initialization of 2D Array in C
In the 1D array, we don't need to specify the size of the array if the declaration and initialization
are being done simultaneously. However, this will not work with 2D arrays. We will have to define
at least the second dimension of the array. The two-dimensional array can be declared and defined
in the following way.

1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  
Two-dimensional array example in C
1. #include<stdio.h>  
2. int main(){      
3. int i=0,j=0;    
4. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};     
5. //traversing 2D array    
6. for(i=0;i<4;i++){    
7.  for(j=0;j<3;j++){    
8.    printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);    
9.  }//end of j    
10. }//end of i    
11. return 0;  
12. }    

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

String Handling Functions in C


C programming language provides a set of pre-defined functions called string handling functions to work with

string values. The string handling functions are defined in a header file called string.h. Whenever we want to

use any string handling function we must include the header file called string.h.

The following table provides most commonly used string handling function and their use...

Function Syntax (or) Example Description

strcpy() strcpy(string1, string2) Copies string2 value into string1

strncpy() strncpy(string1, string2, 5) Copies first 5 characters string2 into string1

strlen() strlen(string1) returns total number of characters in string1

strcat() strcat(string1,string2) Appends string2 to string1

strncat() strncpy(string1, string2, 4) Appends first 4 characters of string2 to string1

strcmp() strcmp(string1, string2) Returns 0 if string1 and string2 are the same;
less than 0 if string1<string2; greater than 0 if string1>string2

strncmp() strncmp(string1, string2, 4) Compares first 4 characters of both string1 and string2

strcmpi() strcmpi(string1,string2) Compares two strings, string1 and string2 by ignoring case (upper or

stricmp() stricmp(string1, string2) Compares two strings, string1 and string2 by ignoring case (similar to

strlwr() strlwr(string1) Converts all the characters of string1 to lower case.

strupr() strupr(string1) Converts all the characters of string1 to upper case.

strdup() string1 = strdup(string2) Duplicated value of string2 is assigned to string1

strchr() strchr(string1, 'b') Returns a pointer to the first occurrence of character 'b' in string1
Function Syntax (or) Example Description

strrchr() 'strrchr(string1, 'b') Returns a pointer to the last occurrence of character 'b' in string1

strstr() strstr(string1, string2) Returns a pointer to the first occurrence of string2 in string1

strset() strset(string1, 'B') Sets all the characters of string1 to given character 'B'.

strnset() strnset(string1, 'B', 5) Sets first 5 characters of string1 to given character 'B'.

strrev() strrev(string1) It reverses the value of string1

You might also like