0% found this document useful (0 votes)
2 views

Introduction to C

C is a widely-used, general-purpose programming language known for its simplicity, portability, and efficiency. Developed in the early 1970s by Dennis Ritchie, it combines features from previous languages like ALGOL, BCPL, and B, making it suitable for system programming and application development. The document covers C's history, features, program structure, data types, and rules for identifiers and constants.

Uploaded by

shreyassupe346
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Introduction to C

C is a widely-used, general-purpose programming language known for its simplicity, portability, and efficiency. Developed in the early 1970s by Dennis Ritchie, it combines features from previous languages like ALGOL, BCPL, and B, making it suitable for system programming and application development. The document covers C's history, features, program structure, data types, and rules for identifiers and constants.

Uploaded by

shreyassupe346
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 116

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

• There are some variables that are used in more


than one function.
• Such variables are called global variables and are
declared in the global declaration section that is
outside of all the functions.
• This section also declares all the user-defined
functions.
• Ex: int a,b; (it should be before main())
• Ex: float f; (it should be before main())
5. Main function section

• Every C program must have one main() function


section.
• This section contains two parts, declaration part and
executable part.
• The declaration part declares all the variables used
in the executable part.
• There is at least one statement in the executable
part.
• These two parts must appear between the opening
and the closing braces.
• The program execution begins at the opening brace
and ends at the closing brace.
• The closing brace of the main function section is the
logical end of the program.
• All statements in the declaration and executable
parts end with a semicolon(;).
• The subprogram section contains all the user-
defined functions that are called in the main
function.
6. Sub-program section

• User-defined functions are generally placed


immediately after the main function, although
they may appear in any order.
• All sections, except the main function section
may be absent when they are not required.
/** //Documentation
* file: age.c
* author: you
* description: program to find our age.
*/
#include <stdio.h> //Link
#define BORN 2000 //Definition
int age(int current); //Global Declaration
int main(void) //Main() Function
{
int current = 2021;
printf("Age: %d", age(current));
return 0;
}
int age(int current) { //Subprograms
return current - BORN;
}
Character set
• The characters that can be used to form words,
numbers and expressions depend upon the computer
on which the program is run.
• The characters in C are grouped into the following
categories:
1. Letters
2 Digits
3. Special characters
4 White spaces
Alphabets
• The C programming language provides support for
all the alphabets that we use in the English
language.
• Thus, in simpler words, a C program would easily
support a total of 52 different characters- 26
uppercase and 26 lowercase
Digits
• The C programming language provides the support
for all the digits that help in constructing/
supporting the numeric values or expressions in a
program.
• These range from 0 to 9, and also help in defining
an identifier. Thus, the C language supports a total
of 10 digits for constructing the numeric values or
expressions in any program.
Special Characters
• We use some special characters in the C language
for some special purposes, such as logical
operations, mathematical operations, checking of
conditions, backspaces, white spaces, etc.
• We can also use these characters for defining the
identifiers in a much better way. For instance, we
use underscores for constructing a longer name for
a variable, etc.
White Spaces
• The white spaces in the C programming language
contain the following:
• Blank Spaces
• Carriage Return
• Tab
• New Line
C Tokens
• C tokens are the basic buildings blocks
in C language which are constructed together to
write a C program.
• Each and every smallest individual units in
a C program are known as C tokens.
• As we can’t construct a sentence without the use
of words, similarly, we can’t construct a program
without using building blocks.
• The smallest individual element in a program is a
token. Without tokens, programming can’t be
done in C.
Keywords in C
• Keywords in C language are the pre-defined &
reserved words.
• Each having its own significance and hence has a
specific function associated with it.
• We can’t simply use keywords for assigning
variable names.
• All keywords must be written in lowercase.
Identifiers in C
• The C programmer has the provision to give names of
his own choice to variables, arrays, and functions.

• These are called identifiers in C.

• The user may use the combination of different


character sets available in the C language to name an
identifier but, there are certain rules to be abided by
the user on his part when naming identifiers
• These are user-defined names and consist of a
sequence of letters and digits.

• Both uppercase and lowercase letters are


permitted, although lowercase letters are
commonly used.
• Rules for Identifiers in C

• First character: The first character of the identifier should


necessarily begin with either an alphabet or an
underscore. It cannot begin with a digit.
• No special characters: C does not support the use of
special characters while naming an identifier.
For instance, special characters like comma or punctuation
marks can’t be used.
• No keywords: The use of keywords as identifiers is strictly
prohibited, as they are reserved words which we have
already discussed.
• No white space: White spaces include blank
spaces, newline and horizontal tab, which can’t be
used.
• Word limit: The identifier name can have an
arbitrarily long sequence that should not exceed 31
characters, otherwise, it would be insignificant.
• Case sensitive: Uppercase and lowercase
characters are treated differently.
Constants in C
• Often referred to as literals, constants, as
the name itself suggests, are fixed values
i.e. they cannot change their value during
program run once they are defined.
• Constants are also called literals.
• There are two ways to define constant in C
programming.
• const keyword
• #define preprocessor
#include<stdio.h>
int main()
{
const float PI=3.14;
PI=4.5;
printf("The value of PI is: %f",PI);
return 0;
}
#include<stdio.h>
#define PI 3.142
int main()
{
PI=4.5;
printf("The value of PI is: %f",PI);
return 0;
}
Strings in C
• Strings are used to store letters and digits.
• In C programming, the one-dimensional array of
characters are called strings. It is enclosed within
double quotes.
• The termination of a string is represented by the
null character that is ‘\0’. The size of a string is the
number of individual characters it has.
Variables
• Variables are containers for storing data values.

• In C, there are different types of variables (defined with


different keywords), for example:

• int - stores integers (whole numbers), without decimals,


such as 123 or -123
• float - stores floating point numbers, with decimals,
such as 19.99 or -19.99
• char - stores single characters, such as 'a' or 'B'. Char
values are surrounded by single quotes
The general rules for naming variables
are:

• Names can contain letters, digits and underscores


• Names must begin with a letter or an underscore
(_)
• Names are case sensitive (myVar and myvar are
different variables)
• Names cannot contain whitespaces or special
characters like !, #, %, etc.
• Reserved words (such as int) cannot be used as
names
Declaring (Creating) Variables

To create a variable, specify the type and


assign it a value:
type variableName = value;

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.

• A format specifier starts with a percentage sign %,


followed by a character.

• For example, to output the value of an int variable, you


must use the format specifier %d or %i surrounded by
double quotes, inside the printf() function:
Example
#include <stdio.h>

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

• The constants may appear repeatedly in a number


of places in the program.
• Example a constant is 3.142, representing the value
of the mathematical constant "pi".
• We face two problems in the subsequent use of
such programs. These are,
1. problem in modification of the program and
2. problem in understanding the program
• Assignment of constants to a symbolic name frees us
from these problems.
• For example, name STRENGTH to define the number of
students and PASS MARK to define the pass marks
required in a subject.
• Constant values are assigned to these names at the
beginning of the program.
• Subsequent use of the names STRENGTH and PASS
MARK in the program has the effect of causing their
defined values to be automatically substituted at the
appropriate points.
A constant is defined as follows
#define symbolic-name value-of-constant

• Valid examples of constant definitions are:


#define STRENGTH 100
#define PASSMARK 50
#define MAX 200
#define PI 3.14159
• Symbolic names are sometimes called constant
identifiers.
• Since the symbolic names are constants (not
variables), they do not appear in declarations.
• The following rules apply to a #define statement which
define a symbolic constant:
1. Symbolic names have the same form as variable
names. (Symbolic names are written in CAPITALS to
visually distinguish them from the normal variable
names, which are written in lowercase letters This is
only a convention, not a rule.)
2. No blank space between the pound sign # and the
word define is permitted.
3. # must be the first character in the line.
4. A blank space is required between #define and
symbolic name and between the symbolic name and
the constant.
5. #define statements must not end with a semicolon.
6. After definition, the symbolic name should not be
assigned any other value within the program by
using an assignment statement. For example,
STRENGTH = 200; is illegal.
7. Symbolic names are NOT declared for data types.
Its data type depends on the type of constant.
8. #define statements may appear anywhere in the
program but before it is referenced in the program
(the usual practice is to place them in the beginning
of the program),
• #define statement is a preprocessor compiler
directive and is much more powerful than what has
been mentioned here.
#include<stdio.h>
//#define PI 3.142
int main()
{
const float PI=3.142;
float radius, area;
printf(“Enter the value of radius\n”);
scanf(“%f”, &radius);
area=PI*radius*radius; //area=3.142*5*5
printf(“Area of Circle is = %.2f”, area);
return 0;
}
Operators in C
• C operators are symbols that are used to perform
mathematical or logical manipulations.
• Operations are performed on operands. Operators can be
classified into three broad categories, according to the
number of operands used. Which are as follows:
1. Unary:
It involves the use of one a single operand. For instance, ’!’ is a
unary operator which operates on a single variable, say ‘c’ as !c
which denotes its negation or complement.
2. Binary: It involves the use of 2 operands. They are
further classified as:
• Arithmetic
• Relational
• Logical
• Assignment
• Bitwise
• Conditional

3. Ternary: It involves the use of 3 operands. For


instance, ?: Is used in place of if-else conditions.
Arithmetic Operators
• Arithmetic Operators are used to performing
mathematical calculations like addition (+),
subtraction (-), multiplication (*), division (/) and
modulus (%).
// Working of arithmetic operators
#include <stdio.h>
int main()
{
int a = 9,b = 4, c;
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}
Increment and Decrement
• Increment and Decrement Operators are useful
operators generally used to minimize the
calculation, i.e. ++x and x++ means x=x+1 or --x and
x−−means x=x-1.
• But there is a slight difference between ++ or
−− written before or after the operand.
• Applying the pre-increment first add one to the
operand and then the result is assigned to the
variable on the left whereas post-increment first
assigns the value to the variable on the left and
then increment the operand.
// Working of increment and decrement operators
#include <stdio.h>
int main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;

printf("++a = %d \n", ++a);


printf("--b = %d \n", --b);
printf("++c = %f \n", ++c);
printf("--d = %f \n", --d);

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;

printf("%d == %d is %d \n", a, b, a == b);


printf("%d == %d is %d \n", a, c, a == c);
printf("%d > %d is %d \n", a, b, a > b);
printf("%d > %d is %d \n", a, c, a > c);
printf("%d < %d is %d \n", a, b, a < b);
printf("%d < %d is %d \n", a, c, a < c);
printf("%d != %d is %d \n", a, b, a != b);
printf("%d != %d is %d \n", a, c, a != c);
printf("%d >= %d is %d \n", a, b, a >= b);
printf("%d >= %d is %d \n", a, c, a >= c);
printf("%d <= %d is %d \n", a, b, a <= b);
printf("%d <= %d is %d \n", a, c, a <= c);

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;

result = (a == b) && (c > b);


printf("(a == b) && (c > b) is %d \n", result);

result = (a == b) && (c < b);


printf("(a == b) && (c < b) is %d \n", result);

result = (a == b) || (c < b);


printf("(a == b) || (c < b) is %d \n", result);
result = (a != b) || (c < b);
printf("(a != b) || (c < b) is %d \n", result);

result = !(a != b);


printf("!(a != b) is %d \n", result);

result = !(a == b);


printf("!(a == b) is %d \n", 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

• The conditional operator is also known as a ternary


operator. The conditional statements are the
decision-making statements which depends upon
the output of the expression. It is represented by
two symbols, i.e., '?' and ':'.
• As conditional operator works on three operands,
so it is also known as the ternary operator.
• The behavior of the conditional operator is similar
to the 'if-else' statement as 'if-else' statement is
also a decision-making statement.
Syntax
Expression1? expression2: expression3;
Example
#include <stdio.h>
int main()
{
int age; // variable declaration
printf("Enter your age");
scanf("%d",&age);
(age>=18)?(printf("eligible for voting")):(printf("n
ot eligible for voting")); // conditional operator
return 0;
}
Type Conversion
• In C programming, we can convert the value of one
data type (int, float, double, etc.) to another. This
process is known as type conversion.
• In C, there are two types of type conversion:
• Implicit Conversion
• Explicit Conversion
Implicit Type Conversion In C
• In implicit type conversion, the value of one type is
automatically converted to the value of another
type
#include<stdio.h>

int main() {

// create a double variable


double value = 4150.12;
printf("Double Value: %.2lf\n", value);

// convert double value to integer


int number = value;
printf("Integer Value: %d", number);

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() {

// create an integer variable


int number = 35;
printf("Integer Value: %d\n", number);

// explicit type conversion


double value = (double) number;
printf("Double Value: %.2lf", value);

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

➢Conditional branch statements


•The statements that transfer the control from one place to another place in the
program based on some conditions are called Conditional branch statements.
Conditional Branch statements
•Conditional Branch statements allow us to control the flow of our program’s
execution based upon conditions known only during run time.
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.
Simple if Statement
•The ‘if’ statement is the simplest form of decision control statement.
•When a set of statements have to be executed when an expression (condition) is
evaluated to true or skipped when an expression (condition) is evaluated to false,
then if statement is used.
•It is used whenever there is only one choice (alternative). Hence it is also called as
“One-way decision or selection statement”.
• Syntax:
if(Test Expression)
{
Statement 1;
Statement 2;
... Body of if

Statement n;
}
Statement x;
Example
✓int age;
➢if(age>=18)
printf(“\nThe person is eligible to vote”);
➢if(age<18)
printf(“\nThe person is not eligible to vote”);
✓int x,y;
➢ if(x==y)
printf(“Numbers are equal”);
➢if(x!=y)
printf(“Numbers are not equal”);

✓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.

It is an entry controlled loop. It is an exit controlled loop.

In this loop, the condition is mentioned at The loop condition is specified after the block
the starting of the loop. is executed.

Statement(s) can be executed zero times if


Statement is executed at least once.
the condition is false.

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;

for (i = 1; i < 11; ++i)


{
printf("%d ", i);
}
return 0;
}
Nested For Loop
The nested for loop means any type of loop which is defined inside
the 'for' loop.

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;
}

You might also like