You are reading the article Do While Loop In C updated in December 2023 on the website Daihoichemgio.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 Do While Loop In C
Introduction to Do While Loop in CDO WHILE loop is the same as WHILE LOOP built-in term of the C Programming Language/Many other Programming Languages but DO WHILE loops execute the Program Statements first then the condition will be checked next. This is the main different thing when we compare with the WHILE LOOP. The condition will be checked first by the WHILE LOOP then the Programming Statements will be executed first. DO WHILE will execute the program at first even if the condition is valid/un-appropriate/False at first.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Syntax:
do{ }while(Condition);
Statements inside of the do while will be executed based on its instruction only if the condition of the loop is true the second time. at first, statements will be executed and printed without checking the loop condition.
While(Condition): Condition inside a loop is a parameter to run the program if the condition is TRUE else no programming statements will be executed which are inside of it
Flowchart of Do While LoopThe flow chart of do while loop in C are given below:
How do While Loop Works in C?:The do while loop works based on the condition in the while() parameter but at 1st the program inside of the do while will be executed then the condition is checked. it is the main working difference between the while and the do while program.
Examples of Do While Loop in CExamples of do while in C programming are given below:
Example #1The below example here is to print natural numbers within 10 from 1 number with the do while loop.
Code:
int main() { int i=1; printf(“Hi This is pavan.. WELCOME. Here I m Printing Natural Numbers:n”); do{ printf(“%d”,i);//printing i variable’s value printf(“,”); i=i+1; }while(i<10); printf(“n”); return 0; }
Output:
Example #2Switch case listed do while program to print some specific text based on the options list which are embedded/showing in the program in the terminal/compiler when executing it.
Code:
void main () { char c1; int choice1,dummy1; do{ printf(“n1. Print Hello Pavann2. Print C Languagen3. Exitn”); scanf(“%d”,&choice1); switch(choice1) { case 1 : printf(“Hello Pavann”); break; case 2: printf(“C Languagen”); break; case 3: exit(0); break; default: printf(“Atleast Now enter a valid choice/option”); } printf(“If you want to enter again/more?”); scanf(“%d”,&dummy1); scanf(“%c”,&c1); }while(c1==’y’); }
Output:
Example #3This is the C Program to print the table of the number which gave as input to the terminal/compiler by the user of the System. Here you can print any kind of table with up to the 10 multiples of the user input number. kindly give it a try and know how the table’s program is working using do while. even though if the condition in the do while is incorrect/false the program inside the loop will be executed just once without any error/any other.
Code:
int main(){ int i1=1,number1=0; printf(“Enter number to print its table : “); scanf(“%d”,&number1); printf(“========================n”); do{ printf(“%d X “,number1); printf(“%d = “,i1); printf(“%d n”,(number1*i1)); i1++; }while(i1<=10); printf(“========================n”); return 0; }
Output:
Example #4Below C Program is to print the sum of natural numbers using do while loop in my way. Check it you will get a small idea to build many big projects of programming in the future.
Code:
int main(){ int i1=1,number2=0,number1,a1; printf(“Enter number to print sum of the natural numbers in my way : “); scanf(“%d”,&number1); printf(“========================n”); do{ printf(“%d n”,i1); number2=number2+i1; a1=number2; a1=a1+number2; i1++; }while(i1<=number1); printf(“========================n”); printf(“n========================n”); return 0; }
Output:
Example #5Infinite Loop program in do while loop syntax of C programming language.
Code:
int main(){ int i=1; do{ printf(“%d.”,i); printf(“pavan kumar sake “); i=i+1; }while(1); }
Output:
Example #6The below example of the C Syntax Program will Print natural numbers, odd numbers, prime numbers, and its sum in a well-illustrated way.
int main() { int nums1=1,nums2,nums3=1,nums4=0,nums5=0, nums6=0, nums7=1; printf(“List of Even Numbers n”); do { printf(“%d “,2*nums1); nums4=nums4+(2*nums1); nums1++; }while(nums1<=10); printf(“n”); printf(“Sum of Even numbers : %d n”,nums4); printf(“n”); printf(“List of Odd Numbers n”); do { nums2= (2*nums3)+1; nums5 = nums5+nums2; printf(“%d “,nums2); nums3++; }while(nums3<=10); printf(“n”); printf(“Sum of Odd numbers : %d n”,nums5); printf(“n”); printf(“List of 1st 10 Natural Numbers n”); do { nums6 = nums6+nums7; printf(“%d “,nums7); nums7++; }while(nums7<=10); printf(“n”); printf(“Sum of 1st 10 Natural numbers : %d n”,nums6); return 0; }
Output:
Example #7This is the example to print the perfect numbers using DO WHILE program with C Language syntax.
Code:
int main() { int n,k,l; printf(“Enter how many perfect nums you want to print:: “); scanf(“%d”,&n); int c=0; int i=1; do{ l=0; for(k=1;k<i;k++){ if (i%k==0){ l=l+k; } } if(i==l){ printf(“n %d is a perfect number.n”,i); c=c+1; } if(c==n){ break; } i=i+1; return 0; getchar(); }
Output:
Example #8Basic simple calculator program using do while and switch case condition. Check the syntax. Everything is mostly simple in the do while c program which is listed below.
Code:
int main() { int yes1; int a1, b1, c1, choice1; yes1 = 1; do { printf(“Enter 1st integer: “); scanf(“%d”, &a1); printf(“Enter 2nd integer: “); scanf(“%d”, &b1); printf(“n Add (1), Subtract (2), Multiply (3), Divide (4) :: “); scanf(“%d”, &choice1); printf(“n”); switch(choice1) { case(1): c1 = a1 + b1; printf(“%d + %d = %dn”, a1, b1, c1); break; case(2): c1 = a1 – b1; printf(“%d – %d = %dn”, a1, b1, c1); break; case(3): c1 = a1 * b1; printf(“%d * %d = %dn”, a1, b1, c1); break; case(4): c1 = a1 / (float)b1; printf(“%d / %d = %dn”, a1, b1, c1); break; default: printf(“Incorrect choice. Try again.n”); } printf(“nChoose Option n 1. YES n 2. NO : “); scanf(“%d”, &yes1); }while(yes1 == 1); return 0; }
Output:
Recommended ArticlesThis is a guide to Do While Loop in C. Here we discuss the basic concept and parameters of do-while loop in C along with different examples and its code implementation. You may also look at the following articles to learn more –
You're reading Do While Loop In C
How Does Do While Loop Work In Java With Examples
Introduction to do while loop in Java
Looping in any programming language has been used ever since. Loops and iterations form an essential component of the programming language, Be it Java or Python; One such looping construct is the do-while loop in the language of Java which is also popularly known as a post-incremental loop, i.e. where the looping construct runs for one time for sure and then the condition is matched for it to run the next time and so on. The condition, in this case, is put in the end. In other words, the condition blocks keep on executing continuously unless and until a specific set of conditions is termed as true.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
do { } while (expression);The expression which is mentioned right after the while block is used to return a Boolean value, i.e. either a true value or a false value. If either of the values could not be found, then the compiler throws a compile-time error. The do command in this syntax ensures that the code is executed at least once, even when the expression is not executed, or the condition is not checked. The block of statements is the set of statements that are executed inside the do-while looping construct. This consists of the program body. The while statement, in the end, is used to evaluate the expression and then apply a postcondition to check whether the intended case is meeting the requirements and should be further looped.
How does a do-while loop work in Java?Following is the explanation for how does do-while loop work in Java:
For a do-while loop to work, the condition is not necessary to be met as this loop also works well for the first time even when the condition is not met. The compiler executor then enters the function execution block executes whatever is there within the block of statements, and then comes out to check the expression part where the condition is compared. If the condition is met, then the loop is reiterated; otherwise, the loop is exited from the block. The basic difference between the while and the do-while loop is that while the former one looks for the pre-conditions, the latter one targets the postconditions.
The basic difference between a do-while and a very well-known loop is that the number of iterations is needed to be known in the loop and the initial value and the value which is being incremented. This is more often used when the iterations and their count are fixed in number, whereas in the case of the do-while loop, the number of iterations is not known before-hand but can change dynamically.
Flow Diagram:
Examples for do-while loop in JavaBelow are the examples of all the numbers till 10:
Example #1Printing all the Numbers less than equal to 10.
Code:
public class Main { public static void main(String args []) { int c=1; System.out.println("printing all the numbers till 10:"); do { System.out.println(c); ++c; } while(c<11); } }Output:
Example #2Iterating an Array by making use of do-while loop in Java.
Code:
public class Main { public static void main(String args []) { int arr[]= {1, 6, 7, 514, 4, 98}; System.out.println("Printing the list of arrays: "); int i=0; do { System.out.println(arr[i]); ++i; } while (arr[i]<=6); } } Example #3Writing a program for an Infinite do-while loop.
Code:
public class Main { public static void main(String[] args) { do { System.out.println("infinite do while loop"); } while(true); } }Output:
This program will run infinitely until the code block is explicitly broken as the infinite loop hits the condition of the while loop is true, which is a true condition and will always be met. Therefore, these types of loops and programming constructs are not encouraged. They can confuse the compiler and hang your system if it doesn’t contain appropriate RAM and other memory requirements.
Example #4Printing all the Numbers from 10 till 1 in Reverse order.
Code:
public class Main { public static void main(String args []) { int c=10; System.out.println("Printing all the numbers from 10 till 1"); do { System.out.println(c); --c; } } Example #5Printing all the numbers less than Equal to 10 without using the Increment operator.
Code:
public class Main { public static void main(String args []) { int c=1; System.out.println("printing all the numbers till 10"); do { System.out.println(c); c+=1; } while(c<11); } }Output:
The basic difference between this example and the first example was the use of shorthand operators in this case and the use of a pre-incremental counter in the case of example number 1. Both of them will produce the same result; it is just a matter of your choice of which operator you wish to choose for the do-while loop.
ConclusionIn this post, we saw the basic level of introduction to do while loop. We also saw the working of the do-while loop in detail. We saw the intricacies and the major differences and the do-while loop applications over other looping constructs such as while or for loops. We studied the flowchart of the do-while loop, which helped us in understanding it more deeply. We read about the syntax and a huge list of various examples to understand the do-while loop clear.
Recommended ArticlesThis is a guide to do while loop in Java. Here we discuss how does do while loop work in Java, with a flow diagram and top 5 examples in it. You can also go through our other related articles to learn more –
Command Line Arguments In C
Introduction to Command Line Arguments in C
Web development, programming languages, Software testing & others
The syntax :
int main(int argc, char *argv[])where argc represents the count of arguments passed to the program and argv[] is a pointer array holding the pointers of data type char pointing to the arguments passed to the program.
Working of Command-Line Arguments in C
Whenever there is a need to pass the values to the program from outside and do not want to use it inside the code, we make use of Command-Line Arguments in C.
The values passed to the C program from the command line when the program is executed are called command-line arguments in C.
The main() function in the program handles the command line arguments passed to the program when the program is executed.
The number of arguments passed to the program is represented by argc and every argument passed to the program is pointed by a pointer which is maintained in a pointer array represented by argv[].
Examples of Command-Line Argumentshere are the following examples mention below:
Example #1This program to demonstrate the use of Command-Line Arguments in a program to display the arguments passed to the program.
Code:
//main method is called to which the command line arguments are passed to the program int main(int argc, char *argv[]) { int a; { printf(“The arguments passed to the program are:n”); for(a = 1; a < argc; a++) { printf(“The argument passed to the program is: %st”, argv[a]); } } else { printf(“No argument is passed to the programn”); } return 0; }
In the above program, the main method is called to which the command line arguments are passed to the program. Then an integer variable is defined. Then if condition is applied to check if the count of arguments passed to the program is greater than or equal to two and if the condition is true, the command line arguments passed to the program is printed otherwise no argument is passed to the program is printed. We are not passing any command-line arguments to the program, hence the output no argument is passed to the program is printed on the screen.
Example #2C program to demonstrate the use of Command-Line Arguments in a program to display the arguments passed to the program.
Code:
//main method is called to which the command line arguments are passed to the program int main(int argc, char *argv[]) { int a; { printf(“The arguments passed to the program are:n”); for(a = 1; a < argc; a++) { printf(“The argument passed to the program is: %st”, argv[a]); } } else { printf(“No argument is passed to the programn”); } return 0; }
In the above program, the main method is called to which the command line arguments are passed to the program. Then an integer variable is defined. Then if condition is applied to check if the count of arguments passed to the program is greater than or equal to two and if the condition is true, the command line arguments passed to the program is printed otherwise no argument is passed to the program is printed. We are not passing Hello as command-line arguments to the program.
Note: Please pass the command line argument along with giving the program name to execute the program.
Advantages of Command-Line Arguments in C
Whenever there is a need to pass the values to the program from outside and do not want to use it inside the code, Command Line Arguments can be used in C.
The program to be executed can be controlled from the outside than hard-coding the values inside the program by making use of Command-Line Arguments.
Conclusion Recommended ArticlesStack In C++ Stl With Example
What is std::stack?
A stack is a data structure that operates based on LIFO (Last In First Out) technique. The std::stack allows elements to be added and removed from one end only.
The std::stack class is a container adapter. Container objects hold data of a similar data type. You can create a stack from various sequence containers. If no container is provided, the deque containe will be used by default. Container adapters don’t support iterators, so it can’t be used to manipulate data.
In this C++ tutorial, you will learn
Stack Syntax
Type – is the Type of element contained in the std::stack. It can be any valid C++ type or even a user-defined type.
Container – is the Type of underlying container object.
Member TypesHere are stack member types:
value_type- The first template parameter, T. It denotes the element types.
container_type- The second template parameter, Container. It denotes the underlying container type.
size_type- Unsigned integral type.
Operations in StackA C++ stack supports the following basic operations:
push – It adds/pushes an item into the stack.
pop – It removes/pops an item from the stack.
peek – Returns the top item of the stack without removing it.
isFull – Checks whether a stack is full.
isEmpty – Checks whether a stack is empty.
Stack Implementation
Step 1) We initially have an empty stack. The top of an empty stack is set to -1.
Step 2) Next, we have pushed the element 5 into the stack. The top of the stack will points to the element 5.
Step 3) Next, we have pushed the element 50 into the stack. The top of the stack shifts and points to the element 50.
Step 4) We have then performed a pop operation, removing the top element from the stack. The element 50 is popped from the stack. The top of the stack now points to the element 5.
push() and pop()The stack::push() functions adds new item to the top of stack. The stack size is increased by a 1 after the insertion. The function takes this syntax:
stack.push(value)The value is the item to insert into the stack.
The stack:: pop() function removes the top element of the stack. This is the newest item of the stack. The stack size is reduced by 1 after the removal. Here is the function syntax:
stack.pop()The function takes no parameters.
Example 1:using namespace std; int main() { st.push(10); st.push(20); st.push(30); st.push(40);
st.pop(); st.pop();
while (!st.empty()) { cout << ‘ ‘ << st.top(); st.pop(); } }
Output:
Here is a screenshot of the code:
Code Explanation:
Include the iostream header file in our code to use its functions.
Include the stack header file in our code to use its functions.
Include the std namespace in our code to use its classes without calling it.
Call the main() function. The program logic should be added within this function.
Create a stack st to store integer values.
Use the push() function to insert the value 10 into the stack.
Use the push() function to insert the value 20 into the stack.
Use the push() function to insert the value 30 into the stack.
Use the push() function to insert the value 40 into the stack.
Use the pop() function to remove the top element from the stack, that is, 40. The top element now becomes 30.
Use the pop() function to remove the top element from the stack, that is, 30. The top element now becomes 20.
Use a while loop and empty() function to check whether the stack is NOT empty. The ! is the NOT operator.
Printing the current contents of the stack on the console.
Call the pop() function on the stack.
End of the body of the while loop.
End of the main() function body.
Stacks have inbuilt functions that you can use to play around with the stack and its values. These include:
empty()- checks whether a stack is empty or not.
size()- returns the size of stack, that is, number of elements in a stack.
top()- accesses stack element at the top.
Example 2:using namespace std; { while (!ms.empty()) { cout << ‘t’ << ms.top(); ms.pop(); } cout << ‘n’; } int main() { st.push(32); st.push(21); st.push(39); st.push(89); st.push(25);
cout << “The stack st is: “; createStack(st); cout << “n st.size() : ” << st.size(); cout << “n st.top() : ” << st.top(); cout << “n st.pop() : “; st.pop(); createStack(st); return 0; }
Output:
Here is a screenshot of the code:
Code Explanation:
Include the iostream header file in our code in order to use its functions.
Include the stack header file in our code in order to use its functions.
Include the std namespace in our program in order to use its classes without calling it.
Create the function createStack that we can use to create the stack mystack. The stack will hold a set of integers.
The beginning of the body of the createStack function.
Create an instance of the mystack datatype and giving it the name ms.
Use the while loop and the empty() function to check whether the stack is empty.
The start of the body of the while loop.
Use the top() function stored at the top of the stack. The t character will create a new tab.
Use the pop() function to delete the element at the top of the stack.
End of the body of the while loop.
Print a blank line on the console.
End of the body of the createStack function.
Call the main() function. The program logic should be added within the body of the main() function.
The start of the body of function main().
Create a stack object st.
Use the push() function to insert the element 32 into the stack.
Use the push() function to insert the element 21 into the stack.
Use the push() function to insert the element 39 into the stack.
Use the push() function to insert the element 89 into the stack.
Use the push() function to insert the element 25 into the stack.
Print some text on the console.
Call the createStack function to execute the above insert operations into the stack.
Print the size of the stack on the console alongside other text.
Print the element at the top of the stack on the console.
Print some text on the console.
Delete the element at the top of the stack. It will then return the elements remaining in the stack.
Call the createStack function to execute the above operations.
The program must return value upon successful completion.
End of the body of function main().
emplace() and swap()These are other inbuilt stack functions:
emplace()- constructs then inserts new element to top of stack.
swap()- exchanges stack contents with another stack’s contents.
Example 3:using namespace std; int main() {
st1.emplace(12); st1.emplace(19);
st2.emplace(20); st2.emplace(23);
st1.swap(st2);
cout << “st1 = “; while (!st1.empty()) { cout << st1.top() << ” “; st1.pop(); }
cout << endl << “st2 = “; while (!st2.empty()) { cout << st2.top() << ” “; st2.pop(); } }
Output:
Here is a screenshot of the code:
Code Explanation:
Include the iostream header file in our code to use its functions.
Include the stack header file in our code to use its functions.
Include the cstdlib header file in our code to use its functions.
Include the std namespace in our code to use its classes without calling it.
Call the main() function. The program logic will be added within the body of this function.
Declare a stack named st1 to store integer values.
Declare a stack named st2 to store integer values.
Use the emplace() function to insert the integer 12 into the stack named st1.
Use the emplace() function to insert the integer 19 into the stack named st1.
Use the emplace() function to insert the integer 20 into the stack named st2.
Use the emplace() function to insert the integer 23 into the stack named st2.
Use the swap() function to swap the contents of the two stacks, st1 and st2. The contents of the stack st1 should be moved to the stack st2. The contents of the stack st2 should be moved to the stack st1.
Print some text on the console.
Use the while statement and the empty() function to check whether the stack st1 is not empty.
Print the contents of the stack st1 on the console. The ” ” adds space between the stack elements when printing them on the console.
Execute the pop() function on the stack st1 to remove the top element.
End of the body of the while statement.
Print some text on the console. The endl is a C++ keyword for end line. It moves the mouse cursor to the next line to begin printing from there.
Use the while statement and the empty() function to check whether the stack st2 is not empty.
Print the contents of the stack st2 on the console. The ” ” adds space between the stack elements when printing them on the console.
Execute the pop() function on the stack st2 to remove the top element.
End of the body of the while statement.
End of the body of the main() function.
Stack in STLThe STL (Standard Template Library) comes with template classes that provide common C++ data structures. Therefore, a stack can also be implemented in STL. We simply include this library in our code and use it to define a stack.
The above syntax declares a stack st to elements of data type T.
Example 3:using namespace std; int main() { st.push(12); st.push(19); st.push(20); cout << st.top(); cout << st.size(); }
Output:
Here is a screenshot of the code:
Code Explanation:
Include the iostream header file in our code to use its functions.
Include the stack header file in our code to use its functions.
Include the cstdlib header file in our code to use its functions.
Include the std namespace in our code to use its classes without calling it.
Call the main() function. The program logic should be added within the body of this function.
Declare a stack st to store integer data.
Add the element 12 to the stack.
Add the element 19 to the stack.
Add the element 20 to the stack.
Print the element at the top of the stack on the console.
Print the size of the stack on the console.
End of the body of the function main().
Summary:
A stack is a data structure that operates based on the LIFO (Last In first Out) technique.
The std::stack only allows items to be added and removed from one end.
The std::stack class is a container adapter, holding items of a similar data type.
A stack can be created from various sequence containers.
If you don’t provide a container, the deque container will be used by default.
The push() function is for inserting items into the stack.
The pop() function is for removing the top item from the step.
The empty() function is for checking whether a stack is empty or not.
How Sizeof() Operator Work In C++ With Examples
Introduction to C++ sizeof()
The sizeof() is an operator in C and C++. It is an unary operator which assists a programmer in finding the size of the operand which is being used. The result of this operator is an integral type which is usually signified by size_t. This operator is usually used with data types which can be primitive data types like integer, float, pointer, etc. It can also give size of complex datatypes like structure, union, etc. It is a compile time operator which will tell the size of any data type and compute the size of operand.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Below is the syntax of using sizeof():
sizeof(type) sizeof expressionThe sizeof function in the first type, will give the output as an size in bytes of the object of the type which is sent. The second type is the size in bytes of the object which is in the type of expression. The size will be the size once the expression is evaluated. In both these versions the constant expression of the standard type that is size_t.
How sizeof() Operator work in C++?The sizeof() operator can be used to find the size of datatype or expressions. They work in a very easy manner of taking these as arguments and work on them by returning the size in bytes.
Code:
using namespace std; int main() { cout << “Size of char : ” << sizeof(char) << endl; cout << “Size of int : ” << sizeof(int) << endl; cout << “Size of expression 5 + 8 is : ” << sizeof(5 + 8) << endl; return 0; }
As stated earlier the sizeof function will help us in getting the size of every datatype. Hence it uses these data types as an argument and return the data size of each data type. We have also taken size of expression where we are adding 2 integers. It will calculate these and the result will also be an integer. Hence the output for this will be also 4. The output of above function and code will be the number of bytes each variable uses. To check a few the output for char will be as below.
Output:
Examples of C++ sizeof()Given below are the examples mentioned:
Example #1Operand as a data type.
Code:
using namespace std; int main() { cout << “The size of char data type is ” << sizeof(char)<<“n”; cout << “The size of int data type is ” << sizeof(int)<<“n”; cout << “The size of float data type is “<< sizeof(float)<<“n”; cout << “The size of double data type is ” << sizeof(double)<<“n”; return 0; }
Output:
Example #2Operand as an expression.
Code:
using namespace std; int main() { int a = 7; float d = 15.21; cout << “The addition of int and float is a float as follows: ” << a + d; cout << “nThe size of the expression is ” << sizeof(a + d); return 0; }
The above code with return the size of the data type of the resulting expression. Here we have declared two variables. One variable is an integer and the second variable is a float. We are now adding these two variables in the expression of which we will be finding the size of. The result of this expression will be a float. Hence the sizeof will be the size of float data type.
Output:
Example #3Finding number of elements in the array.
Code:
using namespace std; int main() { int array1[] = { 1,5,76,89,23,06 }; cout << “The number of elements which are present in the array are : “ <<(sizeof(array1) / sizeof(array1[0])); return 0; }
In addition to giving the size of expressions and data types, the sizeof operator can also be used to find the number of elements in an array. Here we have defined an array ‘array1’. We have a few elements added to it. In order to get the count of these elements and get exactly how many elements are present in it we can simply make use of the sizeof operator.
We specify the array name and the first index that is array1[0] which helps us in starting he count from beginning. It will start from index 0 and count till the end. Once it reached the end it will display the number of elements. It will be returned by this sizeof() function that we have.
Output:
ConclusionThe sizeof() operator is a function which returns the size of any data type, expression, array, etc. It takes the data type or expression as a part of argument which is mandatory and returns the result which is size of that data type in bytes. If it is an array it will return the number of elements present in it. It is a very useful function when we have to allocate memory. We can calculate the size and allocate memory as per requirement and as a result save a lot of space which otherwise will be occupied.
Recommended ArticlesThis is a guide to C++ sizeof(). Here we discuss how sizeof() operator work in C++ along with examples respectively. You may also have a look at the following articles to learn more –
How To Manage Full Circular Queue Event In C++?
Introduction
Circular Queue is an improvement over a linear queue and it was introduced to address the memory wastage problem in the linear queue. A circular queue uses the FIFO principle for the insertion and removal of the elements from it. In this tutorial, we will discuss the operations of the circular queue and how to manage it.
What is Circular Queue?A circular queue is another kind of queue in a data structure, whose front and rear ends are connected with each other. It is also known as Circular Buffer. Its operations are similar to the linear queue, so why do we need a new queue in the data structure?
With the linear queue, when the queue reaches its maximum limit, there is a possibility of some memory space before the rear point. It results in memory loss and a good algorithm is one that utilizes resources at their maximum.
Rear − It returns the rear value of the queue.
Front − It returns the front value of the queue.
deQueue − This in-built method is used to remove elements from the queue while checking if it is empty or not.
enQueue − This method is used to insert new elements to the queue while checking its size.
In a circular queue, elements are added at the rear end and removed elements from the front end. deQueue and enQueue are queue-size-independent functions and use the modulo operator for their implementation. Their time complexity is O(1).
Managing a Circular QueueWe are managing a circular queue by using the enQueue and deQueue operations. Initially, a circular queue has a front value of 0 and a rear value of -1, where all elements in the circular queue are NULL.
ExampleC++ code of circular Queue Implementation using an array
using namespace std;
class Queue { int rear, front; int sz; int* arr;
public: Queue(int s) { front = rear = -1; sz = s; arr = new int[s]; }
void enQueue(int v); int deQueue(); void displayQueue(); };
//Circular queue function void Queue::enQueue(int v) { if ((front == 0 && rear == sz – 1) printf(“nNo Space Queue is Full”); return; }
else if (front == -1) { front = rear = 0; arr[rear] = v; }
else if (rear == sz – 1 && front != 0) { rear = 0; arr[rear] = v; }
else { rear++; arr[rear] = v; } }
//Function for deleting queue elements int Queue::deQueue() { if (front == -1) { printf(“nQueue needs data it is empty”); return INT_MIN; }
int ele = arr[front]; arr[front] = -1; if (front == rear) { front = -1; rear = -1; } else if (front == sz – 1) front = 0; else front++; return ele; }
//Printing Circular queue elements void Queue::displayQueue() { if (front == -1) { printf(“nQueue Empty”); return; } printf(“nCircular Queue elements are: n”); for (int i = front; i <= rear; i++) printf(“%d “, arr[i]); } else { for (int i = front; i < sz; i++) printf(“%d “, arr[i]);
for (int i = 0; i <= rear; i++) printf(“%d “, arr[i]); } }
int main() { Queue q(5); q.enQueue(10); q.enQueue(20); q.enQueue(3); q.enQueue(5); q.displayQueue();
printf(“nDeleted element = %dn”, q.deQueue()); printf(“nDeleted element = %d”, q.deQueue()); q.displayQueue(); q.enQueue(13); q.enQueue(27); q.enQueue(50); q.displayQueue(); q.enQueue(22);
return 0; }
Output Circular Queue elements are: 10 20 3 5 Deleted element = 10 Deleted element = 20 Circular Queue elements are: 3 5 Circular Queue elements are: 3 5 13 27 50 No Space Queue is Full ConclusionA circular queue is used in memory management and CPU scheduling. It uses the displayQueue() function to display the queue elements.
We reached the end of this tutorial. I hope this tutorial helped you to understand how to implement a circular Queue.
Update the detailed information about Do While Loop In C on the Daihoichemgio.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!