C Program to convert IP address to 32-bit long int

C Program to convert IP address to 32-bit long int. Internet Protocol Address is the unique number assigned to the each device, which is connected to the computer network. Previously we are using IPv4 versions, now we are using IPv6. Here we read the ip address using unions, and converted that to the 32-bit long int. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
union iptolint
{
char ip[16];
unsigned long int n;
};
unsigned long int conv(char []);

main()
{
union iptolint ipl;
printf(" Read the IP Address to be convertedn");
scanf("%s",ipl.ip);
ipl.n=conv(ipl.ip);
printf(" Equivalent 32-bit long int is : %lun",ipl.n);
}

unsigned long int conv(char ipadr[])
{
unsigned long int num=0,val;
char *tok,*ptr;
tok=strtok(ipadr,".");
while( tok != NULL)
{
val=strtoul(tok,&ptr,0);
num=(num << 8) + val;
tok=strtok(NULL,".");
}
return(num);
}

Read more Similar C Programs
Array In C

Simple C Programs

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

(c) www.c-program-example.com

C Program to do the operations of Sequential file with records.

C Program to do the operations of Sequential file with records. Sequential file, A file which consists of the same record types that is stored on a secondary storage device. The physical sequence of records may be based upon sorting values of one or more data items or fields. Here we are creating, Reading, searching the sequential file, using c file i/o operations. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/


#include <stdio.h>
typedef struct
{
int usn;
char name[25];
int m1,m2,m3;
}STD;

STD s;

void display(FILE *);
int search(FILE *,int);

void main()
{
int i,n,usn_key,opn;
FILE *fp;
printf(" How many Records ? ");
scanf("%d",&n);
fp=fopen("stud.dat","w");
for(i=0;i<n;i++)
{
printf("Read the Info for Student: %d (usn,name,m1,m2,m3) n",i+1);
scanf("%d%s%d%d%d",&s.usn,s.name,&s.m1,&s.m2,&s.m3);
fwrite(&s,sizeof(s),1,fp);
}
fclose(fp);
fp=fopen("stud.dat","r");
do
{
printf("Press 1- Displayt 2- Searcht 3- Exitt Your Option?");
scanf("%d",&opn);
switch(opn)
{
case 1: printf("n Student Records in the File n");
display(fp);
break;
case 2: printf(" Read the USN of the student to be searched ?");
scanf("%d",&usn_key);
if(search(fp,usn_key))
{
printf("Success ! Record found in the filen");
printf("%dt%st%dt%dt%dn",s.usn,s.name,s.m1,s.m2,s.m3);
}
else
printf(" Failure!! Record with USN %d not foundn",usn_key);
break;
case 3: printf(" Exit!! Press a key . . .");
getch();
break;
default: printf(" Invalid Option!!! Try again !!!n");
break;
}
}while(opn != 3);
fclose(fp);
} /* End of main() */

void display(FILE *fp)
{
rewind(fp);
while(fread(&s,sizeof(s),1,fp))
printf("%dt%st%dt%dt%dn",s.usn,s.name,s.m1,s.m2,s.m3);
}
int search(FILE *fp, int usn_key)
{
rewind(fp);
while(fread(&s,sizeof(s),1,fp))
if( s.usn == usn_key) return 1;
return 0;
}





Read more Similar C Programs
C Basic

C File i/o

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

(c) www.c-program-example.com

C Program to compare two strings

This C program compares two strings and tells you whether they are equal, or whether the first is lexicographically (dictionary order) greater than or less than the second. Comparison works character by character: it walks both strings together until two characters differ or a string ends, then decides the result from the first differing character. In this tutorial you’ll see a clean manual comparison and the standard library shortcut, strcmp().

The Program

#include <stdio.h>
#include <string.h>

int main(void)
{
    char str1[100], str2[100];
    int i = 0, result;

    printf("Enter the first string  : ");
    fgets(str1, sizeof(str1), stdin);
    printf("Enter the second string : ");
    fgets(str2, sizeof(str2), stdin);

    /* fgets keeps the trailing newline, so remove it. */
    str1[strcspn(str1, "\n")] = '\0';
    str2[strcspn(str2, "\n")] = '\0';

    /* Walk both strings until characters differ or one ends. */
    while (str1[i] != '\0' && str2[i] != '\0' && str1[i] == str2[i])
        i++;

    result = str1[i] - str2[i];   /* difference of first mismatching chars */

    if (result == 0)
        printf("The two strings are equal.\n");
    else if (result < 0)
        printf("\"%s\" is less than \"%s\".\n", str1, str2);
    else
        printf("\"%s\" is greater than \"%s\".\n", str1, str2);

    return 0;
}

How the Program Works

  • We read both strings with fgets, which (unlike the old gets()) will never overflow the buffer. fgets keeps the newline, so we strip it with strcspn.
  • The while loop advances i as long as both strings still have characters and those characters match.
  • When the loop stops, str1[i] - str2[i] is the difference of the first characters that differ (comparing their ASCII values). Zero means the strings matched all the way to the end.
  • A negative result means str1 comes first alphabetically; positive means it comes later.

This is a modernised version of the classic example — it removes void main(), <conio.h>, clrscr(), gets(), and fixes the original str1[i] != '' bug ('' is an invalid empty character constant; the correct null terminator is '\0').

The Standard Way: strcmp()

In real code you would simply use strcmp() from <string.h>, which does exactly this comparison and returns the same kind of value (negative, zero, or positive):

int result = strcmp(str1, str2);
if (result == 0)      printf("Equal\n");
else if (result < 0)  printf("str1 is smaller\n");
else                  printf("str1 is greater\n");

Sample Output

Enter the first string  : apple
Enter the second string : apricot
"apple" is less than "apricot".

Enter the first string  : hello
Enter the second string : hello
The two strings are equal.

For a clear treatment of strings, pointers and the standard library, The C Programming Language by Kernighan and Ritchie is the classic reference — find it on Amazon.

This post contains affiliate links. If you buy through them, we may earn a small commission at no extra cost to you.

Related C Programs

Try it instantly in one of the best online C compilers, or set up a local toolchain with our complete C development environment guide.

C Program to demonstrate time functions.

C Program to demonstrate time functions. time.h library function is used to get and manipulate date and time functions. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/



#include <stdio.h> /* NULL */
#include <time.h> /* ctime, asctime */

main()
{
time_t now; /* define 'now'. time_t is probably
* a typedef */

/* Calender time is the number of
* seconds since 1/1/1970 */

now = time((time_t *)NULL); /* Get the system time and put it
* into 'now' as 'calender time' */

printf("%s", ctime(&now)); /* Format data in 'now'
* NOTE that 'ctime' inserts a
* 'n' */

/*********************************************************************/

/* Here is another way to extract the time/date information */

time(&now);

printf("%s", ctime(&now)); /* Format data in 'now' */

/*********************************************************************/

{
struct tm *l_time;

l_time = localtime(&now); /* Convert 'calender time' to
* 'local time' - return a pointer
* to the 'tm' structure. localtime
* reserves the storage for us. */
printf("%s", asctime(l_time));
}

/*********************************************************************/

time(&now);
printf("%s", asctime(localtime( &now )));

/*********************************************************************/

{
struct tm *l_time;
char string[20];

time(&now);
l_time = localtime(&now);
strftime(string, sizeof string, "%d-%b-%yn", l_time);
printf("%s", string);
}


}
Read more Similar C Programs
Learn C Programming

Simple C Programs

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

(c) www.c-program-example.com

C Program to demonstrate macros.

C Program to demonstrate macros. Macro is a piece of text that is expanded by the preprocessor part of the compiler. This is used in to expand text before compiling. Macro definitions (#define), and conditional inclusion (#if). In many C implementations, it is a separate program invoked by the compiler as the first part of translation.Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include<stdio.h>
#define SQUARE(x) x*x

main()
{
int value=3;

printf("%d n", SQUARE(value));
}
Read more Similar C Programs
Learn C Programming

Number System

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

(c) www.c-program-example.com

C Program to demonstrate goto statement

The goto statement in C is an unconditional jump that transfers program control directly to a labelled statement within the same function. While modern C style discourages it, goto is still useful in a few real situations — most commonly for breaking out of deeply nested loops and for centralised cleanup/error handling. In this tutorial you will learn the syntax of goto, see a clean, working example, and understand when (and when not) to use it.

Syntax of goto

The goto statement needs a label — an identifier followed by a colon — somewhere in the same function:

goto label;
...
label:
    statement;

When execution reaches goto label;, control jumps straight to label: and continues from there.

Example: Guarding Against Divide-by-Zero

A classic teaching example is to use goto to skip a division when the divisor is zero, jumping to a single exit point. Here is a clean, portable version that compiles on any standard C compiler:

#include <stdio.h>

int main(void)
{
    double num1, num2;

    printf("Enter the first number : ");
    if (scanf("%lf", &num1) != 1) {
        printf("Invalid input.\n");
        return 1;
    }

    printf("Enter the second number : ");
    if (scanf("%lf", &num2) != 1) {
        printf("Invalid input.\n");
        return 1;
    }

    /* Use goto to skip the division when the divisor is zero. */
    if (num2 == 0.0)
        goto divide_error;

    printf("%.2f divided by %.2f is %.2f\n", num1, num2, num1 / num2);
    return 0;

divide_error:
    printf("Error: cannot divide by zero.\n");
    return 1;
}

How the Program Works

  • The program reads two numbers using scanf. The %lf format specifier reads a double, and we check its return value to make sure the input was valid.
  • If the second number is 0.0, the condition if (num2 == 0.0) is true and goto divide_error; jumps past the division straight to the divide_error: label.
  • Otherwise the division is performed and the result is printed, and the program returns before ever reaching the label.
  • The divide_error: label acts as a single, clearly named exit point for the error case.

Notice that this modern version replaces the old, unsafe gets() call from textbook examples with scanf and input validation — gets() was removed from the C standard in C11 because it can overflow buffers.

Sample Output

Enter the first number : 22
Enter the second number : 7
22.00 divided by 7.00 is 3.14

Enter the first number : 10
Enter the second number : 0
Error: cannot divide by zero.

When Should You Use goto?

Situation Is goto a good idea?
Breaking out of deeply nested loops Acceptable — often cleaner than multiple flag variables
Centralised error cleanup (freeing resources) Common in C, used heavily in the Linux kernel
Ordinary loops and branching No — use for, while, if/else instead
Jumping backwards to create a loop No — it produces hard-to-read “spaghetti code”

As a rule of thumb: prefer structured control flow (for, while, break, continue) and reach for goto only for forward jumps to a single cleanup point. For a deeper discussion of control flow and good C style, The C Programming Language by Kernighan and Ritchie remains the definitive reference — see K&R on Amazon.

This post contains affiliate links. If you buy through them, we may earn a small commission at no extra cost to you.

Related C Programs

If you don’t want to install a compiler just to try this out, you can paste the code straight into one of the best online C compilers and run it in your browser. When you’re ready for a proper local setup, follow our guide to building a complete C development environment.

C Program to Demonstrate global and internal variables.

C Program to Demonstrate global and internal variables.When variable declared outside the all the blocks, they are called global variables, and they are initialized by the system. Variables declared within the functions are called as internal variables, the are locale to that function, and user only initialize the variable. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/


#include<stdio.h>

int counter = 0; /* global because we are outside
all blocks. */
int func(void);

main()
{
counter++; /* global because it has not been
declared within this block */
printf("counter is %2d before the call to funcn", counter);

func(); /* call a function. */

printf("counter is %2d after the call to funcn", counter);
}

int func(void)
{
int counter = 10; /* local. */
printf("counter is %2d within funcn", counter);
}
Read more Similar C Programs
Learn C Programming

Number System

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

(c) www.c-program-example.com

C Program to demonstrate Enumeration.

C Program to demonstrate Enumeration. An enum(Enumeration) is a user-defined type consisting of a set of named constants called enumerators. This Program will return the month in a year. I.E. It returns 9 for September. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/



#include<stdio.h>
main()
{
/*
* Define a list of aliases
*/
enum months {Jan=1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};
/* A A
| |
| |
| ------- list of aliases.
-------------- Enumeration tag. */


enum months month; /* define 'month' variable of type 'months' */

printf("%dn", month=Sep); /* Assign integer value via an alias
* This will return a 9 */
}
Read more Similar C Programs
Learn C Programming

Number System

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

(c) www.c-program-example.com

C Program to demonstrate the ‘do’ statement.

C Program to demonstrate the ‘do’ statement. The C do while statement creates a structured loop that executes as long as a specified condition is true at the end of each pass through the loop. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/


#include <stdio.h>

main()
{
int i=1; /* Define an integer variable. */

/*
* The block is executed. Then the i <= 10
* expression is evaluated. If TRUE the block
* is executed again.
*/
do
{
printf ("i is %in", i);
i++;
} while (i <= 10);

}
Read more Similar C Programs
Learn C Programming

Number System

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

(c) www.c-program-example.com

C program to Demonstrate the #define pre-processor.

C Program to demonstrate #define pre-processor. Macro is a piece of text that is expanded by the pre-processor part of the compiler. This is used in to expand text before compiling. Macro definitions (#define), and conditional inclusion (#if). In many C implementations, it is a separate program invoked by the compiler as the first part of translation.Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/


#define EQ ==

main ()
{
/* the EQ is translated to == by
* the C pre-processor. COOL!
*/
if ( 5 EQ 5 ) printf("define works...n");
}
Read more Similar C Programs
Learn C Programming

Number System

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

(c) www.c-program-example.com