Introduction to C
Introduction to C
Introduction
• C is a general-purpose programming language that is
extremely popular, simple and flexible.
• It is machine-independent, structured programming
language which is used extensively in various
applications.
• C was the basic language to write everything from
operating systems (Windows and many others) to
complex programs like the Oracle database, Git, Python
interpreter and more.
History of C language
• The base or father of programming languages is 'ALGOL‘.
• It was first introduced in 1960. 'ALGOL' was used on a
large basis in European countries.
• 'ALGOL' introduced the concept of structured
programming to the developer community.
• In 1967, a new computer programming language was
announced called as 'BCPL' which stands for Basic
Combined Programming Language.
• BCPL was designed and developed by Martin Richards,
especially for writing system software.
• In 1970 a new programming language called 'B' was
introduced by Ken Thompson that contained multiple
features of 'BCPL‘.
• This programming language was created using UNIX
operating system at AT&T and Bell Laboratories.
• Both the 'BCPL' and 'B' were system programming
languages.
• In 1972, a great computer scientist Dennis Ritchie
created a new programming language called 'C' at the
Bell Laboratories.
• It was created from 'ALGOL', 'BCPL' and 'B' programming
languages.
• 'C' programming language contains all the features of
these languages and many more additional concepts
that make it unique from other languages.
Features of C
1. Simple
C language is simple and easy to learn. The syntax of C is simple and gives flexibility
to the programmer with its wide variety of in-built functions and data types.
2. Portable
C is a machine independent language, which means a C program written one
machine can run on another machine without requiring a code change.
3. Fast
C is a compiler based language. C is power packed with several features but it is not
bloated like some other programming languages, it supports only useful features
which makes the compilation of C file fast.
4. Extensible
C program supports code modifications and addition of new code to the already
existing programs, this makes C language extensible. It becomes easier to add new
functionalities to the existing C programs.
5. Rich libraries:
C libraries are full of useful in-built functions. These functions can be used frequently
to perform some repeated tasks.
6. Dynamic memory allocation
Dynamic memory allocation means, optimizing and allocating the memory during
runtime. C language supports dynamic memory allocation, which supports function
like free() to free the un-utilized memory space and other memory management
functions such as malloc(), calloc() etc.
7. Reusability
Function is a block of code that is used to perform a specific task. Along with the in-
built predefined functions, C language allows you to create you own functions that
you can create for a reoccurring tasks. This improves the reusability of the code and
avoids the unnecessary writing of the same code again and again.
8. Mid level programming language
C language provides the benefits of high level and low-level languages both. C allows
manipulation of hardware just like low level language and allows high user end
functionalities like high-level languages.
9. Supports pointers
C language supports pointers. The pointer in C allows you to directly interact with the
memory.
10. Recursion
C supports recursion. Recursion means a function calls itself. Recursion provides
the features of code reusability and backtracking.
C Program Structure
1. Documentation section:
• In this section consist of a set of comment lines giving
the name of the program, the author or Programmer
name and other details.
• Ex: comment for single line
// The program to find simple interest
// Created by: Vish on 21/11/2020 10:42am
• Comments for multiple line
/* The program to find simple interest
Created by: Vish on 21/11/2022 10:42am */
2. LINK SECTION
• Link section provides the instruction to the
compiler to link function from the system library.
• Ex: #include<stdio.h>
3. DEFINITION SECTION
• The definition section defines all the symbols
constants.
• Ex: #define PI 3.142
4. global variables section
Example:
int number=18;
float salary=20000.00;
Format Specifiers
• Format specifiers are used together with the printf()
function to tell the compiler what type of data the
variable is storing. It is basically a placeholder for the
variable value.
int main() {
// Create variables
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
char myLetter = 'D'; // Character
// Print variables
printf("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);
return 0;
}
Data Types in C
• Data types refer to the type of data that we are
using in a C program.
• Whenever we utilise a data type in a C program, we
define the variables or functions used in it.
• We do so because we must specify the type of data
that is in use, so that the compiler knows exactly
what type of data it must expect from the given
program.
• A data type specifies the type of data that a
variable can store such as integer, floating,
character, etc.
Primary Data Types in C
• Here are the five primitive or primary data types that
one can find in C programming language:
1. Integer – We use these for storing various whole
numbers, such as 5, 8, 67, 2390, etc.
2. Character – It refers to all ASCII character sets as well
as the single alphabets, such as ‘x’, ‘Y’, etc.
3. Double – These include all large types of numeric
values.
4. Floating-point – These refer to all the real number
values or decimal points, such as 40.1, 820.673, 5.9, etc.
5. Void – This term refers to no values at all. We mostly
use this data type when defining the functions in a
program.
Integer
• Integers are whole numbers that can have both
zero, positive and negative values but no decimal
values.
• For example: 0, -5, 10
• We can use int for declaring an integer variable.
int id;
• Here, id is a variable of type integer.
• You can declare multiple variables at once in C
programming. For example,
int id, age;
• The size of int is usually 4 bytes (32 bits). And, it can
take 232 distinct states from -
2147483648 to 2147483647.
float and double
• float and double are used to hold real numbers.
float salary;
double price;
• What's the difference between float and double?
• The size of float is 4 bytes. And the size of double is 8
bytes.
char
• Keyword char is used for declaring character type
variables. For example,
char test = 'h';
• The size of the character variable is 1 byte.
Declaration of variable
• After designing suitable variable names, we must
declare them to the compiler.
• Declaration does two things:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
• The declaration of variables must be done before they
are used in the program.
Primary Type Declaration
• A variable can be used to store a value of any data type.
• That is, the name has nothing to do with its type.
• The syntax for declaring a variable is as follows:
data-type v1,v2,....vn;
• v1, v2, ...vn are the names of variables.
• Variables are separated by commas.
• A declaration statement must end with a semicolon.
Ex: int count;
int number, total;
double ratio;
• int and double are the keywords to represent integer type
and real type data values respectively.
Assigning value to variable
• Values can be signed to variables using the assignment
operator = as follows
variable_name = constant;
Ex: initial_value=0;
final_value=100:
balance= 75.84;
yes = ‘x’;
float a; a=10; a=10.00
• An assignment statement implies that the value of the
variable on the left of the 'equal sign is set equal to the
value of the quantity (or the expression) on the right.
year= year + 1;
• means that the 'new value of year is equal to the 'old
value of year plus 1.
• During assignment operation, C converts the type of
value on the right-hand side to the type on the left.
• This may involve truncation when real value is converted
to an integer.
• It is also possible to assign a value to a variable at the
time the variable is declared. This takes the following
form:
data-type variable_name = constant;
Ex: int final_value= 100;
char yes = 'x';
double balance = 75.84;
Defining symbolic Constants
return 0;
}
C Relational Operators
• A relational operator checks the relationship
between two operands. If the relation is true, it
returns 1; if the relation is false, it returns value 0.
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10;
return 0;
}
C Logical Operators
• An expression containing logical operator returns
either 0 or 1 depending upon whether expression
results true or false. Logical operators are
commonly used in decision making in C
programming.
Operator Description
And operator. It performs logical conjunction
of two expressions. (if both expressions
&& evaluate to True, result is True. If either
expression evaluates to False, the result is
False)
Or operator. It performs a logical disjunction
|| on two expressions. (if either or both
expressions evaluate to True, the result is True)
Not operator. It performs logical negation on
!
an expression.
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;
return 0;
}
Assignment Operators
• An assignment operator is used for assigning a
value to a variable. The most common assignment
operator is = .
// Working of assignment operators
#include <stdio.h>
int main()
{
int a = 5, c;
c = a; // c is 5
printf("c = %d\n", c);
c += a; // c is 10
printf("c = %d\n", c);
c -= a; // c is 5
printf("c = %d\n", c);
c *= a; // c is 25
printf("c = %d\n", c);
c /= a; // c is 5
printf("c = %d\n", c);
c %= a; // c = 0
printf("c = %d\n", c);
return 0;
}
Bitwise Operators
• Bitwise operators are used in C programming to
perform bit-level operations.
Conditional Operator
int main() {
return 0;
}
Explicit Type Conversion In C
• In explicit type conversion, we manually convert
values of one data type to another type.
#include<stdio.h>
int main() {
return 0;
}
Branching Statements
•The statements that transfer the control from one place to other place in the
program with or without any condition are called branch statements or selection
statements.
•The branching statements are classified into two types:
➢Conditional branch statements
➢Unconditional branch statements
✓int a,b;
➢if(a>b)
printf(“\n a is greater than b”);
➢if(b>a)
printf(“\n b is greater than a”);
if-else statement
•If one set of activities have to be performed when an expression is evaluated to true and another set
of activities have to be performed when an expression is evaluated to false, then if-else statement is
used.
•The if-else statement is used when we must choose between two choices (alternatives). Hence is
also called as “Two-way Decision or Selection Statement”.
• Syntax:
if(Test Expression)
{
Statement block 1;
// Body of if
}
else
{
Statement block 2;
// Body of else
}
Statement x;
Example
✓int age;
if(age>=18)
printf(“\nThe person is eligible to vote”);
else
printf(“\nThe person is not eligible to vote”);
✓int x,y;
if(x==y)
printf(“Numbers are equal”);
else
printf(“Numbers are not equal”);
✓int a,b;
if(a>b)
printf(“\n a is greater than b”);
else
printf(“\n b is greater than a”);
Nested if-else statement
•If we have series of decisions then only if else statement is not enough then we
use nested if statement.
•When an action has to be performed based on many decisions involving various
types of expressions and variables, then this statement is used. So it is called as
“Multi-way decision statement”.
• Syntax
Example
int a,b,c;
if(a>b)
{
if(a>c)
printf(“Max=%d”,a);
else
printf(“Max=%d”,c);
}
else
{
if(b>c)
printf(“Max=%d”,b);
else
printf(“Max=%d”,c);
}
else-if-ladder or Cascaded if-else or if-else-if Statement
•Used for multipath decision
•It is a chain of ifs in which the statement associated with each else is an if.
•It is a special case of nested-if statement where nesting takes place only in the
else part.
• Syntax
Example
✓int x,y,z;
if(x==y)
printf(“\n The two numbers are equal”);
else if(x>y)
printf(“\n %d is greater than %d”,x,y);
else
printf(“\n %d is less than %d”,x,y);
✓int n;
if(n==0)
printf(“Number is zero”);
else if(n>0)
printf(“Number is positive”);
else
printf(“Number is negative”);
Example
✓int a,b,c;
if(a>b && a>c)
printf(“\n %d is the largest number”,a);
else if(b>a && b>c)
printf(“\n %d is the largest number”,b);
else
printf(“\n %d is the largest number”,c);
✓int marks;
if(marks>=75)
printf(“\n First Class with Distinction”);
else if(marks>=60&&marks<75)
printf(“\n First Class”);
else if(marks>=50&&marks<60)
printf(“\n Second Class”);
else if(marks>=40&&marks<50)
printf(“\n Third Class”);
else
printf(“\n Fail”);
switch statement
•The ‘switch’ statement is a control statement used to make a select one
alternative among several alternatives.
•It is a “multi-way decision statement”.
•The switch statement tests the value of a given variable (or expression)against a
list of case values and when a match is found, a block of statement associated
with that case is executed.
•Syntax:
Looping Statements in C
•A loop is a way of repeating lines of code more than
once and the process is called looping.
•The block of code contained within the loop will be
executed again and again until the condition required
by the loop is met.
while loop
• A while loop in C programming repeatedly executes
a target statement as long as a given condition is
true.
Syntax
while(condition)
{
statement(s);
}
#include <stdio.h>
int main ()
{
int a = 10;
while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
}
return 0;
}
do...while 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
do
{
statement(s);
} while( condition );
#include <stdio.h>
int main ()
{
int a = 10;
do
{
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );
return 0;
}
While Do While
It checks the condition first and then This loop will execute the statement(s) at
executes statement(s) least once, then the condition is checked.
In this loop, the condition is mentioned at The loop condition is specified after the block
the starting of the loop. is executed.
Generally while loop is written as: Generally do while loop is written as:
while (condition) { Statements; // loop body do{ Statements; //loop body } while
} (condition);
for Loop
• A for loop is a more efficient loop structure in ‘C’
programming. The general structure of for loop syntax
in C is as follows:
• Syntax of For Loop in C:
for (initial value; condition; incrementation or decrementation )
{
statements;
}
• How for loop works?
• The initialization statement is executed only once.
• Then, the test expression is evaluated. If the test expression
is evaluated to false, the for loop is terminated.
• However, if the test expression is evaluated to true,
statements inside the body of the for loop are executed,
and the update expression is updated.
• Again the test expression is evaluated.
• This process goes on until the test expression is false.
When the test expression is false, the loop terminates.
// Print numbers from 1 to 10
#include <stdio.h>
int main()
{
int i;
Syntax:
for (initialization; condition; update)
{
for(initialization; condition; update)
{
// inner loop statements.
}
// outer loop statements.
}
Nested For Loop
Example:
#include <stdio.h>
int main()
{
int n;// variable declaration
printf("Enter the value of n :");
// Displaying the n tables.
for(int i=1;i<=n;i++) // outer loop
{
for(int j=1;j<=10;j++) // inner loop
{
printf("%d\t",(i*j)); // printing the value.
}
printf("\n");
}
Unconditional Branch statements
•The statements that transfer the control from one place to another place in the
program without any condition are called Unconditional branch statements.
break
• It is a keyword which is used to terminate the loop
(or) exit from the block.
• The control jumps to next statement after the loop
(or) block.
• break is used with for, while, do-while and switch
statement.
• When break is used in nested loops then, only the
innermost loop is terminated.
#include<stdio.h>
main( ){
int i;
for (i=1; i<=5; i++){
printf ("%d", i);
if (i==3)
break;
}
}
continue
• The continue statement skips the current iteration
of the loop and continues with the next iteration.
#include<stdio.h>
int main()
{
int i=1;//initializing a local variable
//starting a loop from 1 to 10
for(i=1;i<=10;i++)
{
if(i==5) //if value of i is equal to 5, it will continue the loop
{
continue;
}
printf("%d \n",i);
}//end of for loop
return 0;
}
goto statement
•The goto statement is a ‘jump’ statement that
transfers the control to the specified statement
(Label) in a program unconditionally.
•The specified statement is identified by ‘label’(
symbolic name ). Label can be any valid variable
name that is followed by a colon (:).
#include <stdio.h>
void checkEvenOrNot(int num)
{
if (num % 2 == 0)
// jump to even
goto even;
else
// jump to odd
goto odd;
even:
printf("%d is even", num);
// return if even
return;
odd:
printf("%d is odd", num);
}
int main() {
int num = 26;
checkEvenOrNot(num);
return 0;
}