Introduction to Programming
By
M. Srinuvasu Rao Naidu
What is C?
C is a general-purpose programming language created by Dennis
Ritchie at the At&T Bell Laboratories in 1972.
It is a very popular language, despite being old. The main reason
for its popularity is because it is a fundamental language in the
field of computer science.
C is strongly associated with UNIX, as it was developed to write
the UNIX operating system.
C Syntax
#include <stdio.h>
int main()
{
printf("Hello World!");
return 0;
}
Line 1: #include <stdio.h> is a header file library that lets us work with input and
output functions, such as printf() (used in line 4). Header files add functionality to C
programs.
Line 2: A blank line. C ignores white space. But we use it to make the code more
readable.
Line 3: Another thing that always appear in a C program is main(). This is called
a function. Any code inside its curly brackets {} will be executed.
Line 4: printf() is a function used to output/print text to the screen. In our example, it
will output "Hello World!".
Line 5: return 0 ends the main() function.
Line 6: Do not forget to add the closing curly bracket } to actually end the main
function.
Structure of the C Program
There are 6 basic sections responsible for the proper execution of a
program. Sections are mentioned below:
• Documentation
•Preprocessor Section
•Definition
•Global Declaration
•Main() Function
•Sub Programs
C Statements
A computer program is a list of "instructions" to be "executed" by a computer.
In a programming language, these programming instructions are
called statements.
EX: printf("Hello World!");
•Most C programs contain many statements.
•EX: printf("Hello World!");
printf("Have a good day!");
return 0;
C Output (Print Text)
• To output values or print text in C, you can use the printf() function:
Example :
printf("Hello World!");
• When you are working with text, it must be wrapped inside double quotations
marks "“ .
•You can use as many printf() functions as you want. However, note that it does
not insert a new line at the end of the output.
Example :
#include <stdio.h>
int main()
{
printf("Hello World!");
printf("I am learning C.");
printf("And it is awesome!");
return 0;
}
C Comments
• Comments can be used to explain code, and to make it more readable. It can also be
used to prevent execution when testing alternative code.
• Comments can be singled-lined or multi-lined.
Single-line Comments
Single-line comments start with two forward slashes (//).
Any text between // and the end of the line is ignored by the compiler (will not be
executed).
Example
// This is a comment
printf("Hello World!");
C Multi-line Comments
Multi-line comments start with /* and ends with */.
Any text between /* and */ will be ignored by the compiler:
Example
/* The code below will print the words Hello World!
to the screen, and it is amazing */
printf("Hello World!");
C Variables
Variables are containers for storing data values, like numbers and characters.
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'. Characters are surrounded
by single quotes
• To create a variable, specify the type and assign it a value:
Syntax:
type variableName = value;
Variables(cont)
Where type is one of C types (such as int), and variableName is the name of the
variable (such as x or myName). The equal sign is used to assign a value to the
variable.
So, to create a variable that should store a number, look at the following example:
Example:
Create a variable called myNum of type int and assign the value 15 to it:
int myNum = 15;
You can also declare a variable without assigning the value, and assign the value later:
Example :
// Declare a variable
int myNum;
// Assign a value to the variable
myNum = 15;
C Format Specifiers
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, use the format
specifier %d surrounded by double quotes (""), inside the printf() function:
Example
int myNum = 15;
printf("%d", myNum); // Outputs 15
To print other types, use %c for char and %f for float:
Example
// Create variables
int myNum = 15; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
char myLetter = 'D'; // Character
// Print variables
printf("%dn", myNum);
printf("%fn", myFloatNum);
printf("%cn", myLetter);
cont
* To combine both text and a variable, separate them with a comma inside
the printf() function:
Example
int myNum = 15;
printf("My favorite number is: %d", myNum);
* To print different types in a single printf() function, you can use the following:
Example
int myNum = 15;
char myLetter = 'D';
printf("My number is %d and my letter is %c", myNum, myLetter);
Print Values Without Variables
* You can also just print a value without storing it in a variable, as long as you use the
correct format specifier:
Example
printf("My favorite number is: %d", 15);
printf("My favorite letter is: %c", 'D');
Change Variable Values
* If you assign a new value to an existing variable, it will overwrite the previous value:
Example
int myNum = 15; // myNum is 15
myNum = 10; // Now myNum is 10
* You can also assign the value of one variable to another:
Example
int myNum = 15;
int myOtherNum = 23;
// Assign the value of myOtherNum (23) to myNum
myNum = myOtherNum;
// myNum is now 23, instead of 15
printf("%d", myNum);
*Or copy values to empty variables.
*To declare more than one variable of the same type, use a comma-separated list:
Example
int x = 5, y = 6, z = 50;
* You can also assign the same value to multiple variables of the same type:
Example
int x, y, z;
x = y = z = 50;
C Variable Names (Identifiers)
* All C variables must be identified with unique names.
* These unique names are called identifiers.
* Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).
Note: It is recommended to use descriptive names in order to create understandable and
maintainable code:
Example
// Good variable name
int minutesPerHour = 60;
// OK, but not so easy to understand what m actually is
int m = 60;
The general rules for naming variables are:
1. Names can contain letters, digits and underscores
2. Names must begin with a letter or an underscore (_)
3. Names are case-sensitive (myVar and myvar are different variables)
4. Names cannot contain whitespaces or special characters like !, #, %, etc.
5. Reserved words (such as int) cannot be used as names
Data types in c
* The data type specifies the size and type of information the variable will store.
* Each data type requires different amounts of memory and has some specific operations
which can be performed over it.
Basic Format Specifiers
There are different format specifiers for each data type. Here are some of them:
Types of data type
Types of data type
C Type Conversion
Sometimes, you have to convert the value of one data type to another type. This is known
as type conversion.
For example, if you try to divide two integers, 5 by 2, you would expect the result to
be 2.5. But since we are working with integers (and not floating-point values), the
following example will just output 2:
Example
int x = 5;
int y = 2;
int sum = 5 / 2;
printf("%d", sum); // Outputs 2
•To get the right result, you need to know how type conversion works.
* There are two types of conversion in C:
1. Implicit Conversion (automatically)
2. Explicit Conversion (manually)
Implicit Conversion
* Implicit conversion is done automatically by the compiler when you assign a value of
one type to another.
For example, if you assign an int value to a float type:
Example
// Automatic conversion: int to float
float myFloat = 9;
printf("%f", myFloat); // 9.000000
Example
// Automatic conversion: float to int
int myInt = 9.99;
printf("%d", myInt); // 9
•As another example, if you divide two integers: 5 by 2, you know that the sum is 2.5.
• if you store the sum as an integer, the result will only display the number 2. Therefore, it
would be better to store the sum as a float or a double, right?
Example
float sum = 5 / 2;
printf("%f", sum); // 2.000000
* Why is the result 2.00000 and not 2.5? Well, it is because 5 and 2 are still integers in the
division. In this case, you need to manually convert the integer values to floating-point
values
Explicit Conversion
* Explicit conversion is done manually by placing the type in parentheses () in front of
the value.
* Considering our problem from the example above, we can now get the right result:
Example
// Manual conversion: int to float
float sum = (float) 5 / 2;
printf("%f", sum); // 2.500000
* You can also place the type in front of a variable:
Example
int num1 = 5;
int num2 = 2;
float sum = (float) num1 / num2;
printf("%f", sum); // 2.500000
* decimal precision
Output: 2.5
C Constants
* If you don't want others (or yourself) to change existing variable values, you can use
the const keyword.
* This will declare the variable as "constant", which means unchangeable and read-
only:
Example
const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable 'myNum'
You should always declare the variable as constant when you have values that are
unlikely to change:
Example
const int minutesPerHour = 60;
const float PI = 3.14;
•When you declare a constant variable, it must be assigned with a value
Another thing about constant variables, is that it is considered good practice to declare
them with uppercase.
It is not required, but useful for code readability and common for C programmers
Keywords in C
Keywords are predefined or reserved words that have special meanings to the compiler.
These are part of the syntax and cannot be used as identifiers in the program.
Keywords(Cont)
auto
auto is the default storage class variable that is declared inside a function or a block. auto
variables can only be accessed within the function/block they are declared. By default, auto
variables have garbage values assigned to them. Automatic variables are also called local
variables as they are local to a function.
EX : auto int num;
break and continue
The break statement is used to terminate the innermost loop. It generally terminates a loop
or a break statement. The continue statement skips to the next iteration of the loop.
Keywords(Cont)
switch, case, and default
The switch statement in C is used as an alternate to the if-else ladder statement. For a single
variable i.e, switch variable it allows us to execute multiple operations for different possible
values of a single variable.
char
char keyword in C is used to declare a character variable in the C programming language.
const
The const keyword defines a variable who’s value cannot be changed.
do
The do statement is used to declare a do-while loop. A do-while loop is a loop that executes
once, and then checks it’s condition to see if it should continue through the loop. After the
first iteration, it will continue to execute the code while the condition is true.
Keywords(Cont)
double and float
The doubles and floats are datatypes used to declare decimal type variables. They are
similar, but doubles have 15 decimal digits, and floats only have 7.
if-else
The if-else statement is used to make decisions, where if a condition is true, then it will
execute a block of code; if it isn’t true (else), then it will execute a different block of code.
enum
Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to
integral constants, the names make a program easy to read and maintain.
extern
The extern keyword is used to declare a variable or a function that has an external linkage
outside of the file declaration.
for
The “for” keyword is used to declare a for-loop. A for-loop is a loop that is specified to run a
certain amount of times.
goto
The goto statement is used to transfer the control of the program to the given label. It is used
to jump from anywhere to anywhere within a function.
int
int keyword is used in a type declaration to give a variable an integer type. In C, the integer
variable must have a range of at least -32768 to +32767.
Keywords(Cont)
short, long, signed, and unsigned
Different data types also have different ranges up to which they can store numbers. These
ranges may vary from compiler to compiler. Below is a list of ranges along with the
memory requirement and format specifiers on the 32-bit GCC compiler.
Keywords(Cont)
return
The return statement returns a value to where the function was called.
sizeof
sizeof is a keyword that gets the size of an expression, (variables, arrays, pointers, etc.) in
bytes.
register
Register variables tell the compiler to store variables in the CPU register instead of
memory. Frequently used variables are kept in the CPU registers for faster access.
static
The static keyword is used to create static variables. A static variable is not limited by a
scope and can be used throughout the program. It’s value is preserved even after it’s
scope.
struct
The struct keyword in C programming language is used to declare a structure. A structure
is a list of variables, (they can be of different data types), which are grouped together
under one data type.
typedef
The typedef keyword in C programming language is used to define a data type with a new
name in the program. typedef keyword is used to make our code more readable.
Keywords(Cont)
union
The union is a user-defined data type. All data members which are declared under the
union keyword share the same memory location.
void
The void keyword means nothing i.e, NULL value. When the function return type is used
as the void, the keyword void specifies that it has no return value.
volatile
The volatile keyword is used to create volatile objects. Objects which are declared volatile
are omitted from optimization as their values can be changed by code outside the scope of
the current code at any point in time.
C Operators
Operators are used to perform operations on variables and values.
C divides the operators into the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations
C Operators(cont)
Assignment Operators
Assignment operators are used to assign values to variables.
the assignment operator (=) to assign the value 10 to a variable called x:
Example
int x = 10;
C Operators(cont)
Comparison Operators
Comparison operators are used to compare two values (or variables). This is important in
programming, because it helps us to find answers and make decisions.
The return value of a comparison is either 1 or 0, which means true (1) or false (0). These
values are known as Boolean values, and you will learn more about them in the Booleans
and If..Else chapter.
C Operators(cont)
Logical Operators
You can also test for true or false values with logical operators.
Logical operators are used to determine the logic between variables or values, by
combining multiple conditions
C Operators(cont)
Bitwise Operators in C
1. The & (bitwise AND) in C takes two numbers as operands and does AND on
every bit of two numbers. The result of AND is 1 only if both bits are 1.
2. The | (bitwise OR) in C takes two numbers as operands and does OR on every bit
of two numbers. The result of OR is 1 if any of the two bits is 1.
3. The ^ (bitwise XOR) in C takes two numbers as operands and does XOR on
every bit of two numbers. The result of XOR is 1 if the two bits are different.
4. The << (left shift) in C takes two numbers, the left shifts the bits of the first
operand, and the second operand decides the number of places to shift.
5. The >> (right shift) in C takes two numbers, right shifts the bits of the first
operand, and the second operand decides the number of places to shift.
6. The ~ (bitwise NOT) in C takes one number and inverts all bits of it.
C User Input
User Input
You have already learned that printf() is used to output values in C.
To get user input, you can use the scanf() function:
Example
Output a number entered by the user:
// Create an integer variable that will store the number we get from the user
int myNum;
// Ask the user to type a number
printf("Type a number: n");
// Get and save the number the user types
scanf("%d", &myNum);
// Output the number the user typed
printf("Your number is: %d", myNum);
Multiple Inputs
The scanf() function also allow multiple inputs (an integer and a character)
Take String Input
You can also get a string entered by the user.
Ex:
char firstName[30];
scanf("%s", firstName);
C Booleans
Booleans
Very often, in programming, you will need a data type that can only have one of two
values, like:
YES / NO
ON / OFF
TRUE / FALSE
* For this, C has a bool data type, which is known as booleans.
* Booleans represent values that are either true or false.
* In C, the bool type is not a built-in data type, like int or char. It was introduced in C99,
and you must import the following header file to use it:
#include <stdbool.h>
* A boolean variable is declared with the bool keyword and can take the
values true or false:
EX: bool isProgrammingFun = true;
bool isFishTasty = false;
* Before trying to print the boolean variables, you should know that boolean values are
returned as integers:
1 (or any other number that is not 0) represents true
0 represents false
* * Therefore, you must use the %d format specifier to print a boolean value.
Control flow statements in Programming
Control flow statements are fundamental components of programming languages that
allow developers to control the order in which instructions are executed in a program
Branching statements in C
Branching Statements in C are those statements in C language that helps a
programmer to control the flow of execution of the program according to the
requirements. These Branching Statements are considered an essential aspect of the
Programming Languages and are essentially used for executing the specific
segments of code on basis of some conditions.
Types of Branching Statements in C
Branching statements are mainly categorized as follows.
1. Conditional Branching Statements
2. Unconditional Branching Statements
Branching statements in C(cont)
Conditional Branching Statements
Conditional Branching Statements in C are used to execute the specific blocks of code
on the basis of some condition (as per requirements). These type of Branching statements
in C enables the programmers to execute the code only and only certain statements are
met.
Branching statements in C(cont)
Unconditional Branching Statements in C
Unconditional branching statements are used in C to change the normal flow of
program execution. These statements allow programmers to jump to a specific point
in their code regardless of any condition.
There are the following types of unconditional branching statements in C.
Conditional statement
If Statement
The if statement is the most simple decision-making
statement. It is used to decide whether a certain
statement or block of statements will be executed or
not i.e
•if a certain condition is true then a block of statements
is executed otherwise not.
Syntax of if Statement
if(condition)
{
// Statements to execute if
// condition is true
}
If (Example)
// C program to illustrate If statement
#include <stdio.h>
int main()
{
int i = 10;
if (i > 15) //condition is if “i” is grater than 15 if block is executed
{
printf("10 is greater than 15");
}
printf("I am Not in if"); //if “if condition ” is false execute the Statement
}
Out put: I am Not in if
Else Statement
Use the else statement to specify a block of code to be
executed if the condition is false.
Syntax
if (condition)
{
// block of code to be executed if the condition is true
}
else
{
// block of code to be executed if the condition is false
}
Else Example
// C program to illustrate If statement
#include <stdio.h>
int main()
{
int i = 20;
if (i < 15) // if condition is true below block will execute
{
printf("i is smaller than 15");
}
else // condition is false execute the below code
{
printf("i is greater than 15");
}
return 0;
}
Out put: i is greater than 15
Nested if-else in C
A nested if in C is an if statement that is the target of another if
statement. Nested if statements mean an if statement inside another if
statement. Yes, C allow us to nested if statements within if statements,
i.e, we can place an if statement inside another if statement.
Syntax of Nested if-else
if (condition1)
{
// Executes when condition1 is true
if (condition_2)
{ // statement 1 }
else
{ // Statement 2 }
}
else
{
if (condition_3)
{ // statement 3 }
else
{ // Statement 4 }
}
Flow Chart
Nested if-else in C (EXP)
// C program to illustrate nested-if statement
#include <stdio.h>
int main()
{
int i = 10;
if (i == 10) {
// First if statement
if (i < 15)
printf("i is smaller than 15n");
// Nested - if statement
// Will only be executed if statement above
// is true
if (i < 12)
printf("i is smaller than 12 toon");
else
printf("i is greater than 15");
}
else {
if (i == 20) {
// Nested - if statement
// Will only be executed if
statement above
// is true
if (i < 22)
printf("i is smaller than 22 too
n");
else
printf("i is greater than 25");
}
}
return 0;
}
Out put: i is smaller than 15
i is smaller than 12 too
if-else-if Ladder in C
The if else if statements are used when the user has to decide among multiple options.
The C if statements are executed from the top down.
As soon as one of the conditions controlling the if is true, the statement associated with that if
is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true,
then the final else statement will be executed. if-else-if ladder is similar to the switch statement.
Syntax of if-else-if Ladder
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
if-else-if Ladder in C EXP
// C program to illustrate nested-if statement
#include <stdio.h>
int main()
{
int i = 20;
if (i == 10)
printf("i is 10");
else if (i == 15)
printf("i is 15");
else if (i == 20)
printf("i is 20");
else
printf("i is not present");
}
Out put: i is 20
switch Statement in C
The switch case statement is an alternative to the if else if ladder that can be used to
execute the conditional code based on the value of the variable specified in the
switch statement. The switch block consists of cases to be executed based on the
value of the switch variable.
Syntax of switch
switch (expression)
{
case value1:
statements;
case value2:
statements;
....
....
....
default:
statements;
}
switch Statement in C EXP
// C Program to illustrate the use of switch statement
#include <stdio.h>
int main()
{
// variable to be used in switch statement
int var = 2;
// declaring switch cases
switch (var)
{
case 1:
printf("Case 1 is executed");
break;
case 2:
printf("Case 2 is executed");
break;
default:
printf("Default Case is executed");
break;
}
return 0;
}
Output: Case 2 is executed
Conditional Operator in C
The conditional operator is used to add conditional code in our program. It is similar
to the if-else statement. It is also known as the ternary operator as it works on three
operands.
Syntax of Conditional Operator
(condition) ? [true_statements] : [false_statements];
Conditional Operator in C EXP
// C Program to illustrate the use of conditional operator
#include <stdio.h>
// driver code
int main()
{
int var;
int flag = 0;
// using conditional operator to assign the value to var
// according to the value of flag
var = flag == 0 ? 25 : -25;
printf("Value of var when flag is 0: %dn", var);
// changing the value of flag
flag = 1;
// again assigning the value to var using same statement
var = flag == 0 ? 25 : -25;
printf("Value of var when flag is NOT 0: %d", var);
return 0;
}
Out Put:
Value of var when flag is 0: 25
Value of var when flag is NOT 0: -25
C – Loops
Loops in programming are used to repeat a block of code until the specified condition is
met. A loop statement allows programmers to execute a statement or group of statements
multiple times without repetition of code.
There are mainly two types of loops in C Programming:
1. Entry Controlled loops: In Entry controlled loops the test condition is checked
before entering the main body of the loop. For Loop and While Loop is Entry-
controlled loops.
2. Exit Controlled loops: In Exit controlled loops the test condition is evaluated at the
end of the loop body. The loop body will execute at least once, irrespective of whether
the condition is true or false. do-while Loop is Exit Controlled loop.
For loop
•for loop in C programming is a repetition control structure
that allows programmers to write a loop that will be executed a
specific number of times. for loop enables programmers to
perform n number of steps together in a single line.
Syntax:
for (initialize expression; test expression; update expression)
{
//
// body of for loop
//
}
1. Initialization Expression: In this expression, we assign a loop
variable or loop counter to some value. for example: int i=1;
2. Test Expression: In this expression, test conditions are
performed. If the condition evaluates to true then the loop
body will be executed and then an update of the loop variable
is done. If the test expression becomes false then the control
will exit from the loop. for example, i<=9;
3. Update Expression: After execution of the loop body loop
variable is updated by some value it could be incremented,
decremented, multiplied, or divided by any value.
Flow chart
For loop Exp
// C program to illustrate for loop
#include <stdio.h>
// Driver code
int main()
{
int i = 0;
for (i = 1; i <= 10; i++)
{
printf( "Hello Worldn");
}
return 0;
}
Output:
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
While Loop
While loop does not depend upon the number of
iterations. In for loop the number of iterations was
previously known to us but in the While loop, the
execution is terminated on the basis of the test
condition. If the test condition will become false then it
will break from the while loop else body will be
executed.
Syntax:
initialization_expression;
while (test_expression)
{
// body of the while loop
update_expression;
}
Flow Chart
While Loop Exp
// C program to illustrate
// while loop
#include <stdio.h>
// Driver code
int main()
{
// Initialization expression
int i = 2;
// Test expression
while(i < 10)
{
// loop body
printf( "Hello Worldn");
// update expression
i++;
}
return 0;
}
Output
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
do-while Loop
The do-while loop is similar to a while loop but the
only difference lies in the do-while loop test condition
which is tested at the end of the body. In the do-while
loop, the loop body will execute at least
once irrespective of the test condition.
Syntax:
initialization_expression;
Do
{
// body of do-while loop
update_expression;
} while (test_expression);
Flow Chart
do-while Loop Exp
// C program to illustrate
// do-while loop
#include <stdio.h>
// Driver code
int main()
{
// Initialization expression
int i = 2;
do
{
// loop body
printf( "Hello Worldn");
// Update expression
i++;
// Test expression
} while (i < 1);
return 0;
}
Output:
Hello World
Infinite Loop
An infinite loop is executed when the test expression never becomes false and the
body of the loop is executed repeatedly. A program is stuck in an Infinite loop when
the condition is always true. Mostly this is an error that can be resolved by using Loop
Control statements.
// C program to demonstrate infinite
// loops using for loop
#include <stdio.h>
// Driver code
int main ()
{
int i;
// This is an infinite for loop
// as the condition expression
// is blank
for ( ; ; )
{
printf("This loop will run forever.n");
}
return 0;
}
Output
This loop will run forever.
This loop will run forever.
This loop will run forever
. ...
Continue Statement in C
The C continue statement resets program control to the beginning of the loop when
encountered. As a result, the current iteration of the loop gets skipped and the control
moves on to the next iteration. Statements after the continue statement in the loop are
not executed.
Syntax of continue in C
The syntax of continue is just the continue keyword placed wherever we want in the
loop body.
continue;
Use of continue in C
The continue statement in C can be used in any kind of loop to skip the current iteration.
In C, we can use it in the following types of loops:
1. Single Loops
2. Nested Loops
Using continue in infinite loops is not useful as skipping the current iteration won’t
make a difference when the number of iterations is infinite.
Continue Statement in C Exp
The working of the continue statement is as follows:
STEP 1: The loop’s execution starts after the loop condition
is evaluated to be true.
STEP 2: The condition of the continue statement will be
evaluated.
STEP 3A: If the condition is false, the normal execution will
continue.
STEP 3B: If the condition is true, the program control will
jump to the start of the loop and all the statements below the
continue will be skipped.
STEP 4: Steps 1 to 4 will be repeated till the end of the
loop.
Continue Statement in C Exp
#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;
}
Output
1
2
3
4
6
7
8
9
10
C break statement
The break is a keyword in C which is used to bring the program control out of the
loop. The break statement is used inside loops or switch statement. The break
statement breaks the loop one by one, i.e., in the case of nested loops, it breaks the
inner loop first and then proceeds to outer loops. The break statement in C can be used
in the following two scenarios:
1. With switch case
2. With loop
Syntax:
//loop or switch case
break;
C break statement Exp
Example:
#include<stdio.h>
#include<stdlib.h>
void main ()
{
int i;
for(i = 0; i<10; i++)
{
printf("%d ",i);
if(i == 5)
{
break;
}
}
printf("came outside of loop i = %d",i);
}
Output
0 1 2 3 4 5 came outside of loop i = 5
C goto statement
The goto statement is known as jump statement in C. As the name suggests, goto is
used to transfer the program control to a predefined label. The goto statment can be
used to repeat some part of the code for a particular condition. It can also be used to
break the multiple loops which can't be done by using a single break statement.
However, using goto is avoided these days since it makes the program less readable
and complecated.
Syntax:
label:
//some part of the code;
goto label;
C goto statement Exp
Example:
#include <stdio.h>
int main()
{
int num,i=1;
printf("Enter the number whose table you want
to print?");
scanf("%d",&num);
table:
printf("%d x %d = %dn",num,i,num*i);
i++;
if(i<=10)
goto table;
}
Out Put:
Enter the number whose
table you want to print?10
10 x 1 = 10
10 x 2 = 20
10 x 3 = 30
10 x 4 = 40
10 x 5 = 50
10 x 6 = 60
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100

Introduction to Programming c language.pptx

  • 1.
  • 2.
    What is C? Cis a general-purpose programming language created by Dennis Ritchie at the At&T Bell Laboratories in 1972. It is a very popular language, despite being old. The main reason for its popularity is because it is a fundamental language in the field of computer science. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
  • 3.
    C Syntax #include <stdio.h> intmain() { printf("Hello World!"); return 0; } Line 1: #include <stdio.h> is a header file library that lets us work with input and output functions, such as printf() (used in line 4). Header files add functionality to C programs. Line 2: A blank line. C ignores white space. But we use it to make the code more readable. Line 3: Another thing that always appear in a C program is main(). This is called a function. Any code inside its curly brackets {} will be executed. Line 4: printf() is a function used to output/print text to the screen. In our example, it will output "Hello World!". Line 5: return 0 ends the main() function. Line 6: Do not forget to add the closing curly bracket } to actually end the main function.
  • 4.
    Structure of theC Program There are 6 basic sections responsible for the proper execution of a program. Sections are mentioned below: • Documentation •Preprocessor Section •Definition •Global Declaration •Main() Function •Sub Programs
  • 5.
    C Statements A computerprogram is a list of "instructions" to be "executed" by a computer. In a programming language, these programming instructions are called statements. EX: printf("Hello World!"); •Most C programs contain many statements. •EX: printf("Hello World!"); printf("Have a good day!"); return 0;
  • 6.
    C Output (PrintText) • To output values or print text in C, you can use the printf() function: Example : printf("Hello World!"); • When you are working with text, it must be wrapped inside double quotations marks "“ . •You can use as many printf() functions as you want. However, note that it does not insert a new line at the end of the output. Example : #include <stdio.h> int main() { printf("Hello World!"); printf("I am learning C."); printf("And it is awesome!"); return 0; }
  • 7.
    C Comments • Commentscan be used to explain code, and to make it more readable. It can also be used to prevent execution when testing alternative code. • Comments can be singled-lined or multi-lined. Single-line Comments Single-line comments start with two forward slashes (//). Any text between // and the end of the line is ignored by the compiler (will not be executed). Example // This is a comment printf("Hello World!"); C Multi-line Comments Multi-line comments start with /* and ends with */. Any text between /* and */ will be ignored by the compiler: Example /* The code below will print the words Hello World! to the screen, and it is amazing */ printf("Hello World!");
  • 8.
    C Variables Variables arecontainers for storing data values, like numbers and characters. 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'. Characters are surrounded by single quotes • To create a variable, specify the type and assign it a value: Syntax: type variableName = value;
  • 9.
    Variables(cont) Where type isone of C types (such as int), and variableName is the name of the variable (such as x or myName). The equal sign is used to assign a value to the variable. So, to create a variable that should store a number, look at the following example: Example: Create a variable called myNum of type int and assign the value 15 to it: int myNum = 15; You can also declare a variable without assigning the value, and assign the value later: Example : // Declare a variable int myNum; // Assign a value to the variable myNum = 15;
  • 10.
    C Format Specifiers FormatSpecifiers •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, use the format specifier %d surrounded by double quotes (""), inside the printf() function: Example int myNum = 15; printf("%d", myNum); // Outputs 15 To print other types, use %c for char and %f for float: Example // Create variables int myNum = 15; // Integer (whole number) float myFloatNum = 5.99; // Floating point number char myLetter = 'D'; // Character // Print variables printf("%dn", myNum); printf("%fn", myFloatNum); printf("%cn", myLetter);
  • 11.
    cont * To combineboth text and a variable, separate them with a comma inside the printf() function: Example int myNum = 15; printf("My favorite number is: %d", myNum); * To print different types in a single printf() function, you can use the following: Example int myNum = 15; char myLetter = 'D'; printf("My number is %d and my letter is %c", myNum, myLetter); Print Values Without Variables * You can also just print a value without storing it in a variable, as long as you use the correct format specifier: Example printf("My favorite number is: %d", 15); printf("My favorite letter is: %c", 'D');
  • 12.
    Change Variable Values *If you assign a new value to an existing variable, it will overwrite the previous value: Example int myNum = 15; // myNum is 15 myNum = 10; // Now myNum is 10 * You can also assign the value of one variable to another: Example int myNum = 15; int myOtherNum = 23; // Assign the value of myOtherNum (23) to myNum myNum = myOtherNum; // myNum is now 23, instead of 15 printf("%d", myNum); *Or copy values to empty variables. *To declare more than one variable of the same type, use a comma-separated list: Example int x = 5, y = 6, z = 50; * You can also assign the same value to multiple variables of the same type: Example int x, y, z; x = y = z = 50;
  • 13.
    C Variable Names(Identifiers) * All C variables must be identified with unique names. * These unique names are called identifiers. * Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume). Note: It is recommended to use descriptive names in order to create understandable and maintainable code: Example // Good variable name int minutesPerHour = 60; // OK, but not so easy to understand what m actually is int m = 60; The general rules for naming variables are: 1. Names can contain letters, digits and underscores 2. Names must begin with a letter or an underscore (_) 3. Names are case-sensitive (myVar and myvar are different variables) 4. Names cannot contain whitespaces or special characters like !, #, %, etc. 5. Reserved words (such as int) cannot be used as names
  • 14.
    Data types inc * The data type specifies the size and type of information the variable will store. * Each data type requires different amounts of memory and has some specific operations which can be performed over it.
  • 15.
    Basic Format Specifiers Thereare different format specifiers for each data type. Here are some of them:
  • 16.
    Types of datatype Types of data type
  • 17.
    C Type Conversion Sometimes,you have to convert the value of one data type to another type. This is known as type conversion. For example, if you try to divide two integers, 5 by 2, you would expect the result to be 2.5. But since we are working with integers (and not floating-point values), the following example will just output 2: Example int x = 5; int y = 2; int sum = 5 / 2; printf("%d", sum); // Outputs 2 •To get the right result, you need to know how type conversion works. * There are two types of conversion in C: 1. Implicit Conversion (automatically) 2. Explicit Conversion (manually)
  • 18.
    Implicit Conversion * Implicitconversion is done automatically by the compiler when you assign a value of one type to another. For example, if you assign an int value to a float type: Example // Automatic conversion: int to float float myFloat = 9; printf("%f", myFloat); // 9.000000 Example // Automatic conversion: float to int int myInt = 9.99; printf("%d", myInt); // 9 •As another example, if you divide two integers: 5 by 2, you know that the sum is 2.5. • if you store the sum as an integer, the result will only display the number 2. Therefore, it would be better to store the sum as a float or a double, right? Example float sum = 5 / 2; printf("%f", sum); // 2.000000 * Why is the result 2.00000 and not 2.5? Well, it is because 5 and 2 are still integers in the division. In this case, you need to manually convert the integer values to floating-point values
  • 19.
    Explicit Conversion * Explicitconversion is done manually by placing the type in parentheses () in front of the value. * Considering our problem from the example above, we can now get the right result: Example // Manual conversion: int to float float sum = (float) 5 / 2; printf("%f", sum); // 2.500000 * You can also place the type in front of a variable: Example int num1 = 5; int num2 = 2; float sum = (float) num1 / num2; printf("%f", sum); // 2.500000 * decimal precision Output: 2.5
  • 20.
    C Constants * Ifyou don't want others (or yourself) to change existing variable values, you can use the const keyword. * This will declare the variable as "constant", which means unchangeable and read- only: Example const int myNum = 15; // myNum will always be 15 myNum = 10; // error: assignment of read-only variable 'myNum' You should always declare the variable as constant when you have values that are unlikely to change: Example const int minutesPerHour = 60; const float PI = 3.14; •When you declare a constant variable, it must be assigned with a value Another thing about constant variables, is that it is considered good practice to declare them with uppercase. It is not required, but useful for code readability and common for C programmers
  • 21.
    Keywords in C Keywordsare predefined or reserved words that have special meanings to the compiler. These are part of the syntax and cannot be used as identifiers in the program.
  • 22.
    Keywords(Cont) auto auto is thedefault storage class variable that is declared inside a function or a block. auto variables can only be accessed within the function/block they are declared. By default, auto variables have garbage values assigned to them. Automatic variables are also called local variables as they are local to a function. EX : auto int num; break and continue The break statement is used to terminate the innermost loop. It generally terminates a loop or a break statement. The continue statement skips to the next iteration of the loop.
  • 23.
    Keywords(Cont) switch, case, anddefault The switch statement in C is used as an alternate to the if-else ladder statement. For a single variable i.e, switch variable it allows us to execute multiple operations for different possible values of a single variable. char char keyword in C is used to declare a character variable in the C programming language. const The const keyword defines a variable who’s value cannot be changed. do The do statement is used to declare a do-while loop. A do-while loop is a loop that executes once, and then checks it’s condition to see if it should continue through the loop. After the first iteration, it will continue to execute the code while the condition is true.
  • 24.
    Keywords(Cont) double and float Thedoubles and floats are datatypes used to declare decimal type variables. They are similar, but doubles have 15 decimal digits, and floats only have 7. if-else The if-else statement is used to make decisions, where if a condition is true, then it will execute a block of code; if it isn’t true (else), then it will execute a different block of code. enum Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain. extern The extern keyword is used to declare a variable or a function that has an external linkage outside of the file declaration. for The “for” keyword is used to declare a for-loop. A for-loop is a loop that is specified to run a certain amount of times. goto The goto statement is used to transfer the control of the program to the given label. It is used to jump from anywhere to anywhere within a function. int int keyword is used in a type declaration to give a variable an integer type. In C, the integer variable must have a range of at least -32768 to +32767.
  • 25.
    Keywords(Cont) short, long, signed,and unsigned Different data types also have different ranges up to which they can store numbers. These ranges may vary from compiler to compiler. Below is a list of ranges along with the memory requirement and format specifiers on the 32-bit GCC compiler.
  • 26.
    Keywords(Cont) return The return statementreturns a value to where the function was called. sizeof sizeof is a keyword that gets the size of an expression, (variables, arrays, pointers, etc.) in bytes. register Register variables tell the compiler to store variables in the CPU register instead of memory. Frequently used variables are kept in the CPU registers for faster access. static The static keyword is used to create static variables. A static variable is not limited by a scope and can be used throughout the program. It’s value is preserved even after it’s scope. struct The struct keyword in C programming language is used to declare a structure. A structure is a list of variables, (they can be of different data types), which are grouped together under one data type. typedef The typedef keyword in C programming language is used to define a data type with a new name in the program. typedef keyword is used to make our code more readable.
  • 27.
    Keywords(Cont) union The union isa user-defined data type. All data members which are declared under the union keyword share the same memory location. void The void keyword means nothing i.e, NULL value. When the function return type is used as the void, the keyword void specifies that it has no return value. volatile The volatile keyword is used to create volatile objects. Objects which are declared volatile are omitted from optimization as their values can be changed by code outside the scope of the current code at any point in time.
  • 28.
    C Operators Operators areused to perform operations on variables and values. C divides the operators into the following groups: Arithmetic operators Assignment operators Comparison operators Logical operators Bitwise operators Arithmetic Operators Arithmetic operators are used to perform common mathematical operations
  • 29.
    C Operators(cont) Assignment Operators Assignmentoperators are used to assign values to variables. the assignment operator (=) to assign the value 10 to a variable called x: Example int x = 10;
  • 30.
    C Operators(cont) Comparison Operators Comparisonoperators are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions. The return value of a comparison is either 1 or 0, which means true (1) or false (0). These values are known as Boolean values, and you will learn more about them in the Booleans and If..Else chapter.
  • 31.
    C Operators(cont) Logical Operators Youcan also test for true or false values with logical operators. Logical operators are used to determine the logic between variables or values, by combining multiple conditions
  • 32.
    C Operators(cont) Bitwise Operatorsin C 1. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. 2. The | (bitwise OR) in C takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 if any of the two bits is 1. 3. The ^ (bitwise XOR) in C takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different. 4. The << (left shift) in C takes two numbers, the left shifts the bits of the first operand, and the second operand decides the number of places to shift. 5. The >> (right shift) in C takes two numbers, right shifts the bits of the first operand, and the second operand decides the number of places to shift. 6. The ~ (bitwise NOT) in C takes one number and inverts all bits of it.
  • 33.
    C User Input UserInput You have already learned that printf() is used to output values in C. To get user input, you can use the scanf() function: Example Output a number entered by the user: // Create an integer variable that will store the number we get from the user int myNum; // Ask the user to type a number printf("Type a number: n"); // Get and save the number the user types scanf("%d", &myNum); // Output the number the user typed printf("Your number is: %d", myNum); Multiple Inputs The scanf() function also allow multiple inputs (an integer and a character) Take String Input You can also get a string entered by the user. Ex: char firstName[30]; scanf("%s", firstName);
  • 34.
    C Booleans Booleans Very often,in programming, you will need a data type that can only have one of two values, like: YES / NO ON / OFF TRUE / FALSE * For this, C has a bool data type, which is known as booleans. * Booleans represent values that are either true or false. * In C, the bool type is not a built-in data type, like int or char. It was introduced in C99, and you must import the following header file to use it: #include <stdbool.h> * A boolean variable is declared with the bool keyword and can take the values true or false: EX: bool isProgrammingFun = true; bool isFishTasty = false; * Before trying to print the boolean variables, you should know that boolean values are returned as integers: 1 (or any other number that is not 0) represents true 0 represents false * * Therefore, you must use the %d format specifier to print a boolean value.
  • 35.
    Control flow statementsin Programming Control flow statements are fundamental components of programming languages that allow developers to control the order in which instructions are executed in a program
  • 36.
    Branching statements inC Branching Statements in C are those statements in C language that helps a programmer to control the flow of execution of the program according to the requirements. These Branching Statements are considered an essential aspect of the Programming Languages and are essentially used for executing the specific segments of code on basis of some conditions. Types of Branching Statements in C Branching statements are mainly categorized as follows. 1. Conditional Branching Statements 2. Unconditional Branching Statements
  • 37.
    Branching statements inC(cont) Conditional Branching Statements Conditional Branching Statements in C are used to execute the specific blocks of code on the basis of some condition (as per requirements). These type of Branching statements in C enables the programmers to execute the code only and only certain statements are met.
  • 38.
    Branching statements inC(cont) Unconditional Branching Statements in C Unconditional branching statements are used in C to change the normal flow of program execution. These statements allow programmers to jump to a specific point in their code regardless of any condition. There are the following types of unconditional branching statements in C.
  • 39.
  • 40.
    If Statement The ifstatement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e •if a certain condition is true then a block of statements is executed otherwise not. Syntax of if Statement if(condition) { // Statements to execute if // condition is true }
  • 41.
    If (Example) // Cprogram to illustrate If statement #include <stdio.h> int main() { int i = 10; if (i > 15) //condition is if “i” is grater than 15 if block is executed { printf("10 is greater than 15"); } printf("I am Not in if"); //if “if condition ” is false execute the Statement } Out put: I am Not in if
  • 42.
    Else Statement Use theelse statement to specify a block of code to be executed if the condition is false. Syntax if (condition) { // block of code to be executed if the condition is true } else { // block of code to be executed if the condition is false }
  • 43.
    Else Example // Cprogram to illustrate If statement #include <stdio.h> int main() { int i = 20; if (i < 15) // if condition is true below block will execute { printf("i is smaller than 15"); } else // condition is false execute the below code { printf("i is greater than 15"); } return 0; } Out put: i is greater than 15
  • 44.
    Nested if-else inC A nested if in C is an if statement that is the target of another if statement. Nested if statements mean an if statement inside another if statement. Yes, C allow us to nested if statements within if statements, i.e, we can place an if statement inside another if statement. Syntax of Nested if-else if (condition1) { // Executes when condition1 is true if (condition_2) { // statement 1 } else { // Statement 2 } } else { if (condition_3) { // statement 3 } else { // Statement 4 } } Flow Chart
  • 45.
    Nested if-else inC (EXP) // C program to illustrate nested-if statement #include <stdio.h> int main() { int i = 10; if (i == 10) { // First if statement if (i < 15) printf("i is smaller than 15n"); // Nested - if statement // Will only be executed if statement above // is true if (i < 12) printf("i is smaller than 12 toon"); else printf("i is greater than 15"); } else { if (i == 20) { // Nested - if statement // Will only be executed if statement above // is true if (i < 22) printf("i is smaller than 22 too n"); else printf("i is greater than 25"); } } return 0; } Out put: i is smaller than 15 i is smaller than 12 too
  • 46.
    if-else-if Ladder inC The if else if statements are used when the user has to decide among multiple options. The C if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed. if-else-if ladder is similar to the switch statement. Syntax of if-else-if Ladder if (condition) statement; else if (condition) statement; . . else statement;
  • 47.
    if-else-if Ladder inC EXP // C program to illustrate nested-if statement #include <stdio.h> int main() { int i = 20; if (i == 10) printf("i is 10"); else if (i == 15) printf("i is 15"); else if (i == 20) printf("i is 20"); else printf("i is not present"); } Out put: i is 20
  • 48.
    switch Statement inC The switch case statement is an alternative to the if else if ladder that can be used to execute the conditional code based on the value of the variable specified in the switch statement. The switch block consists of cases to be executed based on the value of the switch variable. Syntax of switch switch (expression) { case value1: statements; case value2: statements; .... .... .... default: statements; }
  • 49.
    switch Statement inC EXP // C Program to illustrate the use of switch statement #include <stdio.h> int main() { // variable to be used in switch statement int var = 2; // declaring switch cases switch (var) { case 1: printf("Case 1 is executed"); break; case 2: printf("Case 2 is executed"); break; default: printf("Default Case is executed"); break; } return 0; } Output: Case 2 is executed
  • 50.
    Conditional Operator inC The conditional operator is used to add conditional code in our program. It is similar to the if-else statement. It is also known as the ternary operator as it works on three operands. Syntax of Conditional Operator (condition) ? [true_statements] : [false_statements];
  • 51.
    Conditional Operator inC EXP // C Program to illustrate the use of conditional operator #include <stdio.h> // driver code int main() { int var; int flag = 0; // using conditional operator to assign the value to var // according to the value of flag var = flag == 0 ? 25 : -25; printf("Value of var when flag is 0: %dn", var); // changing the value of flag flag = 1; // again assigning the value to var using same statement var = flag == 0 ? 25 : -25; printf("Value of var when flag is NOT 0: %d", var); return 0; } Out Put: Value of var when flag is 0: 25 Value of var when flag is NOT 0: -25
  • 52.
    C – Loops Loopsin programming are used to repeat a block of code until the specified condition is met. A loop statement allows programmers to execute a statement or group of statements multiple times without repetition of code. There are mainly two types of loops in C Programming: 1. Entry Controlled loops: In Entry controlled loops the test condition is checked before entering the main body of the loop. For Loop and While Loop is Entry- controlled loops. 2. Exit Controlled loops: In Exit controlled loops the test condition is evaluated at the end of the loop body. The loop body will execute at least once, irrespective of whether the condition is true or false. do-while Loop is Exit Controlled loop.
  • 53.
    For loop •for loopin C programming is a repetition control structure that allows programmers to write a loop that will be executed a specific number of times. for loop enables programmers to perform n number of steps together in a single line. Syntax: for (initialize expression; test expression; update expression) { // // body of for loop // } 1. Initialization Expression: In this expression, we assign a loop variable or loop counter to some value. for example: int i=1; 2. Test Expression: In this expression, test conditions are performed. If the condition evaluates to true then the loop body will be executed and then an update of the loop variable is done. If the test expression becomes false then the control will exit from the loop. for example, i<=9; 3. Update Expression: After execution of the loop body loop variable is updated by some value it could be incremented, decremented, multiplied, or divided by any value. Flow chart
  • 54.
    For loop Exp //C program to illustrate for loop #include <stdio.h> // Driver code int main() { int i = 0; for (i = 1; i <= 10; i++) { printf( "Hello Worldn"); } return 0; } Output: Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World
  • 55.
    While Loop While loopdoes not depend upon the number of iterations. In for loop the number of iterations was previously known to us but in the While loop, the execution is terminated on the basis of the test condition. If the test condition will become false then it will break from the while loop else body will be executed. Syntax: initialization_expression; while (test_expression) { // body of the while loop update_expression; } Flow Chart
  • 56.
    While Loop Exp //C program to illustrate // while loop #include <stdio.h> // Driver code int main() { // Initialization expression int i = 2; // Test expression while(i < 10) { // loop body printf( "Hello Worldn"); // update expression i++; } return 0; } Output Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World
  • 57.
    do-while Loop The do-whileloop is similar to a while loop but the only difference lies in the do-while loop test condition which is tested at the end of the body. In the do-while loop, the loop body will execute at least once irrespective of the test condition. Syntax: initialization_expression; Do { // body of do-while loop update_expression; } while (test_expression); Flow Chart
  • 58.
    do-while Loop Exp //C program to illustrate // do-while loop #include <stdio.h> // Driver code int main() { // Initialization expression int i = 2; do { // loop body printf( "Hello Worldn"); // Update expression i++; // Test expression } while (i < 1); return 0; } Output: Hello World
  • 59.
    Infinite Loop An infiniteloop is executed when the test expression never becomes false and the body of the loop is executed repeatedly. A program is stuck in an Infinite loop when the condition is always true. Mostly this is an error that can be resolved by using Loop Control statements. // C program to demonstrate infinite // loops using for loop #include <stdio.h> // Driver code int main () { int i; // This is an infinite for loop // as the condition expression // is blank for ( ; ; ) { printf("This loop will run forever.n"); } return 0; } Output This loop will run forever. This loop will run forever. This loop will run forever . ...
  • 60.
    Continue Statement inC The C continue statement resets program control to the beginning of the loop when encountered. As a result, the current iteration of the loop gets skipped and the control moves on to the next iteration. Statements after the continue statement in the loop are not executed. Syntax of continue in C The syntax of continue is just the continue keyword placed wherever we want in the loop body. continue; Use of continue in C The continue statement in C can be used in any kind of loop to skip the current iteration. In C, we can use it in the following types of loops: 1. Single Loops 2. Nested Loops Using continue in infinite loops is not useful as skipping the current iteration won’t make a difference when the number of iterations is infinite.
  • 61.
    Continue Statement inC Exp The working of the continue statement is as follows: STEP 1: The loop’s execution starts after the loop condition is evaluated to be true. STEP 2: The condition of the continue statement will be evaluated. STEP 3A: If the condition is false, the normal execution will continue. STEP 3B: If the condition is true, the program control will jump to the start of the loop and all the statements below the continue will be skipped. STEP 4: Steps 1 to 4 will be repeated till the end of the loop.
  • 62.
    Continue Statement inC Exp #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; } Output 1 2 3 4 6 7 8 9 10
  • 63.
    C break statement Thebreak is a keyword in C which is used to bring the program control out of the loop. The break statement is used inside loops or switch statement. The break statement breaks the loop one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to outer loops. The break statement in C can be used in the following two scenarios: 1. With switch case 2. With loop Syntax: //loop or switch case break;
  • 64.
    C break statementExp Example: #include<stdio.h> #include<stdlib.h> void main () { int i; for(i = 0; i<10; i++) { printf("%d ",i); if(i == 5) { break; } } printf("came outside of loop i = %d",i); } Output 0 1 2 3 4 5 came outside of loop i = 5
  • 65.
    C goto statement Thegoto statement is known as jump statement in C. As the name suggests, goto is used to transfer the program control to a predefined label. The goto statment can be used to repeat some part of the code for a particular condition. It can also be used to break the multiple loops which can't be done by using a single break statement. However, using goto is avoided these days since it makes the program less readable and complecated. Syntax: label: //some part of the code; goto label;
  • 66.
    C goto statementExp Example: #include <stdio.h> int main() { int num,i=1; printf("Enter the number whose table you want to print?"); scanf("%d",&num); table: printf("%d x %d = %dn",num,i,num*i); i++; if(i<=10) goto table; } Out Put: Enter the number whose table you want to print?10 10 x 1 = 10 10 x 2 = 20 10 x 3 = 30 10 x 4 = 40 10 x 5 = 50 10 x 6 = 60 10 x 7 = 70 10 x 8 = 80 10 x 9 = 90 10 x 10 = 100