Module 1
Module 1
Structure of a C Program
A C program is divided into different sections. There are six main sections to a basic c
program. The six sections are,
Documentation Section
The documentation section is the part of the program where the programmer gives the
details associated with the program. He usually gives the name of the program, the details
of the author and other details like the time of coding and description. It gives anyone
reading the code the overview of the code.
/* File Name: areaofcircle.c
Author: Abhijith
date: 06/05/2021
description: a program to calculate area of circle
user enters the radius
*/
Link Section
This part of the code is used to declare all the header files that will be used in the program.
This leads to the compiler being told to include the header files to the source program and
link the system libraries.
#include<stdio.h>
Definition Section
In this section, we define different constants. The keyword define is used in this part.
#define PI 3.14
1. Integer constants
An integer constant is a numeric constant (associated with number) without any fractional
or exponential part. There are three types of integer constants in C programming:
● decimal constant(base 10)
● octal constant(base 8)
● hexadecimal constant(base 16)
For example:
Decimal constants: 0, -9, 22 etc
Octal constants: 021, 077, 033 etc
Hexadecimal constants: 0x7f, 0x2a, 0x521 etc
In C programming, octal constant starts with a 0 and hexadecimal constant starts with a
0x(0X).
Unsigned integer constants may exceed the magnitude of ordinary integer constants by
approximately a factor of 2, though they may not be negative. An unsigned integer constant
can be identified by appending the letter U (either upper- or lowercase) to the end of the
constant.
Long integer constants may exceed the magnitude of ordinary integer constants, but require
more memory within the computer. With some computers (andor some compilers), a long
integer constant will automatically be generated simply by specifying a quantity that
exceeds the normal maximum value. It is always possible, however, to create a long integer
constant by appending the letter L (either upper- or lowercase) to the end of the constant.
An unsigned long integer may be specified by appending the letters UL to the end of the
constant. The
letters may be written in either upper- or lowercase. However, the U must precede the L.
Several unsigned and long integer constants are shown below
Constant Number System
50000U decimal (unsigned)
123456789L decimal (long)
123456789UL octal (long)
077777711 octal (unsigned)
0X50000U hexadecimal (unsigned)
0XFFFFFUL hexadecimal (unsigned long)
2. Floating-point constants
Afloating-point constant is a base- 10 number that contains either a decimal point or an
exponent (or both).
Several valid floating-point constants are shown below.
0. 1 . 0.2 827.602
50000. 0.000743 12.3 315.0066
2E-8 0.006e-3 1.6667E+8 .12121212e12
The interpretation of a floating-point constant with an exponent is essentially the same as
scientific notation, except that the base 10 is replaced by the letter E (or e). Thus, the
number 1.2 x 10^-3 would be written as 1 .2E-3 or 1 .2e-3. This is equivalent to 0.12e-2, or
12e-4, etc.
The quantity 3 x 10^5can be represented in C by any of the following floating-point constants.
300000. 3e5 3e+5 3E5 3.Oe+
.3e6 0.3E6 30E4 30. E+4 300e3
Similarly, the quantity 5.026 x 10^-l7 can be represented by any of the following loating-point
constants. 5.026E-17 .5026e-16 50.26e-18 .0005026E-13
Floating-point constants are normally represented as double-precision quantities in C.
Hence, each floating-point constant will typically occupy 2 words (8 bytes) of memory.
Some versions of C permit the specification of a “single-precision,” floating-point constant,
by appending the letter F (in either upper- or lowercase) to the end of the constant (e.g.,
3E5F). Similarly, some versions of C permit the specification of a “long” floating-point
constant, by appending the letter L (upper- or lowercase) to the end of the constant
(e.g.,0.123456789E-33L).
3. Character constants
A character constant is a constant which uses single quotation around characters.A
character constant is a single character, enclosed in apostrophes (i.e., single quotation
marks). For example: 'a', 'l', 'm', 'F', ' '( blank space)
Most computers, and virtually all personal computers, make use of the ASCII (i.e., American
Standard Code for Information Interchange) character set, in which each individual
character is numerically encoded with its own unique 7-bit combination (hence a total of 2'
= 128 different characters).
Example:
Character ASCII value
'A' 65
'a' 97
'0' 48
Escape Sequences
Sometimes, it is necessary to use characters which cannot be typed or has special meaning
in C programming. For example: newline(enter), tab, question mark etc. In order to use
these characters, escape sequence is used.
For example: \n is used for newline. The backslash ( \ ) causes "escape" from the normal
way the characters are interpreted by the compiler.
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\? Question mark
\0 Null character
4. String constants
A string constant consists of any number of consecutive characters (including none),
enclosed in (double) quotation marks.
For example:
"good" //string constant
"" //null string constant
" " //string constant of white spaces
"x" //string constant having single character
"Earth is round\n" //prints string with newline
The following string constant includes three special characters that are represented by their
corresponding escape sequences.
" \ t T o continue, press the \"RETURN\" key\n"
The special characters are \t (horizontal tab), \ " (double quotation marks, which appears
twice), and \ n (newline).
The compiler automatically places a null character (\0) at the end of every string constant,
as the last character within the string (before the closing double quotation mark). This
character is not visible when the string is displayed. However, we can easily examine the
individual characters within a string, and test to see whether or not each character is a null
character Thus, the end of every string can be readily identified. This is very helpful if the
string is scanned on a character-by-character basis, as is required in many applications.
Also, in many situations this end-of-string designation eliminates the need to specify a
maximum string length.
5. Enumeration constants
Keyword enum is used to define enumeration types.
For example:
enum color {yellow, green, black, white};
Here, color is a variable and yellow, green, black and white are the enumeration constants
having value 0, 1, 2 and 3 respectively. If we do not explicitly assign values to enum names,
the compiler by default assigns values starting from 0.
Symbolic Constants
A symbolic constant is a name that substitutes for a sequence of characters. The
characters may represent a numeric constant, a character constant or a string constant.
Thus, a symbolic constant allows a name to appear in place of a numeric constant, a
character constant or a string.
When a program is compiled, each occurrence of a symbolic constant is replaced by its
corresponding character sequence.Symbolic constants are usually defined at the beginning
of a program. The symbolic constants may then appear later in the program in place of the
numeric constants, character constants, etc. that the symbolic constants represent.
A symbolic constant is defined by writing
#define name text
where name represents a symbolic name, typically written in uppercase letters, and text
represents the sequence of characters that is associated with the symbolic name. Note that
text does not end with a semicolon, since a symbolic constant definition is not a true C
statement. Moreover, if text were to end with a semicolon, this semicolon would be treated
as though it were a part of the numeric constant, character constant or string constant that
is substituted for the symbolic name.
EXAMPLE
#define P I 3.141593
Now suppose that the program contains the statement
area = PI * radius * radius;
During the compilation process, each occurrence of a symbolic constant will be replaced by
its corresponding text. Thus,the above statement will become
area = 3.141593 * radius * radius;
C Identifiers
Identifier refers to name given to entities such as variables, functions, structures etc.
Identifier must be unique. They are created to give unique name to a entity to identify it
during the execution of the program. For example:
int money;
double accountBalance;
Here, money and accountBalance are identifiers.
Rules for writing an identifier
● A valid identifier can have letters (both uppercase and lowercase letters), digits and
underscores.
● The first letter of an identifier should be either a letter or an underscore. However, it
is discouraged to start an identifier name with an underscore.
● There is no rule on length of an identifier. However, the first 31 characters of
identifiers are discriminated by the compiler.
● Identifiers are case sensitive ie; X is different from x.
● Keywords should not be used as identifiers.
The following are valid identifiers
x y12 sum_1 _temperature names area tax_rate TABLE
The following names are not valid identifiers for the reasons stated.
2csbmec The first character must be a letter.
mec#cs2b Illegal character #.
order-no Illegal character (-).
mec cs2b Illegal character (blank space)
Preprocessor Directives
In a C program, all lines that start with # are processed by preprocessor which is a special
program invoked by the compiler. In a very basic term, preprocessor takes a C program and
produces another C program without any #.
There are 4 main types of preprocessor directives:
● Macros
● File Inclusion
● Conditional Compilation
● Other directives
All preprocessor commands begin with a hash symbol (#). It must be the first nonblank
character, and for readability, a preprocessor directive should begin in the first column. The
following section lists down all the important preprocessor directives
1 #define
Substitutes a preprocessor macro.
2 #include
Inserts a particular header from another file.
3 #undef
Undefines a preprocessor macro.
4 #ifdef
Returns true if this macro is defined.
5 #ifndef
Returns true if this macro is not defined.
6 #if
Tests if a compile time condition is true.
7 #else
The alternative for #if.
8 #elif
#else and #if in one statement.
9 #endif
Ends preprocessor conditional.
10 #error
Prints error message on stderr.
11 #pragma
Issues special commands to the compiler, using a standardized method.
1) When we use include directive, the contents of included header file (after preprocessing)
are copied to the current file.
Angular brackets < and > instruct the preprocessor to look in the standard folder where all
header files are held. Double quotes “ and “ instruct the preprocessor to look into the
current folder and if the file is not present in current folder, then in standard folder of all
header files.
Eg:
#include <math.h>
#include "yourheaderfile.h"
2) When we use define for a constant, the preprocessor produces a C program where the
defined constant is searched and matching tokens are replaced with the given expression.
For example in the following program max is defined as 100.
#include<stdio.h>
#define max 100
int main()
{
printf("max is %d", max);
return 0;
}
Output:
max is 100
A macro can also be defined using #define.A macro is a segment of code which is replaced
by the value of macro. Macro is defined by #define directive
#include <stdio.h>
#define MULTIPLY(a, b) a*b
int main()
{
printf("%d", MULTIPLY(2, 3));
return 0;
}
We have to include “stdio.h” file as shown in below to make use of these printf() and scanf()
library functions in C program.
#include <stdio.h>
printf() function in C
In C programming language, printf() function is used to print the “character, string, float,
integer, octal and hexadecimal values” onto the output screen.
Here’s a quick summary of the available printf format specifiers:
%c character
%d decimal (integer) number (base 10)
%ld Long integer
%e exponential floating-point number
%f floating-point number
%lf double number
%i integer (base 10)
%o octal number (base 8)
%s a string of characters
%u unsigned decimal (integer) number
%x number in hexadecimal (base 16)
%% print a percent sign
\% print a percent sign
\a Audible alert
\b Backspace
\f Form feed
\r Carriage return
\? Question mark
\n New Line
\t Tab
\v Vertical tab
\\ Back slash
\0 ASCII null character
\’ Single quotes
\”” Double quotes
\o Octal Constant
\x Hexadecimal constant
scanf() function in C language:
In C programming language, scanf() function is used to read character, string, numeric data
from keyboard.
The examples show various syntax for reading different data types
int x; scanf(“%i”,&x); or scanf(“%d”,&x);
float x;scanf(“%f”,&x);
char x; scanf(“%c”,&c);
long int x; scanf(“%ld”,&x);
char str[100];scanf(“%s”,str);
● The symbols which are used to perform logical and mathematical operations in a C
program are called C operators.
● These C operators join individual constants and variables to form expressions.
● Operators, functions, constants and variables are combined together to form
expressions.
● Consider the expression A + B * 5. where, +, * are operators, A, B are variables, 5 is
constant and A + B * 5 is an expression.
Types of C operators:
C language offers many types of operators. They are,
Types of Operators Description
Arithmetic operators These are used to perform mathematical calculations like addition,
subtraction, multiplication, division and modulus
Assignmentoperators These are used to assign the values for the variables in C programs.
Relational operators These operators are used to compare the value of two variables.
Logical operators These operators are used to perform logical operations on the given two
variables.
Bit wise operators These operators are used to perform bit operations on given two
variables.
Conditional (ternary) Conditional operators return one value if condition is true and returns
operators another value is condition is false.
Increment/decrement These operators are used to either increase or decrease the value of
operators the variable by one.
Special operators &, *, sizeof( ) and ternary operators.
Arithmetic Operators in C:
C Arithmetic operators are used to perform mathematical calculations like addition, subtraction,
multiplication, division and modulus in C programs.
Arithmetic Operators/Operation Example
+ (Addition) A+B
– (Subtraction) A-B
* (multiplication) A*B
/ (Division) A/B
% (Modulus) A%B
Assignment operators in C:
● In C programs, values for the variables are assigned using assignment operators.
● For example, if the value “10” is to be assigned for the variable “sum”, it can be assigned
as “sum = 10;”
● There are 2 categories of assignment operators in C language. They are,
1.Simple assignment operator ( Example: = )
2. Compound assignment operators ( Example:+=, -=, *=, /=, %=, &=, ^= )
Operators Example/Description
= sum = 10;
10 is assigned to variable sum
+= sum += 10;
This is same as sum = sum + 10
-= sum -= 10;
This is same as sum = sum – 10
*= sum *= 10;
This is same as sum = sum * 10
/= sum /= 10;
This is same as sum = sum / 10
%= sum %= 10;
This is same as sum = sum % 10
&= sum&=10;
This is same as sum = sum & 10
^= sum ^= 10;
This is same as sum = sum ^ 10
Relational operators in C:
Relational operators are used to find the relation between two variables. i.e. to compare the
values of two variables in a C program.
Operators Example/Description
> x > y (x is greater than y)
< x < y (x is less than y)
>= x >= y (x is greater than or equal to y)
<= x <= y (x is less than or equal to y)
== x == y (x is equal to y)
!= x != y (x is not equal to y)
Logical operators in C:
● These operators are used to perform logical operations on the given expressions.
● There are 3 logical operators in C language. They are, logical AND (&&), logical OR (||)
and logical NOT (!).
Operators Example/Description
&& (logical AND) (x>5)&&(y<5)
It returns true when both conditions are true
|| (logical OR) (x>=10)||(y>=10)
It returns true when at-least one of the condition is true
! (logical NOT) !((x>5)&&(y<5))
It reverses the state of the operand “((x>5) && (y<5))”
If “((x>5) && (y<5))” is true, logical NOT operator makes it false
● These operators are used to perform bit operations. Decimal values are converted into
binary values which are the sequence of bits and bit wise operators work on these bits.
● Conditional operators return one value if condition is true and returns another value is
condition is false.
● This operator is also called as ternary operator.
#include <stdio.h>
int main() {
int first_check = 1; // Example value (1 means true, 0 means false)
int second_check = 0; // Example value (1 means true, 0 means false)
return 0;
}
Increment/decrement operators in C:
● Increment operators are used to increase the value of the variable by one and
decrement operators are used to decrease the value of the variable by one in C
programs.
● Syntax:
Increment operator: ++var_name; (or) var_name++;
Decrement operator: – -var_name; (or) var_name – -;
● Example:
Increment operator :++ i ; i ++ ;
Decrement operator : – – i ; i – – ;
Special Operators in C:
Below are some of the special operators that the C programming language offers.
Operators Description
& This is used to get the address of the variable.
Example : &a will give address of a.
* This is used as pointer to a variable.
Example : * a where, * is pointer to the variable a.
sizeof () This gives the size of the variable.
Example : sizeof (char) will give us 1.
Operator Precedence:
Operator precedence determines the grouping of terms in an expression and decides how an
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.
() Function call
[] Array subscripting
* Indirection (dereference)
& Address-of
sizeof Size-of[note 1]
12 || Logical OR
14 = Simple assignment
15 , Comma Left-to-right
Example:
#include <stdio.h>
main()
{
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
printf("Value of (a + b) * c / d is :%d\n", e );
e = ((a + b) * c) / d; // (30 * 15 ) / 5
printf("Value of ((a + b) * c) / d is :%d\n" , e );
e = (a + b) * (c / d); // (30) * (15/5)
printf("Value of (a + b) * (c / d) is :%d\n", e );
e = a + (b * c) / d; // 20 + (150/5)
printf("Value of a + (b * c) / d is :%d\n" , e );
return 0;
}
Output:
Value of (a + b) * c / d is :90
Value of ((a + b) * c) / d is :90
Value of (a + b) * (c / d) is :90
Value of a + (b * c) / d is :50
Output:
Enter the three numbers.... !
235
Largest=5
Bitwise Operators in C
Bit level operators make C useful for many low level applications. Bitwise operations allow
one to read and manipulate bits in variables of certain types. The bit wise operators only
work on int and char types. The following are the bitwise operators in C
Operator Description
~ Bitwise Complement
<< Bitwise Shift Left
>> Bitwise Shift Right
& Bitwise AND
^ Bitwise EX-OR
| Bitwise OR
Bitwise operations helps to work on Boolean variable, which needs only one bit.Set
membership can be represented with Boolean variables ( 1 means element in the set 0
means not in the set) and the Bitwise-AND can be used to implement set-intersection and
Bitwise-OR to implement set union.
The bitwise AND(&) is true only if both bits are set. The bitwise OR(|) is false only when both
the bits are false. The bitwise EX-OR operation returns 1 if the input bits are different.
The following chart defines these bitwise binary operations
Variable Decimal B3 B2 B1 B0
Equivalent
x 12 1 1 0 0
y 10 1 0 1 0
x&y 8 1 0 0 0
x|y 14 1 1 1 0
x^y 6 0 1 1 0
Bitwise NOT operation is the unary operator which flips the bits. It is also known as 1’s
complement operator. This changes each 1 to 0 and 0 to 1.
Variable Decimal B3 B2 B1 B0
Equivalent
x 12 1 1 0 0
~x 3 0 0 1 1
Bitwise SHIFT operators << and >> perform left and right shifts of their left operand by the
number of bit positions given by the right operand, which must be non negative.
When we shift left , the most significant bits are lost and the vacated least significant bits
are zero. Similarly when we shift right least significant bits are lost and the most significant
bits become zero.
Eg:
int x=5 // 0000 0000 0000 0101
y=x<<2; // x is shifted left two times and the result is stored in y.
so y become 20 //0000 0000 0001 0100
z=x>>2;// x is shifted right two times and the result is stored in z
so z become 1 // 0000 0000 0000 0001
Control Statements in C
Control statements enable us to specify the flow of program control; ie, the order in which
the instructions in a program must be executed. They make it possible to make decisions,
to perform tasks repeatedly or to jump from one section of code to another.
There are four types of control statements in C:
1.Decision making statements
2.Selection statements
3.Iteration statements
4.Jump statements
The following program checks whether the entered number is positive or negative.
#include<stdio.h>
int main( )
{
int a;
printf("n Enter a number:");
scanf("%d",&a);
if(a>0)
{
printf("n The number %d is positive.",a);
}
else
{
printf("The number %d is negative.",a);
}
return 0;
}
3.Iteration Statement(loops)
Loops are used in programming to repeat a specific block until some end condition is met.
There are three loops in C programming:
for loop
while loop
do...while loop
for Loop
The syntax of for loop is:
for (initializationStatement; testExpression; updateStatement)
{
// statements
}
The initialization statement is executed only once.
Then, the test expression is evaluated. If the test expression is false (0), for loop is
terminated. But if the test expression is true (nonzero), statements inside the body of for
loop is executed and the update expression is updated.
This process repeats until the test expression is false.
The for loop is commonly used when the number of iterations is known.
Example: for loop// Program to calculate the sum of first n natural numbers
// Positive integers 1,2,3...n are known as natural numbers
#include <stdio.h>
int main()
{
int num, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d",&num);
// for loop terminates when n is less than count
for(count = 1; count <= num; ++count)
{
sum+= count;
}
printf("Sum= %d", sum);
return 0;
}
while loop
The syntax of a while loop is:
while (testExpression)
{
//codes
}
where, testExpression checks the condition is true or false before each loop.The while loop
evaluates the test expression.If the test expression is true (nonzero), codes inside the body
of while loop are executed. The test expression is evaluated again. The process goes on
until the test expression is false.When the test expression is false, the while loop is
terminated.
do...while loop
The do..while loop is similar to the while loop with one important difference. The body of
do...while loop is executed once, before checking the test expression. Hence, the do...while
loop is executed at least once.
Syntax: do...while loop
do
{
// codes
}
while (testExpression);
The code block (loop body) inside the braces is executed once.Then, the test expression is
evaluated. If the test expression is true, the loop body is executed again. This process goes
on until the test expression is evaluated to 0 (false). When the test expression is false
(nonzero), the do...while loop is terminated.
// Program to add numbers until user enters zero
#include <stdio.h>
int main()
{
double number, sum = 0;
//loop body is executed at least once
do
{
printf("Enter a number: ");
scanf("%lf",&number);
sum+= number;
}
while(number!= 0.0);
printf("Sum= %.2lf",sum);
return 0;
}
4.Jump statements
These statements cause the normal program control to jump to a different point. Normal jump
statements are.
break
continue
goto
It is sometimes desirable to skip some statements inside the loop or terminate the loop
immediately without checking the test expression.In such cases, break and continue
statements are used.
break Statement
The break statement terminates the loop (for, while and do...while loop) immediately when it
is encountered. The break statement is used with decision making statement such as
switch
Example : break statement
// Program to calculate the sum of maximum of 10 numbers
// Calculates sum until user enters positive number
# include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;
for(i=1;i <= 10; ++i)
{
printf("Entera n%d: ",i);
scanf("%lf",&number);
//If user enters negative number, loop is terminated
if(number< 0.0)
{
break;
}
sum+= number; // sum = sum + number;
}
printf("Sum= %.2lf",sum);
return 0;
}
This program calculates the sum of maximum of 10 numbers. It's because, when the user enters
negative number, the break statement is executed and loop is terminated.
In C programming, break statement is also used with switch...case statement.
continue Statement
The continue statement skips some statements inside the loop. The continue statement is
used with decision making statement such as if...else.
Example : continue statement
// Program to calculate sum of maximum of 10 numbers
// Negative numbers are skipped from calculation
# include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;
for(i=1;i <= 10; ++i)
{
printf("Enter a n%d: ",i);
scanf("%lf",&number);
//If user enters negative number, loop is terminated
if(number< 0.0)
{
continue;
}
sum+= number; // sum = sum + number;
}
printf("Sum= %.2lf",sum);
return 0;
}
goto
The goto statement is used to alter the normal sequence of a C program.
Syntax of goto statement
goto label;
... .. ...
... .. ...
... .. ...
label:
statement;
The label is an identifier. When goto statement is encountered, control of the program
jumps to label: and starts executing the code.
Nesting of loops in C
We can write one loop inside another loop.A loop within another loop is called a nested
loop.
In C programming, nested loops are loops that are placed inside another loop. This allows
you to repeat a set of instructions multiple times, and inside each iteration of the outer loop,
the inner loop completes its full iteration. Nested loops are useful when you need to
perform repetitive tasks within repetitive tasks.
The following is the syntax of writing one for loop inside another for loop.There is no rule
that a loop must be nested inside its own type. In fact, there can be any type of loop nested
inside any type and to any level. Each inner (nested) loop must be completely embedded
within an outer loop, the loops cannot overlap.Here for each iteration of the outer loop, the
inner loop keep executing completely.
Nesting of for loop
for ( initialization; condition; increment )
{
for ( initialization; condition; increment )
{ // statement of inside loop
}
// statement of outer loop
}
Example:
#include <stdio.h>
int main()
{
int i,j;
for(i=0;i<5;i++)
{
for(j=0;j<10;j++)
{
printf("* ");
}
printf("\n");
}
}
Output:
**********
**********
**********
**********
**********
Note: The outer loop executes 5 times.The inner loop executes 10 times and print 10 '*'
each time.
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");
}
Output:n=3
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
***
***
***
***
***
***
In this example, the outermost loop controls the layers, the middle loop controls the rows
within each layer, and the innermost loop controls the columns within each row. The
program prints a block of stars for each layer, with each block containing three rows and
three columns.
Remember that the indentation in the code helps to visualize the structure of the nested
loops. When working with nested loops, it's crucial to keep track of the loop indices and
their ranges to achieve the desired pattern or behavior.
Example programs
#include <stdio.h>
main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("* ");
}
printf("\n");
}
}
o/p
*
**
***
****
*****
Here the inner for loop executes i times.when i=1 it execute 1 time and prints one *.when
i=2 it executes 2 times and it print * * . The outer loop repeats 5 times.
int n,i;
for(n=2;n<=10;n++)
{
printf("Multiplication table of %d\n",n);
for(i=1;i<=15;i++)
{printf("%2d * %2d = %2d\n",i,n,i*n);
}
}
}
Note: here the inner loop is used to print the multiplication table of a number upto 15 and
the outer loop will select the number from 2 -10.
int i,n,f,dig,sum=0,t;
printf("Enter the number:");
scanf("%d",&n);
t=n;
while(n!=0)
{
dig=n%10;
n=n/10;
f=1;
for(i=2;i<=dig;i++)
f=f*i;
sum=sum+f;
}
if(t==sum)
printf("Strong number\n");
else
printf("Not a Strong number\n");
}
Write a C program to check whether the given number is Armstrong number or not. [Hint:
An Armstrong number is a number with the sum of digits raised to the power of number of
digits, returns the number. ( university question)
Example: 153 = 1^3 + 5^3+ 3^3=1+125+27=153
9474=9^4 + 4^4 + 7^4 + 4^4 = 6561 + 256 + 2401 + 256=9474
#include <stdio.h>
#include <math.h>
int main() {
int num, original, remainder, n = 0;
double result = 0.0;
printf("Enter a number: ");
scanf("%d", &num);
original = num;
// Count number of digits
int temp = num;
while (temp != 0) {
temp /= 10;
n++;
}
// Compute sum of digits raised to the power n
temp = num;
while (temp != 0) {
remainder = temp % 10;
result += pow(remainder, n);
temp /= 10;
}
// Check if it's an Armstrong number
if ((int)result == original)
printf("%d is an Armstrong number.\n", original);
else
printf("%d is not an Armstrong number.\n", original);
return 0;
}
The following program will find out all prime numbers less than 100
#include <stdio.h>
int main ()
{ /* local variable definition */
int i, j;
for(i = 2; i<100; i++)
{
for(j = 2; j <= (i/j); j++)
{if(i%j==0) break;} // if factor found, not prime
if(j > (i/j)) printf("%d is prime\n", i);
}
return 0;
}
Note:Nested loops are widely used for matrix processing( reading, printing, matrix
arithmetic etc)