C Programming Code Examples
C > Beginners Lab Assignments Code Examples
C Program to Find the Common Ancestor and Print the Path
/* C Program to Find the Common Ancestor and Print the Path */
/*
*
* 10
* / \
* 7 15
* / \ / \
* 6 8 12 18
* / \
* 5 9
* (Given Binary tree)
*/
#include <stdio.h>
#include <stdlib.h>
struct btnode
{
int value;
struct btnode *l;
struct btnode *r;
};
typedef struct btnode N;
N* new(int);
int count;
void create();
void preorder(N *t);
void ancestor(N *t);
int search(N *t, int, int);
void path(int, int, int);
N *root = NULL;
void main()
{
int choice;
create();
while (1)
{
printf("Enter the choice\n");
printf("1-Display : 2-path : 3-Exit\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("preorder display of tree elements\n");
preorder(root);
printf("\n");
break;
case 2:
ancestor(root);
break;
case 3:
exit(0);
default:
printf("Enter the right choice\n");
}
}
}
/* creating temporary node */
N* new(int data)
{
N* temp = (N*)malloc(sizeof(N));
temp->value = data;
temp->l = NULL;
temp->r = NULL;
return(temp);
}
/* Creating the binary search tree */
void create()
{
root = new(10);
root->l = new(7);
root->r = new(15);
root->l->l = new(6);
root->l->r = new(8);
root->r->l = new(12);
root->r->r = new(18);
root->r->r->r = new(20);
root->l->l->l = new(5);
root->l->r->r = new(9);
}
/* To display the preorder traversal of the tree */
void preorder(N *temp)
{
printf("%d->", temp->value);
if (temp->l != NULL)
preorder(temp->l);
if (temp->r != NULL)
preorder(temp->r);
}
/* to find common ancestor for given nodes */
void ancestor(N *temp)
{
int a, b, anc = 0;
count = 0;
printf("enter two node values to find common ancestor\n");
scanf("%d", &a);
scanf("%d", &b);
count = search(root, a, b);
if (count == 2)
{
while (temp->value != a && temp->value != b)
{
if ((temp->value > a)&&(temp->value > b))
{
anc = temp->value;
temp = temp->l;
}
else if ((temp->value < a)&&(temp->value < b))
{
anc = temp->value;
temp = temp->r;
}
else if ((temp->value > a)&&(temp->value < b))
{
anc = temp->value;
printf("anc = %d\n", anc);
break;
}
else if ((temp->value < a)&&(temp->value > b))
{
anc = temp->value;
temp = temp->r;
}
else
{
printf("common ancestor = %d\n", anc);
break;
}
}
path(anc, a, b);
}
else
printf("enter correct node values & do not enter root value\n");
}
/* to find whether given nodes are present in tree or not */
int search(N *temp, int a, int b)
{
if ((temp->value == a ||temp->value == b)&& (root->value != a&&root->value != b))
{
count++;
}
if (temp->l != NULL)
search(temp->l, a, b);
if (temp->r != NULL)
search(temp->r, a, b);
return count;
}
/* to print the path ancestor to given nodes */
void path(int anc, int c, int b)
{
N *temp = NULL;
int j = 0, a[2];
a[0] = c;
a[1] = b;
for (;j < 2;j++)
{
if (anc == root->value) // If ancestor is root
{
temp = root;
while (1)
{
printf("%d", temp->value);
if (a[j] < temp->value)
temp = temp->l;
else if (a[j] > temp->value)
temp = temp->r;
else
{
if (a[j] == temp->value)
{
break;
}
}
printf("->");
}
printf("\n");
}
else if (anc < root->value) //If ancestor is less than the root value
{
temp = root;
while (temp != NULL)
{
if (anc < temp->value)
temp = temp->l;
else if (anc > temp->value)
temp = temp->r;
else
{
while (1)
{
if (a[j] < temp->value)
{
printf("%d->", temp->value);
temp = temp->l;
}
else if (a[j] > temp->value)
{
printf("%d->", temp->value);
temp = temp->r;
}
else
{
printf("%d\n", temp->value);
break;
}
}
}
}
}
else //If ancestor greater than the root value
{
temp = root;
while (temp != NULL)
{
if (anc > temp->value)
temp = temp->r;
else if (anc < temp->value)
temp = temp->l;
else
{
while (1)
{
if (a[j] < temp->value)
{
printf("%d->", temp->value);
temp = temp->l;
}
else if (a[j] > temp->value)
{
printf("%d->", temp->value);
temp = temp->r;
}
else
{
printf("%d\n", temp->value);
break;
}
}
}
}
}
}
}
An expression containing logical operator returns either 0 or 1 depending upon whether expression results true or false. Logical operators are commonly used in decision making in C programming. These operators are used to perform logical operations and used with conditional statements like C if-else statements.
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,
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.
The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities. The if...else ladder allows you to check between multiple test expressions and execute different statements. In C/C++ if-else-if ladder helps user decide from among multiple options. The C/C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
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.
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.
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.
#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 for loop is used in the case where we need to execute some part of the code until the given condition is satisfied. The for loop is also called as a per-tested loop. It is better to use for loop if the number of iteration is known in advance. The for-loop statement is a very specialized while loop, which increases the readability of a program. It is frequently used to traverse the data structures like the array and linked list.
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.
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.
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.
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.
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.
The typedef is a keyword used in C programming to provide some meaningful names to the already existing variable in the C program. It behaves similarly as we define the alias for the commands. In short, we can say that this keyword is used to redefine the name of an already existing variable.
C program Returns nonzero if ch is a white-space character, including space, horizontal tab, vertical tab, formfeed, carriage return, or newline character; otherwise zero is return.
Before accepting the Elements Check if no of rows and columns of both matrices is equal. Accept the Elements in Matrix 1 and Matrix 2. Addition of two matrices. Print out the matrix
Print an array in reverse order, we shall know the length of the array in advance. We can start an iteration from length value of array to zero and in each iteration we can print...
C code Print the 'Factorial' of a given number. A factorial is product of all the numbers from 1 to n, where n is the 'specified number'. This C program find the product of all the number
Create a structure. The name of the structure is StudentData. The Student is the variable of structure StudentData. Assigning the values of each struct member here. Displaying the...