Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


C Programming Code Examples

C > Beginners Lab Assignments Code Examples

Implement various Queue Functions using Dynamic Memory Allocation

/* Implement various Queue Functions using Dynamic Memory Allocation - Use malloc function to allocate memory. - Define separate functions for the operations like insert, delete and display. - Use switch statement to access these functions. */ #include <stdio.h> #include <stdlib.h> #define MAX 10 struct node { int data; struct node *link; }*front, *rear; // function protypes void insert(); void delete(); void queue_size(); void check(); void first_element(); void main() { int choice, value; while(1) { printf("enter the choice \n"); printf("1 : create an empty queue \n2 : Insert element\n"); printf("3 : Dequeue an element \n4 : Check if empty\n"); printf("5. Get the first element of the queue\n"); printf("6. Get the number of entries in the queue\n"); printf("7. Exit\n"); scanf("%d", &choice); switch (choice) // menu driven program { case 1: printf("Empty queue is created with a capacity of %d\n", MAX); break; case 2: insert(); break; case 3: delete(); break; case 4: check(); break; case 5: first_element(); break; case 6: queue_size(); break; case 7: exit(0); default: printf("wrong choice\n"); break; } } } // to insert elements in queue void insert() { struct node *temp; temp = (struct node*)malloc(sizeof(struct node)); printf("Enter value to be inserted \n"); scanf("%d", &temp->data); temp->link = NULL; if (rear == NULL) { front = rear = temp; } else { rear->link = temp; rear = temp; } } // delete elements from queue void delete() { struct node *temp; temp = front; if (front == NULL) { printf("queue is empty \n"); front = rear = NULL; } else { printf("deleted element is %d\n", front->data); front = front->link; free(temp); } } // check if queue is empty or not void check() { if (front == NULL) printf("\nQueue is empty\n"); else printf("Elements are present in the queue \n"); } // returns first element of queue void first_element() { if (front == NULL) { printf(" The queue is empty \n"); } else printf(" The front element is %d \n", front->data); } // returns number of entries and displays the elements in queue void queue_size() { struct node *temp; temp = front; int cnt = 0; if (front == NULL) { printf(" queue empty \n"); } while (temp) { printf("%d ", temp->data); temp = temp->link; cnt++; } printf(" size of queue is %d \n", cnt); } /* - Ask the user for the operations like insert, delete, display etc. - According to the entered option access the respective functions. Use switch statement to access the functions. - Use structure with a data and a pointer as the data module. Use malloc function to assign the memory dynamically. - In the insert() function ask the user to enter the number to be inserted and store the value into the new data module's data. - In the delete() function delete the element at the front. - In the check() function, check if the queue is empty or not. - In the first_element() function, print the first element of the queue. */

Allocate memory block. Allocates a block of size bytes of memory, returning a pointer to the beginning of the block. The content of the newly allocated block of memory is not initialized, remaining with indeterminate values. If size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be dereferenced. The "malloc" or "memory allocation" method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It doesn't Iniatialize memory at execution time so that it has initializes each block with the default garbage value initially.

#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program. Here are the two types of file that can be included using #include:

The if-else statement is used to perform two operations for a single condition. The if-else statement is an extension to the if statement using which, we can perform two different operations, i.e., one is for the correctness of that condition, and the other is for the incorrectness of the condition. Here, we must notice that if and else block cannot be executed simiulteneously. Using if-else statement is always preferable since it always invokes an otherwise case with every if condition.

The break is a keyword in C which is used to bring the program control out of the loop. The break statement is used inside loops or switch statement. The break statement breaks the loop one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to outer loops.

The exit() function is used to terminate a process or function calling immediately in the program. It means any open file or function belonging to the process is closed immediately as the exit() function occurred in the program. The exit() function is the standard library function of the C, which is defined in the stdlib.h header file. So, we can say it is the function that forcefully terminates the current program and transfers the control to the operating system to exit the program. The exit(0) function determines the program terminates without any error message, and then the exit(1) function determines the program forcefully terminates the execution process.

Switch statement in C tests the value of a variable and compares it with multiple cases. Once the case match is found, a block of statements associated with that particular case is executed. Each case in a block of a switch has a different name/number which is referred to as an identifier. The value provided by the user is compared with all the cases inside the switch block until the match is found. If a case match is NOT found, then the default statement is executed, and the control goes out of the switch block.

While loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be executed multiple times depending upon a given boolean condition. It can be viewed as a repeating if statement. The while loop is mostly used in the case where the number of iterations is not known in advance. The while loop evaluates the test expression inside the parentheses (). If test expression is true, statements inside the body of while loop are executed. Then, test expression is evaluated again. The process goes on until test expression is evaluated to false. If test expression is false, the loop terminates.

In the C Programming Language, the #define directive allows the definition of macros within your source code. These macro definitions allow constant values to be declared for use throughout your code. Macro definitions are not variables and cannot be changed by your program code like variables. You generally use this syntax when creating constants that represent numbers, strings or expressions.

The free() function in C library allows you to release or deallocate the memory blocks which are previously allocated by calloc(), malloc() or realloc() functions. It frees up the memory blocks and returns the memory to heap. It helps freeing the memory in your program which will be available for later use. In C, the memory for variables is automatically deallocated at compile time. For dynamic memory allocation in C, you have to deallocate the memory explicitly. If not done, you may encounter out of memory error.

The sizeof() operator is commonly used in C. It determines the size of the expression or the data type specified in the number of char-sized storage units. The sizeof() operator contains a single operand which can be either an expression or a data typecast where the cast is data type enclosed within parenthesis. The data type cannot only be primitive data types such as integer or floating data types, but it can also be pointer data types and compound data types such as unions and structs.

In C, the "main" function is treated the same as every function, it has a return type (and in some cases accepts inputs via parameters). The only difference is that the main function is "called" by the operating system when the user runs the program. Thus the main function is always the first code executed when a program starts. main() function is a user defined, body of the function is defined by the programmer or we can say main() is programmer/user implemented function, whose prototype is predefined in the compiler. Hence we can say that main() in c programming is user defined as well as predefined because it's prototype is predefined. main() is a system (compiler) declared function whose defined by the user, which is invoked automatically by the operating system when program is being executed.

Writes the C string pointed by format to the standard output (stdout). If format includes format specifiers (subsequences beginning with %), the additional arguments following format are formatted and inserted in the resulting string replacing their respective specifiers. printf format string refers to a control parameter used by a class of functions in the input/output libraries of C programming language. The string is written in a simple template language: characters are usually copied literally into the function's output, but format specifiers, which start with a % character, indicate the location and method to translate a piece of data (such as a number) to characters. "printf" is the name of one of the main C output functions, and stands for "print formatted". printf format strings are complementary to scanf format strings, which provide formatted input (parsing). In both cases these provide simple functionality and fixed format compared to more sophisticated and flexible template engines or parsers,

Read formatted data from stdin. Reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments. The additional arguments should point to already allocated objects of the type specified by their corresponding format specifier within the format string. In C programming, scanf() is one of the commonly used function to take input from the user. The scanf() function reads formatted input from the standard input such as keyboards. The scanf() function enables the programmer to accept formatted inputs to the application or production code. Moreover, by using this function, the users can provide dynamic input values to the application.

Pointers in C are easy and fun to learn. Some C programming tasks are performed more easily with pointers, and other tasks, such as dynamic memory allocation, cannot be performed without using pointers. So it becomes necessary to learn pointers to become a perfect C programmer. Let's start learning them in simple and easy steps. As you know, every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory. Consider the following example, which prints the address of the variables defined. A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address. The general form of a pointer variable declaration is:

C Area of Circle. Ellipse in which the two axes are of equal length. Plane curve generated by one point moving at a constant distance from a fixed point. You can compute area of circle.



C Program Checks if the mouse pointer is over the button. Checks whether count=1 so as to display the button on the new position for only once. Creates a box and the box is...




C program, using recursion, performs a depth first search traversal. Depth-first search (DFS) is an algorithm for 'Traversing or Searching' a tree, 'tree structure' or graph. The concept of



C Language program code add two Complex numbers by passing structure to a function. In this program code, structures j1 and j2 are passed as an argument of function add(). The