C Tutorial

C Tutorial C Language Environment Setup Execution flow of C program C printf and Scanf C Data type C Token Variable in C Operators in C Comments in C Escape Sequence in C C – Storage Classes C Decision control statement Loop Statement in C Break, continue and goto statement in C Type Casting in C Function in C Recursion in C String in C C Array Pointer in C Dynamic memory allocation C –Structure Nested Structure in C Union in C File Handling in C C pre-processor Static Function In C Sizeof In C Selection Sort In C Scope Of Variables In C Runtime Vs Compile Time In C Random Access Lseek In C Queue Implementation In C Pseudo Code In C Prototype In C Pointer To Pointer In C Pointer Arithmetic In C Passing Array To Function In C Null Character In C Merge Sort In C Macros In C Library Functions In C Memory Leak In C Int In C Goto And Labels In C Fibonacci Series In C Fflush In C Derived Data Types In C Data Types In C Const Vs Volatile In C Character Set In C Character Class Tests In C Calloc In C C Pointers Arrays In C Include In C Clrscr In C C Vs Java String Literals In C Types Of Pointers In C Variables In C Volatile In C Why C Is A Middle Level Language Infix To Postfix Program In C Ceil function in C LCM of two numbers in C Quick sort in C Static in C function pointer as argument in C Top Array Keywords in C Add two numbers using the function in C Armstrong program in C using function Array, Declaring Arrays and Array Initialization Limitations of Inline Function in C Merge and Merge sort with example in C Do-While Loop in C For Loop in C While-Loop in C Difference between while and do-while loop in C Array Of Structures in C Data Structures And Algorithms in C Types Of Structures In C How to Avoid Structure Padding in C Use of Structure in C Do WHILE LOOP in C Programming Examples For Loop in C Programming Examples Entry Control Loop in C Exit control loop in C Infinite loop in C Nested loop in C pow() function in C String Handling functions in C Prime Number code in C Factorial Program in C using For Loop Factorial Program in C Using While Loop Fibonacci Series in C Using For Loop Fibonacci series in C using while loop Prime Number Program in C using for Loop While Loop in C programming examples Built-in functions in C Assert() Function C vs Java Strings Call Back Function in Embedded C Else If Ladder fgets() function Ftell() Function getc() function getch() function gets() function Heap Sort Nested if-else statement Pi() Function Positioning of file Write() function abs() function in C Attributes in C C program to find factorial of a number using Recursion Ferror() in c fopen() function in C Fibonacci series program in C using Recursion Formatted Input and output function in C Snake Game in C User Defined Functions in C Beep() function in C Cbrt() function in C Hook() function in C Isalnum() function in C C Program to find the Roots of a Quadratic Equation C Switch Statements Difference between rand() and srand() function in C Difference between while and for loop in C Doubly Linked list in C Example of Iteration in C How to use atoi() function in C How to use floor() function in C How to use sine() function in C How to use Typedef Struct in C Integer Promotions in C C Program Swap Numbers in cyclic order Using Call by Reference C Program to Find Largest Number Using Dynamic Memory Allocation C Program to Find the Largest Number using Ternary Operator C/C++ Program to Find the Size of int, float, double and char Find the Largest Three Distinct Elements in an Array using C/C++ Loop Questions in C Modulus on Negative Numbers in C Multiplication table program in C using For loop Nested Loops in C Programming Examples C Program for Mean and Median of an Unsorted Array Results of Comparison Operations in C and C++ Reverse a Stack using Recursion in C Simple hash() function in C strcat() Function in C Sum of N numbers in C using For loop Use of free() function in C Write a program that produces different results in C and C++ C Function Argument and Return Values Keywords in C Bank management system in C Calendar application in C Floor() Function in C Free() Function in C How to delete a file in C How to move a text in C Remove an element from an array in C Unformatted input() and output() function in C What are linker and loader in C SJF Scheduling Program in C Socket Programming in C Structure in C Tower of Hanoi in C Union Program in C Variable Declaration in C What is Linked List in C While Loop Syntax in C fork() in C GCD program in C Branching Statements in C Comma Operator in C Control statement in C Double Specifier in C How to create a binary file in C Long int in C Palindrome Number in C Pure Virtual Function in C Run Time Polymorphism in C Types of Array in C Types of Function in C What is a buffer in C What is required in each C Program Associativity of Operators in C Bit Stuffing Program in C Actual and Formal Parameters Addition of two Numbers in C Advantages of function in C Arithmetic Progression Program in C Binomial Coefficient Program in C Difference between Array and List in C Diffie-Hellman Algorithm in C How to convert a number to words in C How to convert a string to hexadecimal in C Difference between If and Switch Statement in C C and C++ Binary Files C program that does not Suspend when Ctrl+Z is Pressed Different ways to Declare the Variable as Constant in C Range of Int in C C Program to find the size of a File FIFO Example in the C Language For loop in C Programming GCD program of two numbers in C GPA Calculator in C How to Calculate Time Complexity in C How to include graphics.h in C How to measure time taken by a function in C How to return a Pointer from a Function in C What is the main in C Addition of Matrix in C Booleans in C C Program for Extended Euclidean algorithms C Program of Fencing the Ground Ceil and Floor in C Compound Interest Program in C Displaying Array in C Distance Vector Routing Protocol Program in c Dos.h Header File in C Language DSA Program in C Explain the two-way selection in C Fee Management System in C File Operations in C Malloc function in C Multiplication Table in C Simple Programs in C Language tolower() Function in C Type Conversion in the C Why does sizeof(x++) not Increment x in C Advantages of Dynamic Memory Allocation in C Armstrong Number in C Assignment Operator Program in C Banker’s Algorithm in C Binary Search in C with Best and Worst Time Complexity Caesar Cipher Program in C Call by Value and Call by Reference in C Conditional Operator in C CRC Program in C Deadlock Detection Program in C Decimal to Binary in C Difference between If Else and Nested If Else in C Difference between Pre-increment and Post-increment in C Difference between Scope and Lifetime in C Evaluation of Arithmetic Expression in C Explain the Increment and Decrement Operators in C Fseek Function in C Functions in C How to Find Square Free Numbers in C Length of an Array Function in C OpenGL in C Projects on C language in 2023 Purpose of a Function Prototype in C Stdio.h in C Two-Dimensional array in C What is String Comparison in C C Compilers for Windows Functions and Recursion in C How to Declare Boolean in C How to Declare Character in C How to Round up a number in C How to use strlen() in C Pointer Declaration in C Algorithm for String Palindrome in C C Program to find ASCII value of a character Constant Pointer in C How to find string length in C using strlen() function Implicit and Explicit in C Indirect Recursion in C Input and Output functions in C isupper() in C Jump Statement in C Lifetime of a Variable in C Linker Error in C Language Numeric Constant in C Size of Pointer in C Square Root in C Language Static and Dynamic Memory allocation String Declaration in C Strong Number in C Symmetric Matrix in C Types of C Tokens What is a Size of Pointer in C What is Increment and Decrement Operator in C 1 2 3 4 Series Program in C Advantages and Disadvantages of C Language C Program for Polynomial Addition C Program to Count the Number of Vowels in a String C Programming Errors and Solutions Compilation Errors in C Complex C Programs Difference between Argument and Parameter in C Difference between char s[] and char *s in C Evaluation of Postfix Expression Using Stack in C Find Leftmost and Rightmost Set Bit of a Number fprintf and fscanf in C Introduction to Dynamic Array in C Print Address in C Realloc function in C Ternary Operators in C Types of Tokens in C with Examples Difference between Static and Dynamic Memory Allocation in C Addition Program in C Array Definition in C Array of Pointers in C Arrow Operator in C Average of Two Numbers in C Binary to Decimal in C Binary to Octal in C BREAK STATEMENT in C C Programming Operators Questions C Programs Asked in Interview Calculator Program in C C Program to Read and Print an Employee's Detail Using Structure Bubble Sort Algorithm in C C Program to Find Area and Perimeter of Circle C Program to Check Whether a Given Number is Even or Odd C in Roman Numerals C Program to Make a Simple Calculator Using Switch Case Insertion Sort Program in C How to take input in string in C GCC Conflicting Types in C Function Definition in C Format Specifier for Hexadecimal in C Flowchart in C Float in C Fizzbuzz Implementation in C Conditional Statement in C Conio.h functions list in C Constants in C Dynamic Array in C Decision Making Statements in C Continue Statement in C Creation of Thread in C DFS Algorithm in C Difference between parameter and arguments in C Dijkstra's Algorithm in C Leap Year Program in C Jump Statements in C Modulus Operator in C Memory Allocation in C Simple Interest Program in C Reverse Array in C Recursive Function in C Queue in C Printing Pascal’s Triangle in C Preprocessor Directives in C Perror() in C Perfect Number in C Programming Language Parameter Passing Techniques in C Pascal Triangle in C Patterm Program in C Affine cipher in C Dereferencing pointer in C Internal static variable vs External static variables in C Difference between exit(0) and exit(1) in C Booth's Algorithm in C Condition Control Statements in C Double Specifier in C Dynamic variables in C How to print alphabets in C How to print char array in c Order of Evaluation in C Order of Operations in C Semantic Error in C Size of String Variable in C SJF PREEMPTIVE SCHEDULING PROGRAM C: Tree in C Arithmetic Progression Program in C Array, Declaring Arrays, and Array Initialization ARRAYS IN C Assert() Function in c Atoi in C Bar3d() function in C Graphics Beep function in c Bigint (BIG INTEGERS) in C with Example Builtin functions of GCC compiler Fibonacci series in C Priority Queue in C 2D ARRAY IN C 7 Best IDEs for C/C++ Developers in 2022 Addition of Two Numbers in C Advantages and Disadvantages of C Language Advantages of Function in C Algorithm for String Palindrome in C What is fgets in C language 2d Shearing Program in C Recursion Questions In C Static Identifier in C Inserting elements in an array using C Language complex.h Header File in C fsetpos()(set file position) in C Comparator function of qsort() in C Print Hex in C strnset() function in C %d in C Butterfly Star pattern in C C form format in Excel Scan Line Polygon Filling in C 8 Queens Problem in C Back Trace in C BSS (Block Started by Symbol) Data Segment in C language Class C in Networking Strings in C Programming What is Circular linked list? What is Loop in C BITWISE OPERATOR IN C LANGUAGE BOMB DIFFUSION PROGRAM IN C LANGUAGE

Loop Questions in C

Question 1: What is For loop syntax?

Ans:

The syntax that has been used for the ‘for’ loop in C programming language is:

for (initialization statement /*for providing a value to variables*/; test expression /*to terminate a specified condition*/; update statement /*modify statement for further evaluation*/)
{
    /* main body of the ‘for’ loop */
}

Question 2: How does the for loop work?

Ans:

In for loop, the initialization command is implemented only once.

After that, it checks the test expression of the loop and finds whether the test expression is false or true. And, for loop is dismissed if the test expression is false.   
If the test expression of the 'F' loop becomes true, then the program line provided in the F loop’s body is executed, and the update expression is changed accordingly.
Again, the entire process of evaluation is to be done. The loop executes its body until and unless the value of the test expression in for loop becomes false. The loop automatically terminates as soon as the test expression result becomes false.

Question 3: What is while loop syntax?

Ans.

The syntax that can be used for the “while” loop in the C programming language is following:

while (test expression or termination condition (to terminate at specified condition)) 
{// the main body of the ‘while’ loop is written here}

Here we will let you know about the working of the “while” loop in C programming:

Initially, we use the parentheses for storing the termination condition of the While loop. Then, there can be two outcomes True or False.

Firstly, if the result is true, then the control will automatically execute the body of the loop. It will continue to evaluate again and again until the termination condition is false. Secondly, if the result is false, then the control will definitely come out of the While loop and will dismiss the While Loop.

Question 4: What is do while loop syntax?

Ans:

do 
{
  /* main body used for the loop */
}
while (termination condition (to terminate at specified condition));

while (termination condition (to terminate at specified condition));

Working of a do-while loop in C:

Initially, the body of do-while executes only one time. After that, the control executes the termination condition.

It then checks whether the termination command results in true. If yes, it will print the desired outcome on the screen, and it will continue to execute the termination condition again and again. One more thing is that the execution will run multiple times until the condition become false.
As soon as the results become false after the execution of the termination command, then the loop will be automatically dismissed.

Question 5: What is nested loop?

Ans:

A nested loop is generally used when we want to run a loop statement inside another loop statement. This kind of loop is also known as a “loop inside the loop”.

Explanation of execution of Nested loop:

In the nested loop, first we provide an initialization statement. Then, the control evaluates the value of the first condition and checks whether the termination condition is true or false.
If the value is false, it will terminate the entire process and only perform the basic command. But if the value is true, it will continue to check the second condition. If it finds the second condition false, it will terminate the processing of the program of the second condition and move to the primary/first loop and perform it.

And, if the second condition results to true, control will execute the loop and termination condition repeatedly until the value of condition becomes false. Along with this, some increment or decrement statements are implemented after every loop execution.

As the second condition terminates, it goes back to the first condition, checks again, and repeats the entire execution process. The execution of termination condition can take place multiple times. According to the loop, C control performs the condition given at the end and produces the outcome. At last, it will display the output on the screen.

Question 6: What is nested for loop syntax?

Ans:

Syntax used in initiating nested For loop:

for (initialization statement (for providing a value to variables); test expression (to terminate at specified condition); update statement (modify statement for further evaluation))
 {
      // initialization of the first for loop
   }
   // initialization of the second for loop
}

Question 7: What is nested while loop syntax?

Ans:

Syntax Used for Initiating Nested While Loop:

while (test expression (to terminate at specified condition)) 
{
// condition must be provided 
   while (test expression (to terminate at specified condition)) 
   { 
      // initialization of the first while loop
   }
   // initialization of the second while loop
}

Question 8: What is nested do while loop syntax?

Ans:

Syntax Used for Initiating Nested Do-While Loop:

do
{
   do
   {     
      // initialization of the first do while loop
   }
while(test expression (to terminate at specified condition)); //condition is given here
   // initialization of the second do while loop
}
while(test expression (to terminate at specified condition));

Question 9: What is nested mixed loop syntax?

Ans:

Syntax Used for Initiating Nested Mixed (Do-While, While, For) Loop:

do
{while(test expression (to terminate at specified condition)) 
// condition should be provided
{   
 for (initialization statement (for providing a value to variables); test expression (to terminate at specified condition); update statement (modify statement for further evaluation))
 
{// initialization of the first loop
 }
  // initialization of the first while loop
 }
 // initialization of second do-while loop
}
while(test expression (to terminate at specified condition));

Question 10: What is an infinity loop?

Ans:

The infinite loop is that loop which does not get dismissed because of its looping construct. A continuous output or no output are the two possible outcomes of this loop. It is also known as an endless loop or an indefinite loop.

There are a lot of applications where an infinite loop is helpful in running applications continuously. Those applications also produce endless outputs until the process is terminated manually. A few of them are the following:

  1. Games: The user can play unlimited matches continuously, but if the user wants to stop the match, the h/.she has to exit the game manually. The game does not terminate on its own.
  2. Operating Systems: As we usually observe, any operating system does not terminate their functioning on their own after the completion of task, until and unless the user manually shut downs the system.
  3. Servers and website: Infinite loop is also used in servers and websites which produce the output as many times the user asks to carry out the process. This processing only gets dismissed when the user closes the website or when the administrator manually shuts the servers and websites down.

Question 11: Write an example of infinite ‘for’ loop.

Ans:

#include <stdio.h>
int main ()  
{  
    int a, b=3; /* declaration and initialization of variables */ 
   for (a=2; a<=b; a--)  
/*for (initialization statement (for providing a value to variables); test expression (to terminate at specified condition); update statement (modify statement for further evaluation)) */
   {   
     printf ("tutorial and example\t"); // printing the output
   }  
return 0;  
} 

Output:

tutorial and example    tutorial and example	    tutorial and example     tutorial and example    tutorial and example    tutorial and example     tutorial and example    tutorial and example    tutorial and example     tutorial and example    tutorial and example    tutorial and example     tutorial and example    tutorial and example    tutorial and example     tutorial and example    tutorial and example    tutorial and example     tutorial and example

Question 12: Write an example of infinite ‘while’ loop.

Ans:

// basic program lines 
#include <stdio.h>  
int main ()  
{  
  int a=1; 
  /* declaration and initialization of variables */  
  while (1)
  {  
      a++;   
      /* increment or decrement statement */ 
      printf("Now a's value is:%d \t", a);  
      /* printing output */
  }  
return 0;  
}  

Output:

Now a's value is:2      Now a's value is:3      Now a's value is:4        Now a's value is:5       Now a's value is:6      Now a's value is:7      Now a's value is:8       Now a's value is:9      Now a's value is:10     Now a's value is:11     Now a's value is:12     Now a's value is:13    Now a's value is:14      Now a's value is:15     Now a's value is:16    Now a's value is:17     Now a's value is:18     Now a's value is:19     Now a's value is:20      Now a's value is:21      Now a's value is:22      Now a's value is:23      Now a's value is:24     Now a's value is:25    Now a's value is:26      Now a's value is:27     Now a's value is:28      Now a's value is:29      Now a's value is:30

Question 13: Write an example of infinite ‘do while’ loop.

Ans:

#include <stdio.h> 
int main ()
{
do  
{  
   printf("All the way up "); 
   /* initializing main body of the infinite do while loop.. */  
}
while (1); /* 1 is considered as true and 0 as false */
}

Output:

All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way up All the way

Question 14: What is the difference between ‘while’ loop and ‘do while’ loop?

Ans:

While loop:

Initially, we use the parentheses for storing the termination condition of the While loop. Then, there can be two outcomes True or False.

Firstly, if the result is true, then the control will automatically execute the body of the loop. It will continue to evaluate again and again until the termination condition is false. Secondly, if the result is false, then the control will definitely come out of the While loop and will dismiss the While Loop.

Do-while loop in C:

Initially, the body of do-while executes only one time. After that, the control executes the termination condition.

It then checks whether the termination command results in true. If yes, it will print the desired outcome on the screen, and it will continue to execute the termination condition again and again. One more thing is that the execution will run multiple times until the condition become false.
As soon as the results become false after the execution of the termination command, then the loop will be automatically dismissed.

Question 15: What is ‘entry’ control loop in C programming language?

Ans:

Initially, an entry control loop verifies the termination condition at the entry point. After that, its control passes to the main body of the while or for loop if the termination condition or test expression becomes true. This kind of loop usually regulates the ‘while’ and ‘for’ loop entrance. Due to this, it is known as an entry control loop in C.

Question 16: What is ‘exit’ control loop in C programming language?

Ans:

To examine the termination condition for exit, we usually use an exit control loop in C.

If the evaluation for termination condition results in true, then the control would be exited from the main body of the loop. Otherwise, the control enters inside the loop one more time.

This sort of loop usually deals with the exit control statement of the loop.

Question 17: How to print for factorial of any number using ‘for’ loop?

Ans:

Factorial of any positive integer:

#include <stdio.h>
int main () 
{
    int n, a; // declaring variables  
    unsigned long long fact = 1;
    printf ("Enter any positive number: \n"); // taking input from the user
    scanf ("%d", &n); // assigning the value inputted by the user to the declared variable
    // program line in case the user enters a negative integer, it will display error
    if (n < 0) // if termination condition
        printf ("Error 404! Sorry to say but there is no factorial of a negative integer."); // to display error
    else {
        for (a = 1; a <= n; ++a) // (initialization statement, test expression, increment statement) 
{
            fact *=a;
        }
        printf ("The factorial of given number is %d = %llu", n, fact); // printing output
    }
    return 0;
} 

This program will take a positive integer as an input from the user and compute the factorial of the given number with the help of for loop.

Sometimes, the factorial of some positive integers can be extremely large that’s why the “unsigned long long” is used as the data type of factorial variable to overcome this issue.

Suppose, the user enters any negative integer, the program will automatically display a pre-defined error message like this:

"Error 404! Sorry to say but there is no factorial of a negative integer"

Question 18: How to print for factorial of any number using ‘while’ loop?

Ans:

 #include<stdio.h>
int main()
{
int a, b=1, c=1; // declaring various variables and initializing values of b and c as 1, 1 simultaneously  
printf("Enter the natural number whose factorial you want to print:\n"); // taking a value as input from the user 
scanf("%d", &a); // assigning the value entered by the user to a
// providing termination condition so that we can avoid loop from running to infinity     
while(b<=a) // initializing loop for calculating the factorial of a positive integer provided by the user as an input
{
        c=c*b; // main body of the while loop that is to be executed until it the loop gets terminated because of the false value retained by the execution of termination condition
        b++;
}
    printf("The factorial of the given number %d is as follow %d", a, c); // printing the output
return 0;
}

Initially, the system will let the user to enter any positive integer and assign the entered number to the variable ‘a’.
After that, the code will multiply the values of ‘b’ with the value of ‘c’ with the help of ‘while’ loop.  This ‘while’ loop will execute the multiplication until the value of ‘b’ does not equal to the value of ‘a’.
And, at last, the program will automatically print the factorial value of the given number after the termination of while loop.

Question 19: How to print Fibonacci series using ‘for’ loop?

Ans:

#include <stdio.h>
int main () 
{
  int a, b;
  // declaring variables and initializing first and second terms without value
  int c1 = 0, c2 = 1; // declaring the value of term 1 as c1 = 0 and term 2 as c2 = 1 
  // initializing the upcoming third term (up.t.term) 
  int uptterm= t1 + t2;
  printf("Enter the no. of terms of the Fibonacci series you want to print: "); // taking input from the user about the no. of terms user wants to print
  scanf("%d", &b); // assigning the value entered by the user to b
  printf("Fibonacci Series is as follow: %d, %d, ", c1, c2); // printing the values of the first two declared as terms c1 and c2
  for (a = 3; a <= n; ++a) // (initialization statement; termination condition; increment or decrement statement) 
// printing the 3rd term and to the nth terms 
{
    printf("%d, ", uptterm);
    c1 = c2;
    c2 = uptterm;
    uptterm = c1 + c2;
  }
  return 0;
}

Question 20: How to print Fibonacci series using ‘while’ loop?

Ans:

#include<stdio.h>
int main ()
{
    int a=0, b=1, c, x=3, terms; 
/* declaring variables and initializing values of all variables */
    printf ("Enter the no. of terms of the Fibonacci series you want to print: "); 
/* taking input from the user to print the result */
    scanf ("%d", &terms); 
/* assigning the value entered to the variable -'terms' */
    printf ("%d\t %d", a, b); 
/* program command to print the values of 'a' and 'b' */
    while(x<=terms) 
/* termination condition or test expression */           
    {
        c=b + a; 
/* using assignment operator to assign the sum total value of 'b' and 'a'to 'c' */    
        printf ("\t %d", c); 
/* printing the value of variable 'c' that is equivalent to (b=a) */      
        a=b; 
/* using assignment operator to assign the value of 'a' to the 'b' */
        b=c; 
/* using assignment operator to assign the value of 'b' to the 'c' */
        x=x+1; 
/* using assignment operator to assign the incremented value of 'x' to 'x' itself */
    }
    return 0;
}

Question 21: How to find out prime numbers using ‘for’ loop?

Ans:

#include <stdio.h>
int main() 
{
  int n, a, flag= 0; 
/* declaring variables and initiating the value of flag as 0 */
  printf("Enter any natural number:  \n"); /* taking input from the user */
  scanf("%d", &n); /* assigning the value entered by the user to variable “n” */
  /* note down, 0 and 1 are not considered as prime numbers */
  /* that’s why providing value 1 for non-prime number flags (as flag=1) */
  if (n == 0 || n == 1) /* using “or” operator and comparison operators */
    flag = 1; /* assigning value to non-prime flags */
  for (a = 2; a <= n / 2; ++a) /* (initialization statement; termination condition; increment or decrement statement) */
{
    /* here we are declaring the fact that if the value of “n” is divisible by the value of “a”, in that case, “n” cannot be considered as a prime number for non-prime numbers we are going to set the value of flag as 1 */
    if (n % a == 0) 
/* n % a here means the remainder, when you divide the value of “n” by “a” */
{
      flag =1;
      break; 
/* break statement for ending the loop execution here */
    }
  }
  if (flag == 0)
    printf("%d can be considered as a prime number.", n); 
/* printing output for first situation */
  else
    printf("%d cannot be considered as a prime number.", n); 
/* printing output for first situation */
  return 0;
}

Question 22: Write a program to find out the composite numbers upto the number entered by the user with the help of for loop.

Ans:

#include<stdio.h>
#include<math.h>
int main ()
{
    int a, b, c; // declaring various variables without assigning values
    printf("Input a natural number up to which you want to print composite numbers :"); // taking input from the user
    scanf("%d", &c); // assigning value entered by the user to c
    for (a=2; a<=c; a++) // (initialization statement; termination condition; increment/decrement statement)  
    {
        for (b=2; b<=(int) pow(a,0.5); b++) // (initialization statement; termination condition; increment/decrement statement)  
        {
            if(a%b==0) // initializing if statement
            {
                printf("%d can be considered as a composite number \n", a); // printing the output
                break; // break statement to terminate “for” loop
            }    
        }
    }
    return 0;
}

Output:

Input a natural number up to which you want to print composite numbers :20
4 can be considered as a composite number
6 can be considered as a composite number
8 can be considered as a composite number
9 can be considered as a composite number
10 can be considered as a composite number
12 can be considered as a composite number
14 can be considered as a composite number
15 can be considered as a composite number
16 can be considered as a composite number
18 can be considered as a composite number
20 can be considered as a composite number

Question 23: Print the following output with the help of nested ‘while’ loop:

1

1 2
1 2 3
1 2 3 4
1 2 3 4 5

Ans:

#include <stdio.h>
int main ()
{
    int a=1, b; // declaring various variables as well as initiating value of ‘a’ as 1
    while (a <= 5) // while (termination condition)
    {
        b=1; // initialization of the value of ‘b’ as 1
        while (b <= a) // while (termination condition)
        {
            printf ("%d ", b); // printing the value of ‘b’ as an output
            b++; // increment statement to modify the value of ‘b’ for further evaluation
        }
       printf ("\n"); // printing the next line command as an output to change the new print line
        a++; // increment statement to modify the value of ‘b’ for further evaluation
    }
    return 0;
}

Question 24: Write down a program that prints the values from -5 to 5 with the help of all possible loops.

Ans.

With the help of ‘for’ loop:

#include <stdio.h>
int main ()
{ 
int a; // declaring variable
for (a=-5; a<6; ++a) // for (initialization statement, test expression, increment statement (modifying for further evaluation))
{
printf (“%d”, a); // printing the result as an output
}
return 0;
}

Output:

the value of a is -5
the value of a is -4
the value of a is -3
the value of a is -2
the value of a is -2
the value of a is -1
the value of a is 0
the value of a is 1
the value of a is 2
the value of a is 3
the value of a is 4
the value of a is 5 

With the help of ‘while’ loop:

/* Printing integers from -5 to 5 */
#include <stdio.h>
int main () 
{
  int a = -5; // declaring and initializing the value of ‘a’ as -5
  while (a <= 5) // termination condition
  {
    printf ("the value of ‘a’ is %d\n", a); // body of the ‘while’ loop 
    ++a; // increment/ decrement statement
  }
  return 0;
}

Output:

the value of a is -5
the value of a is -4
the value of a is -3
the value of a is -2
the value of a is -2
the value of a is -1
the value of a is 0
the value of a is 1
the value of a is 2
the value of a is 3
the value of a is 4
the value of a is 5 

With the help of ‘do while’ loop:

#include <stdio.h>
int main() 
{
  int a=-5;
    do //execute the task without checking the condition only once
  {
      printf("the value of a is %d\n", a);
      a++;//increment statement
  }  
    while(a<=5); //this is termination condition
  return 0;
}

Output:

the value of a is -5
the value of a is -4
the value of a is -3
the value of a is -2
the value of a is -2
the value of a is -1
the value of a is 0
the value of a is 1
the value of a is 2
the value of a is 3
the value of a is 4
the value of a is 5 

Question 25: Write a Program to print the table of any positive integers. You have to write a code which allows the user to enter the positive number at the run time.

Ans.

With the help of nested ‘for’ loop:

#include "stdio.h"
#include "conio.h"
void main()
{
    int n, a, ans; // declaring variables
    printf("\n Enter No. to print Table: ");
    scanf("%d", &n); // assigning value to a entered by the user
    /* for(initialization condition, 
    termination condition, increment or decrement condition) */
    for(a = 1; a <=10 ; a++ )
    {
       ans = n * a;
       printf("\n  %d * %d = %d", n,a, ans) ;
    }
    getch();
}

Output:

Enter No. to print Table: 2
  2 * 1 = 2
  2 * 2 = 4
  2 * 3 = 6
  2 * 4 = 8
  2 * 5 = 10
  2 * 6 = 12
  2 * 7 = 14
  2 * 8 = 16
  2 * 9 = 18
  2 * 10 = 20

Question 26: Make a program that can take input from the user and evaluate and print the factorial(!) of the entered positive number.

Ans.

With the help of ‘for’ loop:

#include <stdio.h>
int main () 
{
    int n, a; // declaring variables  
    unsigned long long fact = 1;
    printf ("Enter any positive number: \n"); // taking input from the user
    scanf ("%d", &n); // assigning the value inputted by the user to the declared variable
    // program line in case the user enters a negative integer, it will display error
    if (n < 0) // if termination condition
        printf ("Error 404! Sorry to say but there is no factorial of a negative integer."); // to display error
    else {
        for (a = 1; a <= n; ++a) // (initialization statement, test expression, increment statement) 
{
            fact *=a;
        }
        printf ("The factorial of given number is %d = %llu", n, fact); // printing output
    }
    return 0;
}

Output:

Enter an integer: 15
Factorial of 15 = 1307674368000

With the help of ‘while’ loop:

#include<stdio.h>
int main()
{
int a, b=1, c=1; // declaring various variables and initializing values of b and c as 1, 1 simultaneously  
printf("Enter the natural number whose factorial you want to print:\n"); // taking a value as input from the user 
scanf("%d", &a); // assigning the value entered by the user to a
// providing termination condition so that we can avoid loop from running to infinity     
while(b<=a) // initializing loop for calculating the factorial of a positive integer provided by the user as an input
{
        c=c*b; // main body of the while loop that is to be executed until it the loop gets terminated because of the false value retained by the execution of termination condition
        b++;
}
    printf("The factorial of the given number %d is as follow %d", a, c); // printing the output
return 0;
}

Output:

Enter the natural number whose factorial you want to print:
5
The factorial of the given number 6 is as follow 720

Here are some more loop questions:

Question 27: What is the difference between ‘for’ loop and ‘while’ loop?

Question 28: Write a C program for calculating the total of any consecutive negative and positive integers which are taken at run time by user.

Question 29: Construct a program that can assign two numbers entered manually by the user through the keyboard to different variables and can calculate the value of one integer raised to the power of another.

Question 30: Write a loop program that lets the user to input a numeral and then display the that number in reverse. Suppose 6487 is a entered number and its reverse is 7846 which is to be shown in output.

Question 31: Make a program that can read all the integers provided as input by the user and print the addition of all the even and odd numbers side by side.

Question 32: Construct a program using a loop that can read the inputted number by the user and can differentiate between the prime and non-prime numbers. The code print as ‘Number is a prime number’ or ‘Number is not a prime number’.

Question 33: Write a program that can provide the HCF of two numbers provided by the user.

Question 34: Write a do-while loop that enables the user to input two numbers. Initially, both the numbers must be added, and the sum should be displayed as an output. The loop must have an option for the user regarding running the program one more time only if the user wants. If yes, then run the program again. If not, then it should terminate.

Question 35: Write a program to print the addition of all the numbers entered by the user as per the need.

Question 36: Make a program that can read the numbers provided by the user as an input and can distinguish between the greater and smaller numerals. The code must print as an output.

Question 37: Construct a loop program to print all Armstrong numbers that lie between 1 and 500. Armstrong numbers are those numbers in which the total of each digit’s power raised to 3 is the same as the number provided. For example, 153 = (1 * 1 * 1) + (5 * 5 * 5) + (3 * 3 * 3)

Question 38: For printing the Fibonacci series, write down a loop program of n terms where n is provided by the user as input.
For instance 0 1 1 2 3 5 8 13 24 .... as an output.

Question 39: In order to evaluate the total of the below-given series, where n is the input provided by the user.
Series- 1 + 1/2 + 1/3 + 1/4 + 1/5 +.....1/n 

Question 40: Write a program, where n is a positive integer and input by the user, to calculate the natural logarithm of 2 by summing up all the numbers of series up to n terms.
Series- 1 - 1/2 + 1/3 - 1/4 + 1/5 -... 1/n

Question 41: Make an interesting game of guessing the number that has been generated by the machine, and that lets the user guess what the exact number it is.
If the user guesses higher than the number generated, the program should print "less than guessed, next time better luck." And if the user guesses lower than it, the program should automatically display "more than guessed, keep trying." The program should repeat itself until the user guesses the number generated by the machine correctly.

Question 42: Write down a loop program to calculate sin x for an initiated value of “x”. The user should provide the value of “x” and a positive integer “n” as input. The program evaluate the value of “sin” of “x” with the help of the following series, and this evaluation should utilize all the terms provided in the below-given series up to the term involving x’s power raised to the n.
Series- sin x = x - x3/3! + x5/5! - x7/7! + x9/9! .....