C Programming Code Examples
Learn C Language
Nested Loop Statement in C Programming Language
Nested Loop Statement in C
C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements inside another loop. Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example, you can define 'while' loop inside a 'for' loop.
A loop inside another loop is called a nested loop. The depth of nested loop depends on the complexity of a problem. We can have any number of nested loops as required. Consider a nested loop where the outer loop runs n times and consists of another loop inside it. The inner loop runs m times. Then, the total number of times the inner loop runs during the program execution is n*m.
Syntax for Nested Loop Statement in C
Outer_loop
{
Inner_loop
{
// inner loop statements.
}
// outer loop statements.
}
/* nested loop statement in C language */
// C Program to print all prime factors
// of a number using nested loop
#include <math.h>
#include <stdio.h>
// A function to print all prime factors of a given number n
void primeFactors(int n)
{
// Print the number of 2s that divide n
while (n % 2 == 0) {
printf("%d ", 2);
n = n / 2;
}
// n must be odd at this point. So we can skip
// one element (Note i = i +2)
for (int i = 3; i <= sqrt(n); i = i + 2) {
// While i divides n, print i and divide n
while (n % i == 0) {
printf("%d ", i);
n = n / i;
}
}
// This condition is to handle the case when n
// is a prime number greater than 2
if (n > 2)
printf("%d ", n);
}
/* Driver program to test above function */
int main()
{
int n = 315;
primeFactors(n);
return 0;
}
Take the height of a person as input and store it in the variable height. If the variable height is lesser than 150 cm, then print the output as "Dwarf". If the variable height is lesser than...
C Program to check Whether a given string is palindrome or not 'using recursion'. Program, with recursion, determines the entered string is a 'palindrome' or not. Palindrome is a word,
C Define the union named number with two variables j1 and j2. Define the union variable x. Take the value of two variables using dot operator(i.e. x.j1, x.j2) as input. Print values
This c language program takes any year as input and prints its last two digits. Take any year as input. Divide the input by 100 and obtain its remainder. The remainder got is
C Program take the octal number as input and store it in the variable octal. Initialize the variables decimal and j to zero. Obtain the remainder and quotient of the octal number.