You are on page 1of 51

Unit-2(PPS)

C Language Introduction

C is a procedural programming language. It was initially developed by Dennis Ritchie in the year
1972. It was mainly developed as a system programming language to write an operating system.
The main features of the C language include low-level memory access, a simple set of keywords,
and a clean style, these features make C language suitable for system programmings like an
operating system or compiler development. 
Many later languages have borrowed syntax/features directly or indirectly from the C language.
Like syntax of Java, PHP, JavaScript, and many other languages are mainly based on the C
language. C++ is nearly a superset of C language (Few programs may compile in C, but not in
C++). 
Introduction To C Language

C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie


to develop the UNIX operating system at Bell Labs. C was originally first implemented on the
DEC PDP-11 computer in 1972.
The UNIX operating system, the C compiler, and essentially all UNIX application programs
have been written in C. C has now become a widely used professional language for various
reasons:

 Easy to learn
 Structured language
 It produces efficient programs
 It can handle low-level activities
 It can be compiled on a variety of computer platforms
Why Use C?

C was initially used for system development work, particularly the programs that make up the
operating system. C was adopted as a system development language because it produces code
that runs nearly as fast as the code written in assembly language. Some examples of the use of C:

 Operating Systems
 Language Compilers
 Assemblers
 Text Editors
 Print Spoolers
 Network Drivers
 Modern Programs
 Databases
 Language Interpreters
 Utilities
Applications of ‘c’

C programming language can be used to design different types of application like designing the
system software like OS & compiler.
Designing the application software like database & spreadsheets.
To design the graphics related applications, i.e., PC's and mobile games.
To evaluate the mathematical equations.
Features Of C Programming Language
C language is one of the powerful languages. Below are some of the features of the C language.

 Reliability
 Portability
 Flexibility
 Interactivity
 Modularity
 Efficiency and Effectiveness
C is the most popular programming language which has many advantages:
Modularity:
It is one of the important characteristics of C. we can split the C program into no. of modules
instead of repeating the same logic statements (sequentially). It allows the reusability
of modules.
Middle-level language:
As a middle-level language, C combines both the advantages of low level and high-level
languages. (arrays, pointers, etc.).
General-purpose programming language:
C can be used to implement any applications such as math’s oriented, graphics, business-oriented
applications.
Portability:
We can compile or execute a C program on any operating system (Unix, dos, windows).
Powerful programming language:
C is a very efficient and powerful programming language, it is best used for data structures and
designing system software. C is case sensitive language.
Advantages of C

C Language has a list of advantages due to this it is a very much popular language around the
world and best suitable for the programmer to learn at the first stage of the programming.
Procedure Oriented Language
C Language is procedure-oriented language, here user creates procedures or functions to execute
their task. Procedure-oriented language is very much easy to learn because it follows an
algorithm to execute your statements. To develop a program using procedure-oriented language,
you need to draw/prepare an algorithm and then start converting it into a procedure or functions.
Lots of Libraries
C Language provides lots of functions which consist of system generated functions and user-
defined functions. C Compiler comes with a list of header files which consist of many general
functions which can be used to develop a program, while the programmer can also create a
function as per their requirements that are called a user-generated/defined function.
Speed of Compilation
C compiler produces machine code very fast compared to other language compilers. C compiler
can compile around 1000 lines of code in a second or two. One more benefit of the C Compiler is
that it also optimize the code for faster execution.
Easy to Learn 
C Language syntax is very easy to understand. It uses a keyword like if, else, goto, switch, main,
etc. This kind of keyword we all are using in our day to day life to convey meaning or to get
some decisions. 
Portable 
C Language setup is around 3-5 MB. So you can carry this language in your Floppy Drive or Pen
Drive. It is very easy to install and operate, Again its output is an exe file that can be executed on
any computer without any other framework/software.
Disadvantages of C

C Language also has some disadvantages. C Language does not have major disadvantages, but
some features are missing in the C Language, obviously, that's why C Language is very much
powerful now.
Object-Oriented Programming Features (OOPS)
Object-Oriented Programming Features is missing in C Language, You have to develop your
program using procedure-oriented language only.
Run-Time Type Checking is Not Available
In C Language there is no provision for run-time type checking, for example, I am passing float
value while receiving parameter is of integer type then the value will be changed, it will not give
any error message.
Namespace Feature
C does not provide namespace features, so you can't be able to use the same variable name again
in one scope. If namespace features are available, then you can able to reuse the same variable
name.
Constructor and Destructor is not available
C does not provide object-oriented features, so it doesn't have Constructor and Destructor
features. Constructor and Destructor are used to construct an object and destroy an object. So in
C Language, you have to implement the construction and destruction of the variable manually,
using a function or by other means.
Our course design of tutorials is practical and informative. At TekSlate, we offer resources to
help you learn various IT courses. We avail both written material and demo video tutorials. For
in-depth knowledge and practical experience explore Online C Tutorials.
 

Beginning with C programming: 


 
1. Structure of a C program 
After the above discussion, we can formally assess the structure of a C program. By
structure, it is meant that any program can be written in this structure only. Writing a C
program in any other structure will hence lead to a Compilation Error.
The structure of a C program is as follows:
 

1. The components of the above structure are: 


1. Header Files Inclusion: The first and foremost component is the inclusion of the Header
files in a C program. 
A header file is a file with extension .h which contains C function declarations and macro
definitions to be shared between several source files.
Some of C Header files: 
 stddef.h – Defines several useful types and macros.
 stdint.h – Defines exact width integer types.
 stdio.h – Defines core input and output functions
 stdlib.h – Defines numeric conversion functions, pseudo-random network generator,
memory allocation
 string.h – Defines string handling functions
 math.h – Defines common mathematical functions
2. Main Method Declaration: The next part of a C program is to declare the main()
function. The syntax to declare the main function is:
Syntax to Declare the main method: 
 
int main()
{}
1.  
2. Variable Declaration: The next part of any C program is the variable declaration. It refers to
the variables that are to be used in the function. Please note that in the C program, no variable
can be used without being declared. Also in a C program, the variables are to be declared
before any operation in the function.
Example: 
 
int main()
{
int a;
.
.
1.  
2. Body: The body of a function in the C program, refers to the operations that are performed in
the functions. It can be anything like manipulations, searching, sorting, printing, etc.
Example: 
 
int main()
{
int a;

printf("%d", a);
.
.
1.  
2. Return Statement: The last part of any C program is the return statement. The return
statement refers to the returning of the values from a function. This return statement and
return value depend upon the return type of the function. For example, if the return type is
void, then there will be no return statement. In any other case, there will be a return statement
and the return value will be of the type of the specified return type.
Example: 
 
int main()
{
int a;
printf("%d", a);

return 0;
}
1.  
2. Writing first program: 
Following is first program in C
 
 C

#include <stdio.h>

int main(void)

    printf("GeeksQuiz");

    return 0;

1. Let us analyze the program line by line. 


Line 1: [ #include <stdio.h> ] In a C program, all lines that start with # are processed by
a preprocessor which is a program invoked by the compiler. In a very basic term,
the preprocessor takes a C program and produces another C program. The produced program
has no lines starting with #, all such lines are processed by the preprocessor. In the above
example, the preprocessor copies the preprocessed code of stdio.h to our file. The .h files are
called header files in C. These header files generally contain declarations of functions. We
need stdio.h for the function printf() used in the program. 
Line 2 [ int main(void) ] There must be a starting point from where execution of compiled C
program begins. In C, the execution typically begins with the first line of main(). The void
written in brackets indicates that the main doesn’t take any parameter (See this for more
details). main() can be written to take parameters also. We will be covering that in future
posts. 
The int was written before main indicates return type of main(). The value returned by main
indicates the status of program termination. See this post for more details on the return type.
Line 3 and 6: [ { and } ] In C language, a pair of curly brackets define scope and are mainly
used in functions and control statements like if, else, loops. All functions must start and end
with curly brackets. 
Line 4 [ printf(“GeeksQuiz”); ] printf() is a standard library function to print something on
standard output. The semicolon at the end of printf indicates line termination. In C, a
semicolon is always used to indicate end of a statement. 
Line 5 [ return 0; ] The return statement returns the value from main(). The returned value
may be used by an operating system to know the termination status of your program. The
value 0 typically means successful termination. 
 
2. How to execute the above program: 
In order to execute the above program, we need to have a compiler to compile and run our
programs. There are certain online compilers
C Expressions

An expression is a formula in which operands are linked to each other by the use of operators to
compute a value. An operand can be a function reference, a variable, an array element or a
constant.

Let's see an example:

1. a-b;  

In the above expression, minus character (-) is an operator, and a, and b are the two operands.

There are four types of expressions exist in C:

o Arithmetic expressions
o Relational expressions
o Logical expressions
o Conditional expressions

Each type of expression takes certain types of operands and uses a specific set of operators.
Evaluation of a particular expression produces a specific value.

For example:

1. x = 9/2 + a-b;  

The entire above line is a statement, not an expression. The portion after the equal is an
expression.
Arithmetic Expressions

An arithmetic expression is an expression that consists of operands and arithmetic operators. An


arithmetic expression computes a value of type int, float or double.

When an expression contains only integral operands, then it is known as pure integer expression
when it contains only real operands, it is known as pure real expression, and when it contains
both integral and real operands, it is known as mixed mode expression.

Evaluation of Arithmetic Expressions

The expressions are evaluated by performing one operation at a time. The precedence and
associativity of operators decide the order of the evaluation of individual operations.

When individual operations are performed, the following cases can be happened:

o When both the operands are of type integer, then arithmetic will be performed, and the
result of the operation would be an integer value. For example, 3/2 will yield 1 not 1.5 as
the fractional part is ignored.
o When both the operands are of type float, then arithmetic will be performed, and the
result of the operation would be a real value. For example, 2.0/2.0 will yield 1.0, not 1.
o If one operand is of type integer and another operand is of type real, then the mixed
arithmetic will be performed. In this case, the first operand is converted into a real
operand, and then arithmetic is performed to produce the real value. For example, 6/2.0
will yield 3.0 as the first value of 6 is converted into 6.0 and then arithmetic is performed
to produce 3.0.

Let's understand through an example.

6*2/ (2+1 * 2/3 + 6) + 8 * (8/4)


Evaluation of expression Description of each operation

6*2/( 2+1 * 2/3 +6) +8 * (8/4) An expression is given.

6*2/(2+2/3 + 6) + 8 * (8/4) 2 is multiplied by 1, giving value 2.

6*2/(2+0+6) + 8 * (8/4) 2 is divided by 3, giving value 0.

6*2/ 8+ 8 * (8/4) 2 is added to 6, giving value 8.


6*2/8 + 8 * 2 8 is divided by 4, giving value 2.

12/8 +8 * 2 6 is multiplied by 2, giving value 12.

1+8*2 12 is divided by 8, giving value 1.

1 + 16 8 is multiplied by 2, giving value 16.

17 1 is added to 16, giving value 17.

Relational Expressions

o A relational expression is an expression used to compare two operands.


o It is a condition which is used to decide whether the action should be taken or not.
o In relational expressions, a numeric value cannot be compared with the string value.
o The result of the relational expression can be either zero or non-zero value. Here, the zero
value is equivalent to a false and non-zero value is equivalent to true.

Relational Description
Expression

x%2 = = 0 This condition is used to check whether the x is an even number or not. The relational
value 1 if x is an even number otherwise results in value 0.

a!=b It is used to check whether a is not equal to b. This relational expression results in 1 if
otherwise 0.

a+b = = x+y It is used to check whether the expression "a+b" is equal to the expression "x+y".

a>=9 It is used to check whether the value of a is greater than or equal to 9.

Let's see a simple example:

1. #include <stdio.h>  
2.  int main()  
3. {  
4.       
5.     int x=4;  
6.     if(x%2==0)  
7.     {  
8.         printf("The number x is even");  
9.     }  
10.     else  
11.     printf("The number x is not even");  
12.     return 0;  
13. }  

Output

Logical Expressions
o A logical expression is an expression that computes either a zero or non-zero value.
o It is a complex test condition to take a decision.

Let's see some example of the logical expressions.

Logical Expressions Description

( x > 4 ) && ( x < It is a test condition to check whether the x is greater than 4 and x is less than 6. Th
6) is true only when both the conditions are true.

x > 10 || y <11 It is a test condition used to check whether x is greater than 10 or y is less than 11.
condition is true if either of the conditions holds true value.

! ( x > 10 ) && ( y It is a test condition used to check whether x is not greater than 10 and y is equal to
==2) condition is true if both the conditions are true.

Let's see a simple program of "&&" operator.

1. #include <stdio.h>  
2. int main()  
3. {  
4.     int x = 4;  
5.     int y = 10;  
6.     if ( (x <10) && (y>5))  
7.     {  
8.         printf("Condition is true");  
9.     }  
10.     else  
11.     printf("Condition is false");  
12.     return 0;  
13. }  

Output

Let's see a simple example of "| |" operator

1. #include <stdio.h>  
2. int main()  
3. {  
4.     int x = 4;  
5.     int y = 9;  
6.     if ( (x <6) || (y>10))  
7.     {  
8.         printf("Condition is true");  
9.     }  
10.     else  
11.     printf("Condition is false");  
12.     return 0;  
13. }  

Output

Conditional Expressions

o A conditional expression is an expression that returns 1 if the condition is true otherwise


0.
o A conditional operator is also known as a ternary operator.

The Syntax of Conditional operator


Suppose exp1, exp2 and exp3 are three expressions.

exp1 ? exp2 : exp3

The above expression is a conditional expression which is evaluated on the basis of the value of
the exp1 expression. If the condition of the expression exp1 holds true, then the final conditional
expression is represented by exp2 otherwise represented by exp3.

Let's understand through a simple example.

1. #include<stdio.h>  
2. #include<string.h>  
3. int main()  
4. {  
5.     int age = 25;  
6.     char status;  
7.     status = (age>22) ? 'M': 'U';  
8.     if(status == 'M')  
9.     printf("Married");  
10.     else  
11.     printf("Unmarried");  
12.     return 0;  
13. }  

Output

What is a Conditional Statement in C?

Conditional Statements in C programming are used to make decisions based on the conditions.
Conditional statements execute sequentially when there is no condition around the statements. If
you put some condition for a block of statements, the execution flow may change based on the
result evaluated by the condition. This process is called decision making in 'C.'

In 'C' programming conditional statements are possible with the help of the following two
constructs:

1. If statement

2. If-else statement
It is also called as branching as a program decides which statement to execute based on the result
of the evaluated condition.

In this tutorial, you will learn-

 What is a Conditional Statement?


 If statement
 Relational Operators
 The If-Else statement
 Conditional Expressions
 Nested If-else Statements
 Nested Else-if statements

If statement

It is one of the powerful conditional statement. If statement is responsible for modifying the flow
of execution of a program. If statement is always used with a condition. The condition is
evaluated first before executing any statement inside the body of If. The syntax for if statement is
as follows:hat is Linux Linux Beginner Tutorial

if (condition)
instruction;

The condition evaluates to either true or false. True is always a non-zero value, and false is a
value that contains zero. Instructions can be a single instruction or a code block enclosed by
curly braces { }.

Following program illustrates the use of if construct in 'C' programming:

#include<stdio.h>
int main()
{
int num1=1;
int num2=2;
if(num1<num2) //test-condition
{
printf("num1 is smaller than num2");
}
return 0;
}

Output:

num1 is smaller than num2


The above program illustrates the use of if construct to check equality of two numbers.

1. In the above program, we have initialized two variables with num1, num2 with value as
1, 2 respectively.
2. Then, we have used if with a test-expression to check which number is the smallest and
which number is the largest. We have used a relational expression in if construct. Since
the value of num1 is smaller than num2, the condition will evaluate to true.
3. Thus it will print the statement inside the block of If. After that, the control will go
outside of the block and program will be terminated with a successful result.

Relational Operators

C has six relational operators that can be used to formulate a Boolean expression for making a
decision and testing conditions, which returns true or false :

< less than

<= less than or equal to

> greater than

>= greater than or equal to

== equal to

!= not equal to

Notice that the equal test (==) is different from the assignment operator (=) because it is one of
the most common problems that a programmer faces by mixing them up.

For example:

int x = 41;
x =x+ 1;
if (x == 42) {
printf("You succeed!");}

Output :

You succeed

Keep in mind that a condition that evaluates to a non-zero value is considered as true.

For example:
int present = 1;
if (present)
printf("There is someone present in the classroom \n");

Output :

There is someone present in the classroom

The If-Else statement

The if-else is statement is an extended version of If. The general form of if-else is as follows:

if (test-expression)
{
True block of statements
}
Else
{
False block of statements
}
Statements;

n this type of a construct, if the value of test-expression is true, then the true block of statements
will be executed. If the value of test-expression if false, then the false block of statements will be
executed. In any case, after the execution, the control will be automatically transferred to the
statements appearing outside the block of If.

Following programs illustrate the use of the if-else construct:

We will initialize a variable with some value and write a program to determine if the value is less
than ten or greater than ten.

Let's start.

#include<stdio.h>
int main()
{
int num=19;
if(num<10)
{
printf("The value is less than 10");
}
else
{
printf("The value is greater than 10");
}
return 0;
}

Output:

The value is greater than 10

1. We have initialized a variable with value 19. We have to find out whether the number is
bigger or smaller than 10 using a 'C' program. To do this, we have used the if-else
construct.
2. Here we have provided a condition num<10 because we have to compare our value with
10.
3. As you can see the first block is always a true block which means, if the value of test-
expression is true then the first block which is If, will be executed.
4. The second block is an else block. This block contains the statements which will be
executed if the value of the test-expression becomes false. In our program, the value of
num is greater than ten hence the test-condition becomes false and else block is executed.
Thus, our output will be from an else block which is "The value is greater than 10". After
the if-else, the program will terminate with a successful result.

In 'C' programming we can use multiple if-else constructs within each other which are referred to
as nesting of if-else statements.

Conditional Expressions

There is another way to express an if-else statement is by introducing the ?: operator. In a


conditional expression the ?: operator has only one statement associated with the if and the else.

For example:

#include <stdio.h>
int main() {
int y;
int x = 2;
y = (x >= 6) ? 6 : x;/* This is equivalent to: if (x >= 5) y = 5; else y = x; */
printf("y =%d ",y);
return 0;}

Output :

y =2
Nested If-else Statements

When a series of decision is required, nested if-else is used. Nesting means using one if-else
construct within another one.

Let's write a program to illustrate the use of nested if-else.

#include<stdio.h>
int main()
{
int num=1;
if(num<10)
{
if(num==1)
{
printf("The value is:%d\n",num);
}
else
{
printf("The value is greater than 1");
}
}
else
{
printf("The value is greater than 10");
}
return 0;
}

Output:

The value is:1

The above program checks if a number is less or greater than 10 and prints the result using
nested if-else construct.

1. Firstly, we have declared a variable num with value as 1. Then we have used if-else
construct.
2. In the outer if-else, the condition provided checks if a number is less than 10. If the
condition is true then and only then it will execute the inner loop. In this case, the
condition is true hence the inner block is processed.
3. In the inner block, we again have a condition that checks if our variable contains the
value 1 or not. When a condition is true, then it will process the If block otherwise it will
process an else block. In this case, the condition is true hence the If a block is executed
and the value is printed on the output screen.
4. The above program will print the value of a variable and exit with success.

Try changing the value of variable see how the program behaves.

NOTE: In nested if-else, we have to be careful with the indentation because multiple if-else
constructs are involved in this process, so it becomes difficult to figure out individual constructs.
Proper indentation makes it easy to read the program.

Nested Else-if statements

Nested else-if is used when multipath decisions are required.

The general syntax of how else-if ladders are constructed in 'C' programming is as follows:

if (test - expression 1) {
statement1;
} else if (test - expression 2) {
Statement2;
} else if (test - expression 3) {
Statement3;
} else if (test - expression n) {
Statement n;
} else {
default;
}
Statement x;

This type of structure is known as the else-if ladder. This chain generally looks like a ladder
hence it is also called as an else-if ladder. The test-expressions are evaluated from top to bottom.
Whenever a true test-expression if found, statement associated with it is executed. When all the n
test-expressions becomes false, then the default else statement is executed.

Let us see the actual working with the help of a program.

#include<stdio.h>
int main()
{
int marks=83;
if(marks>75){
printf("First class");
}
else if(marks>65){
printf("Second class");
}
else if(marks>55){
printf("Third class");
}
else{
printf("Fourth class");
}
return 0;
}

Output:

First class

The above program prints the grade as per the marks scored in a test. We have used the else-if
ladder construct in the above program.

1. We have initialized a variable with marks. In the else-if ladder structure, we have
provided various conditions.
2. The value from the variable marks will be compared with the first condition since it is
true the statement associated with it will be printed on the output screen.
3. If the first test condition turns out false, then it is compared with the second condition.
4. This process will go on until the all expression is evaluated otherwise control will go out
of the else-if ladder, and default statement will be printed.

Try modifying the value and notice the change in the output.

 C - Loops
 You may encounter situations, when a block of code needs to be executed several
number of times. In general, statements are executed sequentially: The first statement in
a function is executed first, followed by the second, and so on.
 Programming languages provide various control structures that allow for more
complicated execution paths.
 A loop statement allows us to execute a statement or group of statements multiple times.
Given below is the general form of a loop statement in most of the programming
languages −

 C programming language provides the following types of loops to handle looping


requirements.

Sr.No Loop Type & Description


.

1 while loop

Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.

2 for loop
Executes a sequence of statements multiple times and abbreviates the code that manages
the loop variable.

3 do...while loop
It is more like a while statement, except that it tests the condition at the end of the loop
body.

4 nested loops
You can use one or more loops inside any other while, for, or do..while loop.

 Loop Control Statements


 Loop control statements change execution from its normal sequence. When execution
leaves a scope, all automatic objects that were created in that scope are destroyed.
 C supports the following control statements.

Sr.No Control Statement & Description


.

1 break statement

Terminates the loop or switch statement and transfers execution to the statement


immediately following the loop or switch.

2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition
prior to reiterating.

3 goto statement
Transfers control to the labeled statement.
while loop in C

A while loop in C programming repeatedly executes a target statement as long as a given


condition is true.

Syntax

The syntax of a while loop in C programming language is −


while(condition) {
statement(s);
}
Here, statement(s) may be a single statement or a block of statements. The condition may be
any expression, and true is any nonzero value. The loop iterates while the condition is true.
When the condition becomes false, the program control passes to the line immediately
following the loop.

Flow Diagram

Here, the key point to note is that a while loop might not execute at all. When the condition is
tested and the result is false, the loop body will be skipped and the first statement after the while
loop will be executed.

Example

Live Demo
#include <stdio.h>

int main () {

/* local variable definition */


int a = 10;

/* while loop execution */


while( a < 20 ) {
printf("value of a: %d\n", a);
a++;
}

return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
for loop in C
A for loop is a repetition control structure that allows you to efficiently write a loop that needs
to execute a specific number of times.

Syntax

The syntax of a for loop in C programming language is −


for ( init; condition; increment ) {
statement(s);
}
Here is the flow of control in a 'for' loop −
 The init step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here, as
long as a semicolon appears.
 Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop does not execute and the flow of control jumps to the next
statement just after the 'for' loop.
 After the body of the 'for' loop executes, the flow of control jumps back up to
the increment statement. This statement allows you to update any loop control
variables. This statement can be left blank, as long as a semicolon appears after the
condition.
 The condition is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then increment step, and then again condition). After the
condition becomes false, the 'for' loop terminates.

Example

Live Demo
#include <stdio.h>

int main () {
int a;

/* for loop execution */


for( a = 10; a < 20; a = a + 1 ){
printf("value of a: %d\n", a);
}

return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
do...while loop in C
Unlike for and while loops, which test the loop condition at the top of the loop,
the do...while loop in C programming checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at
least one time.

Syntax

The syntax of a do...while loop in C programming language is −


do {
statement(s);
} while( condition );
Notice that the conditional expression appears at the end of the loop, so the statement(s) in the
loop executes once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop
executes again. This process repeats until the given condition becomes false.
Example
Live Demo
#include <stdio.h>

int main () {
/* local variable definition */
int a = 10;

/* do loop execution */
do {
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );

return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
nested loops in C
C programming allows to use one loop inside another loop. The following section shows a few
examples to illustrate the concept.

Syntax

The syntax for a nested for loop statement in C is as follows −


for ( init; condition; increment ) {

for ( init; condition; increment ) {


statement(s);
}
statement(s);
}
The syntax for a nested while loop statement in C programming language is as follows −
while(condition) {

while(condition) {
statement(s);
}
statement(s);
}
The syntax for a nested do...while loop statement in C programming language is as follows −
do {
statement(s);

do {
statement(s);
}while( condition );

}while( condition );
A final note on loop nesting is that you can put any type of loop inside any other type of loop.
For example, a 'for' loop can be inside a 'while' loop or vice versa.

Example

The following program uses a nested for loop to find the prime numbers from 2 to 100 −
Live Demo
#include <stdio.h>

int main () {

/* local variable definition */


int i, j;

for(i = 2; i<100; i++) {

for(j = 2; j <= (i/j); j++)


if(!(i%j)) break; // if factor found, not prime
if(j > (i/j)) printf("%d is prime\n", i);
}

return 0;
}
When the above code is compiled and executed, it produces the following result −
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime

 Array in C
C Array is a collection of variables belongings to the same data type. You can store group of data
of same data type in an array.

 Array might be belonging to any of the data types


 Array size must be a constant value.
 Always, Contiguous (adjacent) memory locations are used to store array elements in
memory.
 It is a best practice to initialize an array to zero or null while declaring, if we don’t assign
any values to array.
EXAMPLE FOR C ARRAYS:

 int a[10];       // integer array


 char b[10];    // character array   i.e. string
TYPES OF C ARRAYS:

There are 2 types of C arrays. They are,


1. One dimensional array
2. Multi dimensional array
 Two dimensional array
 Three dimensional array
 four dimensional array etc…

What is an Array?

An array is a collection of one or more values of the same type. Each value is called an element
of the array. The elements of the array share the same variable name but each element has its
own unique index number (also known as a subscript). An array can be of any type, For
example: int, float, char etc. If an array is of type int then it's elements must be of type int only.

To store roll no. of 100 students, we have to declare an array of size 100 i.e roll_no[100]. Here


size of the array is 100 , so it is capable of storing 100 values. In C, index or subscript starts
from 0, so roll_no[0] is the first element, roll_no[1] is the second element and so on. Note that
the last element of the array will be at roll_no[99] not at roll_no[100] because the index starts
at 0.

Arrays can be single or multidimensional. The number of subscript or index determines the
dimensions of the array. An array of one dimension is known as a one-dimensional array or 1-D
array, while an array of two dimensions is known as a two-dimensional array or 2-D array.

Let's start with a one-dimensional array.

One-dimensional array

Conceptually you can think of a one-dimensional array as a row, where elements are stored one
after another.
Syntax: datatype array_name[size];

datatype: It denotes the type of the elements in the array.

array_name: Name of the array. It must be a valid identifier.

size: Number of elements an array can hold. here are some example of array declarations:

1 int num[100];
2 float temp[20];
3 char ch[50];
num is an array of type int, which can only store 100 elements of type int.
temp is an array of type float, which can only store 20 elements of type float.
ch is an array of type char, which can only store 50 elements of type char.

Note: When an array is declared it contains garbage values.

The individual elements in the array:

1num[0], num[1], num[2], ....., num[99]


2temp[0], temp[1], temp[2], ....., temp[19]
3ch[0], ch[1], ch[2], ....., ch[49]
We can also use variables and symbolic constants to specify the size of the array.

1 #define SIZE 10
2
3 int main()
4{
5 int size = 10;
6
7 int my_arr1[SIZE]; // ok
8 int my_arr2[size]; // not allowed until C99
9 // ...
10 }

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

Multi-dimensional Arrays in C
C programming language allows multidimensional arrays. Here is the general form of a
multidimensional array declaration −
type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional integer array −
int threedim[5][10][4];

Two-dimensional Arrays

The simplest form of multidimensional array is the two-dimensional array. A two-dimensional


array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array
of size [x][y], you would write something as follows −
type arrayName [ x ][ y ];
Where type can be any valid C data type and arrayName will be a valid C identifier. A two-
dimensional array can be considered as a table which will have x number of rows and y number
of columns. A two-dimensional array a, which contains three rows and four columns can be
shown as follows −
Thus, every element in the array a is identified by an element name of the form a[ i ][ j ], where
'a' is the name of the array, and 'i' and 'j' are the subscripts that uniquely identify each element in
'a'.

Initializing Two-Dimensional Arrays

Multidimensional arrays may be initialized by specifying bracketed values for each row.
Following is an array with 3 rows and each row has 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to the previous example −
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Accessing Two-Dimensional Array Elements


An element in a two-dimensional array is accessed by using the subscripts, i.e., row index and
column index of the array. For example −
int val = a[2][3];
The above statement will take the 4th element from the 3rd row of the array. You can verify it
in the above figure. Let us check the following program where we have used a nested loop to
handle a two-dimensional array −
Live Demo

#include <stdio.h>

int main () {

/* an array with 5 rows and 2 columns*/


int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;

/* output each array element's value */


for ( i = 0; i < 5; i++ ) {

for ( j = 0; j < 2; j++ ) {


printf("a[%d][%d] = %d\n", i,j, a[i][j] );
}
}

return 0;
}
When the above code is compiled and executed, it produces the following result −
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
As explained above, you can have arrays with any number of dimensions, although it is likely
that most of the arrays you create will be of one or two dimensions.
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 tutorial 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);

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' . ... A string is actually a one-
dimensional array of characters in C language.

C Functions

In c, we can divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. A function can be called
multiple times to provide reusability and modularity to the C program. In other words, we can
say that the collection of functions creates a program. The function is also known
as procedureor subroutinein other programming languages.

Advantage of functions in C

There are the following advantages of C functions.

o By using functions, we can avoid rewriting same logic/code again and again in a
program.
o We can call C functions any number of times in a program and from any place in a
program.
o We can track a large C program easily when it is divided into multiple functions.
o Reusability is the main achievement of C functions.
o However, Function calling is always a overhead in a C program.

Function Aspects

There are three aspects of a C function.

o Function declaration A function must be declared globally in a c program to tell the


compiler about the function name, function parameters, and return type.
o Function call Function can be called from anywhere in the program. The parameter list
must not differ in function calling and function declaration. We must pass the same
number of functions as it is declared in the function declaration.

o Function definition It contains the actual statements which are to be executed. It is the
most important aspect to which the control comes when the function is called. Here, we
must notice that only one value can be returned from the function.

SN C function aspects Syntax

1 Function declaration return_type function_name (argument list);

2 Function call function_name (argument_list)

3 Function definition return_type function_name (argument list) {function body;}

The syntax of creating function in c language is given below:

1. return_type function_name(data_type parameter...){  
2. //code to be executed  
3. }  

Types of Functions

There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C header files such as
scanf(), printf(), gets(), puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the C programmer, so
that he/she can use it many times. It reduces the complexity of a big program and
optimizes the code.

Return Value
A C function may or may not return a value from the function. If you don't have to return any
value from the function, use void for the return type.

Let's see a simple example of C function that doesn't return any value from the function.

Example without return value:

1. void hello(){  
2. printf("hello c");  
3. }  

If you want to return any value from the function, you need to use any data type such as int, long,
char, etc. The return type depends on the value to be returned from the function.

Let's see a simple example of C function that returns int value from the function.

Example with return value:

1. int get(){  
2. return 10;  
3. }  

In the above example, we have to return 10 as a value, so the return type is int. If you want to
return floating-point value (e.g., 10.2, 3.1, 54.5, etc), you need to use float as the return type of
the method.

1. float get(){  
2. return 10.2;  
3. }  

Now, you need to call the function, to get the value of the function.

Different aspects of function calling

A function may or may not accept any argument. It may or may not return any value. Based on
these facts, There are four different aspects of function calls.

o function without arguments and without return value


o function without arguments and with return value
o function with arguments and without return value
o function with arguments and with return value
Example for Function without argument and return value

Example 1

1. #include<stdio.h>  
2. void printName();  
3. void main ()  
4. {  
5.     printf("Hello ");  
6.     printName();  
7. }  
8. void printName()  
9. {  
10.     printf("Javatpoint");  
11. }  

Output

Hello Javatpoint

Example 2

1. #include<stdio.h>  
2. void sum();  
3. void main()  
4. {  
5.     printf("\nGoing to calculate the sum of two numbers:");  
6.     sum();  
7. }  
8. void sum()  
9. {  
10.     int a,b;   
11.     printf("\nEnter two numbers");  
12.     scanf("%d %d",&a,&b);   
13.     printf("The sum is %d",a+b);  
14. }  

Output

Going to calculate the sum of two numbers:


Enter two numbers 10
24

The sum is 34

Example for Function without argument and with return value

Example 1

1. #include<stdio.h>  
2. int sum();  
3. void main()  
4. {  
5.     int result;   
6.     printf("\nGoing to calculate the sum of two numbers:");  
7.     result = sum();  
8.     printf("%d",result);  
9. }  
10. int sum()  
11. {  
12.     int a,b;   
13.     printf("\nEnter two numbers");  
14.     scanf("%d %d",&a,&b);  
15.     return a+b;   
16. }  

Output

Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

Example 2: program to calculate the area of the square

1. #include<stdio.h>  
2. int sum();  
3. void main()  
4. {  
5.     printf("Going to calculate the area of the square\n");  
6.     float area = square();  
7.     printf("The area of the square: %f\n",area);  
8. }  
9. int square()  
10. {  
11.     float side;  
12.     printf("Enter the length of the side in meters: ");  
13.     scanf("%f",&side);  
14.     return side * side;  
15. }  

Output

Going to calculate the area of the square


Enter the length of the side in meters: 10
The area of the square: 100.000000

Example for Function with argument and without return value

Example 1

1. #include<stdio.h>  
2. void sum(int, int);  
3. void main()  
4. {  
5.     int a,b,result;   
6.     printf("\nGoing to calculate the sum of two numbers:");  
7.     printf("\nEnter two numbers:");  
8.     scanf("%d %d",&a,&b);  
9.     sum(a,b);  
10. }  
11. void sum(int a, int b)  
12. {  
13.     printf("\nThe sum is %d",a+b);      
14. }  

Output

Going to calculate the sum of two numbers:


Enter two numbers 10
24

The sum is 34

Example 2: program to calculate the average of five numbers.

1. #include<stdio.h>  
2. void average(int, int, int, int, int);  
3. void main()  
4. {  
5.     int a,b,c,d,e;   
6.     printf("\nGoing to calculate the average of five numbers:");  
7.     printf("\nEnter five numbers:");  
8.     scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);  
9.     average(a,b,c,d,e);  
10. }  
11. void average(int a, int b, int c, int d, int e)  
12. {  
13.     float avg;   
14.     avg = (a+b+c+d+e)/5;   
15.     printf("The average of given five numbers : %f",avg);  
16. }  

Output

Going to calculate the average of five numbers:


Enter five numbers:10
20
30
40
50
The average of given five numbers : 30.000000

Example for Function with argument and with return value

Example 1

1. #include<stdio.h>  
2. int sum(int, int);  
3. void main()  
4. {  
5.     int a,b,result;   
6.     printf("\nGoing to calculate the sum of two numbers:");  
7.     printf("\nEnter two numbers:");  
8.     scanf("%d %d",&a,&b);  
9.     result = sum(a,b);  
10.     printf("\nThe sum is : %d",result);  
11. }  
12. int sum(int a, int b)  
13. {  
14.     return a+b;  
15. }  

Output

Going to calculate the sum of two numbers:


Enter two numbers:10
20
The sum is : 30

Example 2: Program to check whether a number is even or odd

1. #include<stdio.h>  
2. int even_odd(int);  
3. void main()  
4. {  
5.  int n,flag=0;  
6.  printf("\nGoing to check whether a number is even or odd");  
7.  printf("\nEnter the number: ");  
8.  scanf("%d",&n);  
9.  flag = even_odd(n);  
10.  if(flag == 0)  
11.  {  
12.     printf("\nThe number is odd");  
13.  }  
14.  else   
15.  {  
16.     printf("\nThe number is even");  
17.  }  
18. }  
19. int even_odd(int n)  
20. {  
21.     if(n%2 == 0)  
22.     {  
23.         return 1;  
24.     }  
25.     else   
26.     {  
27.         return 0;  
28.     }  
29. }  

Output

Going to check whether a number is even or odd


Enter the number: 100
The number is even

C Library Functions

Library functions are the inbuilt function in C that are grouped and placed at a common place
called the library. Such functions are used to perform some specific operations. For example,
printf is a library function used to print on the console. The library functions are created by the
designers of compilers. All C standard library functions are defined inside the different header
files saved with the extension .h. We need to include these header files in our program to make
use of the library functions defined in such header files. For example, To use the library
functions such as printf/scanf we need to include stdio.h in our program which is a header file
that contains all the library functions regarding standard input/output.

The list of mostly used header files is given in the following table.

SN Header Description
file

1 stdio.h This is a standard input/output header file. It contains all the library functions regardin
input/output.

2 conio.h This is a console input/output header file.


3 string.h It contains all string related library functions like gets(), puts(),etc.

4 stdlib.h This header file contains all the general library functions like malloc(), calloc(), exit(),

5 math.h This header file contains all the math operations related functions like sqrt(), pow(), et

6 time.h This header file contains all the time-related functions.

7 ctype.h This header file contains all character handling functions.

8 stdarg.h Variable argument functions are defined in this header file.

9 signal.h All the signal handling functions are defined in this header file.

1 setjmp.h This file contains all the jump functions.


0

1 locale.h This file contains locale functions.


1

1 errno.h This file contains error handling functions.


2

1 assert.h This file contains diagnostics functions.


3

Call by value and Call by reference in C

There are two methods to pass the data into the function in C language, i.e., call by
value and call by reference.

Let's understand call by value and call by reference in c language one by one.
Call by value in C

o In call by value method, the value of the actual parameters is copied into the formal
parameters. In other words, we can say that the value of the variable is used in the
function call in the call by value method.
o In call by value method, we can not modify the value of the actual parameter by the
formal parameter.
o In call by value, different memory is allocated for actual and formal parameters since the
value of the actual parameter is copied into the formal parameter.
o The actual parameter is the argument which is used in the function call whereas formal
parameter is the argument which is used in the function definition.

Let's try to understand the concept of call by value in c language by the example given below:

1. #include<stdio.h>  
2. void change(int num) {    
3.     printf("Before adding value inside function num=%d \n",num);    
4.     num=num+100;    
5.     printf("After adding value inside function num=%d \n", num);    
6. }    
7. int main() {    
8.     int x=100;    
9.     printf("Before function call x=%d \n", x);    
10.     change(x);//passing value in function    
11.     printf("After function call x=%d \n", x);    
12. return 0;  
13. }    
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by Value Example: Swapping the values of the two variables


1. #include <stdio.h>  
2. void swap(int , int); //prototype of the function   
3. int main()  
4. {  
5.     int a = 10;  
6.     int b = 20;   
7.     printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a a
nd b in main  
8.     swap(a,b);  
9.     printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual parameter
s do not change by changing the formal parameters in call by value, a = 10, b = 20  
10. }  
11. void swap (int a, int b)  
12. {  
13.     int temp;   
14.     temp = a;  
15.     a=b;  
16.     b=temp;  
17.     printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters, a = 20
, b = 10   
18. }  
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20

Call by reference in C

o In call by reference, the address of the variable is passed into the function call as the
actual parameter.
o The value of the actual parameters can be modified by changing the formal parameters
since the address of the actual parameters is passed.
o In call by reference, the memory allocation is similar for both formal parameters and
actual parameters. All the operations in the function are performed on the value stored at
the address of the actual parameters, and the modified value gets stored at the same
address.

Consider the following example for the call by reference.

1. #include<stdio.h>  
2. void change(int *num) {    
3.     printf("Before adding value inside function num=%d \n",*num);    
4.     (*num) += 100;    
5.     printf("After adding value inside function num=%d \n", *num);    
6. }      
7. int main() {    
8.     int x=100;    
9.     printf("Before function call x=%d \n", x);    
10.     change(&x);//passing reference in function    
11.     printf("After function call x=%d \n", x);    
12. return 0;  
13. }    
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200
Call by reference Example: Swapping the values of the two variables
1. #include <stdio.h>  
2. void swap(int *, int *); //prototype of the function   
3. int main()  
4. {  
5.     int a = 10;  
6.     int b = 20;   
7.     printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a a
nd b in main  
8.     swap(&a,&b);  
9.     printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual paramet
ers do change in call by reference, a = 10, b = 20  
10. }  
11. void swap (int *a, int *b)  
12. {  
13.     int temp;   
14.     temp = *a;  
15.     *a=*b;  
16.     *b=temp;  
17.     printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters, a = 
20, b = 10   
18. }  
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10

Difference between call by value and call by reference in c

No Call by value Call by reference


.

1 A copy of the value is passed into the function An address of value is passed into the function

2 Changes made inside the function is limited to the Changes made inside the function validate outside of
function only. The values of the actual parameters do the function also. The values of the actual parameters
not change by changing the formal parameters. do change by changing the formal parameters.

3 Actual and formal arguments are created at the Actual and formal arguments are created at the same
different memory location memory location

You might also like