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 > C on Unix Code Examples

A Program to utilize message queue for implementing the merge sort(Socket Programming)

/* A Program to utilize message queue for implementing the merge sort(Socket Programming) */ #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <sys/ipc.h> #include <sys/msg.h> #include <sys/wait.h> #include<stdlib.h> #include<stdio.h> #define MAXLINE 1000 struct mymesg { long mtype; int a[4]; }; void Merge(int a[],int mer[],int ct) { if(ct==0) { ct+=4; for(int i=1;i<=ct;i++) mer[i]=a[i]; } else { for(int i=1;i<=4;i++) { int j=1; while(a[i]>mer[j]&&j<=ct)j++; if(j>ct) mer[j]=a[i]; else { for(int k=ct;k>=j;k--) mer[k+1]=mer[k]; mer[j]=a[i]; } ct++; } } } int main() { int n,pid,mpid,sum,b[17],mer[17],num=16; mpid=msgget(12,0666|IPC_CREAT); system("clear"); printf("Elements are... "); for(int i=1;i<=num;i++) { b[i]=rand()%150; printf("%d ",b[i]); } printf(" "); int i,ct=1,gmax;n=4;sum=0;gmax=4; for(i=1;i<=n;i++) { struct mymesg ptr; ptr.mtype=1; pid=fork(); if (pid>0) { int k=0; printf("Group %d: ",i); for(int j=ct;j<=ct+gmax-1;j++) { ptr.a[++k]=b[j]; printf("%d ",ptr.a[k]); } printf(" "); msgsnd(mpid,&ptr,MAXLINE,IPC_NOWAIT); waitpid(pid,NULL,0); msgrcv(mpid,&ptr,MAXLINE,0,IPC_NOWAIT); printf("Sorted Sub-Group %d: ",i); for(int j=1;j<=gmax;j++) printf("%d ",ptr.a[j]); printf(" "); Merge(ptr.a,mer,ct-1); if(ct==num+1-gmax) break; ct+=gmax; continue; } else { msgrcv(mpid,&ptr,MAXLINE,0,IPC_NOWAIT); for(int j=1;j<=gmax;j++) { for(int k=1;k<=gmax-j;k++) { if(ptr.a[k]>ptr.a[k+1]) { int t=ptr.a[k+1]; ptr.a[k+1]=ptr.a[k]; ptr.a[k]=t; } } } ptr.mtype=2; msgsnd(mpid,&ptr,MAXLINE,IPC_NOWAIT); exit(0); } } printf("Merged Sorted Group.... "); for(int i=1;i<=num;i++) printf("%d ",mer[i]); printf(" "); return 0; }

The msgsnd() function operates on XSI message queues (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.224, Message Queue). It is unspecified whether this function interoperates with the realtime interprocess communication facilities defined in Realtime. The msgsnd() function shall send a message to the queue associated with the message queue identifier specified by msqid. The application shall ensure that the argument msgp points to a user-defined buffer that contains first a field of type long specifying the type of the message, and then a data portion that holds the data bytes of the message. The structure below is an example of what this user-defined buffer might look like:

The msgrcv() function reads a message from the queue associated with the message queue identifier specified by msqid and places it in the user-defined buffer pointed to by msgp. The argument msgp points to a user-defined buffer that must contain first a field of type long int that will specify the type of the message, and then a data portion that will hold the data bytes of the message. The structure below is an example of what this user-defined buffer might look like: The structure member mtype is the received message's type as specified by the sending process. The structure member mtext is the text of the message.

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.

#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.

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 continue statement in C programming works somewhat like the break statement. Instead of forcing termination, it forces the next iteration of the loop to take place, skipping any code in between. For the for loop, continue statement causes the conditional test and increment portions of the loop to execute. For the while and do...while loops, continue statement causes the program control to pass to the conditional tests.

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.

Execute system command. Invokes the command processor to execute a command. If command is a null pointer, the function only checks whether a command processor is available through this function, without invoking any command. The effects of invoking a command depend on the system and library implementation, and may cause a program to behave in a non-standard manner or to terminate.

The msgget() function operates on XSI message queues (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.224, Message Queue). It is unspecified whether this function interoperates with the realtime interprocess communication facilities defined in Realtime. The msgget() function shall return the message queue identifier associated with the argument key.

wait for a process to exit. Wait for the process specified by pid to exit, and return its exit code in the integer pointed to by status. If that process has exited already, waitpid returns immediately. If that process does not exist, waitpid fails. What it means for a process to move from "has exited already" to "does not exist", and when this occurs, is something you must decide. If process P is "interested" in the exit code of process Q, process P should be able to find out that exit code by calling waitpid, even if Q exits somewhat before the time P calls waitpid. As described under _exit(), precisely what is meant by "interested" is up to you. You might implement restrictions or requirements on who may wait for which processes, like Unix does. You might also add a system call for one process to express interest in another process's exit code. If you do this, be sure to write a man page for the system call, and discuss the rationale for your choices therein in your design document.

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,

Generate random number. Returns a pseudo-random integral number in the range between 0 and RAND_MAX. This number is generated by an algorithm that returns a sequence of apparently non-related numbers each time it is called. This algorithm uses a seed to generate the series, which should be initialized to some distinctive value using function srand.

Assignment operators are used to assign the value, variable and function to another variable. Assignment operators in C are some of the C Programming Operator, which are useful to assign the values to the declared variables. Let's discuss the various types of the assignment operators such as =, +=, -=, /=, *= and %=. The following table lists the assignment operators supported by the C language: Simple assignment operator. Assigns values from right side operands to left side operand. Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand.

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.

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.

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.

C Program code finds the sum of the main & opposite diagonal elements of a MxN Matrix. The program accepts an MxN matrix. Then adds main diagonal of matrix as well as the

A number is called as "Armstrong Number" if Sum of Cubes of Digits of Number is equal to the number itself. In C code, we are checking the input number is Armstrong or not. Check

C Code replace first occurrence of a character with another in a string. Input the string from user, store it in some variable say 'str'. Input a character to replace, character new character

C Language Program calculates the Area of a Circle given it's Radius. Lets use The formula to compute the 'area' is: Area = ? x r2 where r is the radius of the circle & ? value is 22/7. 'Pi'

'StrrChr' is similar to the function 'StrChr', the only difference is that it searches the string in "Reverse Order", would have understood why we have extra r in 'strrchr', yes you guessed it