0% found this document useful (0 votes)
39 views

C Material Part3

Union in C allows different data types to share the same memory location. Only one member can contain a value at a time. The size of a union is determined by its largest member. Pointers can be used to access union members and pass unions to functions. File handling in C enables programs to create, read, write and delete files for persistent storage beyond the life of the program.

Uploaded by

Niranjan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

C Material Part3

Union in C allows different data types to share the same memory location. Only one member can contain a value at a time. The size of a union is determined by its largest member. Pointers can be used to access union members and pass unions to functions. File handling in C enables programs to create, read, write and delete files for persistent storage beyond the life of the program.

Uploaded by

Niranjan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Union in C

Union can be defined as a user-defined data type which is a collection of different variables of


different data types in the same memory location. The union can also be defined as many
members, but only one member can contain a value at a particular point in time.

Union is a user-defined data type, but unlike structures, they share the same memory location.

struct abc  
{  
   int a;  
   char b;   
}   

The above code is the user-defined structure that consists of two members, i.e., 'a' of type int and
'b' of type character. When we check the addresses of 'a' and 'b', we found that their addresses
are different. Therefore, we conclude that the members in the structure do not share the same
memory location.

When we define the union, then we found that union is defined in the same way as the
structure is defined but the difference is that union keyword is used for defining the union
data type, whereas the struct keyword is used for defining the structure. The union contains
the data members, i.e., 'a' and 'b', when we check the addresses of both the variables then
we found that both have the same addresses. It means that the union members share the
same memory location.

In union, members will share the memory location. If we try to make changes in any of the
member then it will be reflected to the other member as well

union abc  
{  
   int a;  
char b;   
}var;  
int main()  
{  
  var.a = 66;  
  printf("\n a = %d", var.a);  
  printf("\n b = %d", var.b);  
}   

n the above code, union has two members, i.e., 'a' and 'b'. The 'var' is a variable of union abc type.
In the main() method, we assign the 66 to 'a' variable, so var.a will print 66 on the screen. Since
both 'a' and 'b' share the memory location, var.b will print 'B' (ascii code of 66).
Deciding the size of the union
The size of the union is based on the size of the largest member of the union.

union abc{  
int a;  
char b;  
float c;  
double d;  
};  
int main()  
{  
  printf("Size of union abc is %d", sizeof(union abc));  
  return 0;  
}  

As we know, the size of int is 4 bytes, size of char is 1 byte, size of float is 4 bytes, and the
size of double is 8 bytes. Since the double variable occupies the largest memory among all
the four variables, so total 8 bytes will be allocated in the memory. Therefore, the output of
the above program would be 8 bytes.

Accessing members of union using pointers

We can access the members of the union through pointers by using the (->) arrow
operator.

Example.

#include <stdio.h>  
union abc  
{  
    int a;  
    char b;  
};  
int main()  
{  
    union abc *ptr; // pointer variable declaration  
    union abc var;  
    var.a= 90;  
    ptr = &var;  
    printf("The value of a is : %d", ptr->a);  
    return 0;  
}  
C Pointers
The pointer in C language is a variable which stores the address of another variable. This variable
can be of type int, char, array, function, or any other pointer. The size of the pointer depends on
the architecture. However, in 32-bit architecture the size of a pointer is 2 byte.

Consider the following example to define a pointer which stores the address of an integer.

int n = 10;   
int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type in
teger.   

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol). It is also known as
indirection pointer used to dereference a pointer.

1. int *a;//pointer to int  
2. char *c;//pointer to char  

Pointer Example
An example of using pointers to print the address and value is given below.

As you can see in the above figure, pointer variable stores the address of number variable, i.e.,
fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

As you can see in the above figure, pointer variable stores the address of number variable, i.e.,
fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

Pointer example as explained for the above figure.

#include<stdio.h>  
int main(){  
int number=50;    
int *p;      
p=&number;//stores the address of number variable    
printf("Address of p variable is %x \n",p); // p contains the address of the number therefore printing 
p gives the address of number.     
printf("Value of p variable is %d \n",*p); // As we know that * is used to dereference a pointer therefo
re if we print *p, we will get the value stored at the address contained by p.    
return 0;  
}    

Pointer to array
int arr[10];  
int *p[10]=&arr; // Variable p of type pointer is pointing to the address of an integer array arr.  

Pointer to a function
void show (int);  
void(*p)(int) = &display; // Pointer p is pointing to the address of a function  

Pointer to structure
struct st {  
    int i;  
    float f;  
}ref;  
struct st *p = &ref;  

Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings,
trees, etc. and used with arrays, structures, and functions.

2) We can return multiple values from a function using the pointer.

3) It makes you able to access any memory location in the computer's memory.

Usage of pointer
There are many applications of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions where
the pointer is used.

2) Arrays, Functions, and Structures

Pointers in c language are widely used in arrays, functions, and structures. It reduces the code and
improves the performance.
Address Of (&) Operator
The address of operator '&' returns the address of a variable. But, we need to use %u to display
the address of a variable.

#include<stdio.h>  
int main(){  
int number=50;   
printf("value of number is %d, address of number is %u",number,&number);    
return 0;  

Pointer Program to swap two numbers without using the 3rd


variable.
#include<stdio.h>  
int main(){  
int a=10,b=20,*p1=&a,*p2=&b;  
  
printf("Before swap: *p1=%d *p2=%d",*p1,*p2);  
*p1=*p1+*p2;  
*p2=*p1-*p2;  
*p1=*p1-*p2;  
printf("\nAfter swap: *p1=%d *p2=%d",*p1,*p2);  
  
return 0;  
}  
Pointers to functions

Pointers give greatly possibilities to 'C' functions which we are limited to return one
value. With pointer parameters, our functions now can process actual data rather than
a copy of data.
In order to modify the actual values of variables, the calling statement passes
addresses to pointer parameters in a function.
#include,stdio.h>
void swap (int *a, int *b);
int main() {
int m = 25;
int n = 100;
printf("m is %d, n is %d\n", m, n);
swap(&m, &n);
printf("m is %d, n is %d\n", m, n);
return 0;}
void swap (int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;}
}
Pointers to Arrays
#include <stdio.h>

int main () {

/* an array with 5 elements */


double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p;
int i;

p = balance;
/* output each array element's value */
printf( "Array values using pointer\n");
for ( i = 0; i < 5; i++ ) {
printf("*(p + %d) : %f\n", i, *(p + i) );
}

printf( "Array values using balance as address\n");


for ( i = 0; i < 5; i++ ) {
printf("*(balance + %d) : %f\n", i, *(balance + i) );
}
return 0;
}

Pointers to strings
#include<stdio.h>
Void main()
{
Char s[20],t[20];
Printf(“\n Enter a string”);
gets(s);
sc(t,c);
printf(“\n source=%s \t Target=%s’,s,t);
}
Void sc(char *t1,char *s1)
{
While (*s1!=’\0’’)
{
*t1=*s1;
*t1++;
*s1++;
}
*t1=0;
}
Pointers to structures

#include <stdio.h>
struct person
{
int age;
float weight;
};

int main()
{
struct person *personPtr, person1;
personPtr = &person1;

printf("Enter age: ");


scanf("%d", &personPtr->age);

printf("Enter weight: ");


scanf("%f", &personPtr->weight);

printf("Displaying:\n");
printf("Age: %d\n", personPtr->age);
printf("weight: %f", personPtr->weight);

return 0;
}

File Handling in C
In programming, we may require some specific input data to be generated several numbers of
times. Sometimes, it is not enough to only display the data on the console. The data to be
displayed may be very large, and only a limited amount of data can be displayed on the console,
and since the memory is volatile, it is impossible to recover the programmatically generated data
again and again. However, if we need to do so, we may store it onto the local file system which is
volatile and can be accessed every time. Here, comes the need of file handling in C.

File handling in C enables us to create, update, read, and delete the files stored on the local file
system through our C program.
The following operations can be performed on a file.

o Creation of the new file


o Opening an existing file
o Reading from the file
o Writing to the file
o Deleting the file

Functions for file handling


There are many functions in the C library to open, read, write, search and close the file. A list of
file functions are given below:

No. Function Description

1 fopen() opens new or existing file

2 fprintf() write data into the file

3 fscanf() reads data from the file

4 fputc() writes a character into the file

5 fgetc() reads a character from file

6 fclose() closes the file

7 fseek() sets the file pointer to given position

8 fputw() writes an integer to file

9 fgetw() reads an integer from file

10 ftell() returns current position

11 rewind() sets the file pointer to the beginning of the file

Opening File: fopen()


We must open a file before it can be read, write, or update. The fopen() function is used to open a
file.

The syntax of the fopen() is given below.

FILE *fopen( const char * filename, const char * mode );  

The fopen() function accepts two parameters:

o The file name (string). If the file is stored at some specific location, then we must mention
the path at which the file is stored. For example, a file name can be
like "c://some_folder/some_file.ext".
o The mode in which the file is to be opened. It is a string.
We can use one of the following modes in the fopen() function.

Mode Description

r opens a text file in read mode

w opens a text file in write mode

a opens a text file in append mode

r+ opens a text file in read and write mode

w+ opens a text file in read and write mode

a+ opens a text file in read and write mode

rb opens a binary file in read mode

wb opens a binary file in write mode

ab opens a binary file in append mode

rb+ opens a binary file in read and write mode

wb+ opens a binary file in read and write mode

ab+ opens a binary file in read and write mode

The fopen function works in the following way.

o Firstly, It searches the file to be opened.


o Then, it loads the file from the disk and place it into the buffer. The buffer is used to provide
efficiency for the read operations.
o It sets up a character pointer which points to the first character of the file.

Example which opens a file in write mode.

#include<stdio.h>  
void main( )  
{  
FILE *fp ;  
char ch ;  
fp = fopen("file_handle.c","r") ;  
while ( 1 )  
{  
ch = fgetc ( fp ) ;  
if ( ch == EOF )  
break ;  
printf("%c",ch) ;  
}  
fclose (fp ) ;  
}  
Closing File: fclose()
The fclose() function is used to close a file. The file must be closed after performing all the
operations on it.

The syntax of fclose() function is given below:

int fclose( FILE *fp );  

C fprintf() and fscanf()

Writing File : fprintf() function


The fprintf() function is used to write set of characters into file. It sends formatted output to a
stream.

Syntax:

int fprintf(FILE *stream, const char *format [, argument, ...])  

Example:

#include <stdio.h>  
main(){  
   FILE *fp;  
   fp = fopen("file.txt", "w");//opening file  
   fprintf(fp, "Hello file by fprintf...\n");//writing data into file  
   fclose(fp);//closing file  
}  

Reading File : fscanf() function


The fscanf() function is used to read set of characters from file. It reads a word from the file and
returns EOF at the end of file.

Syntax:

int fscanf(FILE *stream, const char *format [, argument, ...])  

Example:

#include <stdio.h>  
main(){  
   FILE *fp;  
   char buff[255];//creating char array to store data of file  
   fp = fopen("file.txt", "r");  
   while(fscanf(fp, "%s", buff)!=EOF){  
   printf("%s ", buff );  
   }  
   fclose(fp);  
}  
C File Example: Storing employee information
Let's see a file handling example to store employee information as entered by user from console.
We are going to store id, name and salary of the employee.

#include <stdio.h>  
void main()  
{  
    FILE *fptr;  
    int id;  
    char name[30];  
    float salary;  
    fptr = fopen("emp.txt", "w+");/*  open for writing */  
    if (fptr == NULL)  
    {  
        printf("File does not exists \n");  
        return;  
    }  
    printf("Enter the id\n");  
    scanf("%d", &id);  
    fprintf(fptr, "Id= %d\n", id);  
    printf("Enter the name \n");  
    scanf("%s", name);  
    fprintf(fptr, "Name= %s\n", name);  
    printf("Enter the salary\n");  
    scanf("%f", &salary);  
    fprintf(fptr, "Salary= %.2f\n", salary);  
    fclose(fptr);  
}  

C fputc() and fgetc()

Writing File : fputc() function


The fputc() function is used to write a single character into file. It outputs a character to a stream.

Syntax:

1. int fputc(int c, FILE *stream)  

Example:

#include <stdio.h>  
main(){  
   FILE *fp;  
   fp = fopen("file1.txt", "w");//opening file  
   fputc('a',fp);//writing single character into file  
   fclose(fp);//closing file  
}  

Reading File : fgetc() function


The fgetc() function returns a single character from the file. It gets a character from the stream. It
returns EOF at the end of file.

Syntax:

1. int fgetc(FILE *stream)

Example:

#include<stdio.h>  
#include<conio.h>  
void main(){  
FILE *fp;  
char c;  
clrscr();  
fp=fopen("myfile.txt","r");  
  
while((c=fgetc(fp))!=EOF){  
printf("%c",c);  
}  
fclose(fp);  
getch();  
}  

C fputs() and fgets()


The fputs() and fgets() in C programming are used to write and read string from stream. Let's see
examples of writing and reading file using fgets() and fgets() functions.

Writing File : fputs() function


The fputs() function writes a line of characters into file. It outputs string to a stream.

Syntax:

1. int fputs(const char *s, FILE *stream)  

Example:

#include<stdio.h>  
#include<conio.h>  
void main(){  
FILE *fp;  
clrscr();  
  
fp=fopen("myfile2.txt","w");  
fputs("hello c programming",fp);  
  
fclose(fp);  
getch();  
}

Reading File : fgets() function


The fgets() function reads a line of characters from file. It gets string from a stream.

Syntax:

char* fgets(char *s, int n, FILE *stream)  

Example:

#include<stdio.h>  
#include<conio.h>  
void main(){  
FILE *fp;  
char text[300];  
clrscr();  
  
fp=fopen("myfile2.txt","r");  
printf("%s",fgets(text,200,fp));  
  
fclose(fp);  
getch();  
}  

C fseek() function
The fseek() function is used to set the file pointer to the specified offset. It is used to write data
into file at desired location.

Syntax:

int fseek(FILE *stream, long int offset, int whence)  

There are 3 constants used in the fseek() function for whence: SEEK_SET, SEEK_CUR and
SEEK_END.

Example:

#include <stdio.h>  
void main(){  
   FILE *fp;  
  
   fp = fopen("myfile.txt","w+");  
   fputs("This is javatpoint", fp);  
    
   fseek( fp, 7, SEEK_SET );  
   fputs("sonoo jaiswal", fp);  
   fclose(fp);  
}

C rewind() function
The rewind() function sets the file pointer at the beginning of the stream. It is useful if you have to
use stream many times.

Syntax:

void rewind(FILE *stream)  

#include<stdio.h>  
#include<conio.h>  
void main(){  
FILE *fp;  
char c;  
clrscr();  
fp=fopen("file.txt","r");  
  
while((c=fgetc(fp))!=EOF){  
printf("%c",c);  
}  
  
rewind(fp);//moves the file pointer at beginning of the file  
  
while((c=fgetc(fp))!=EOF){  
printf("%c",c);  
}  
  
fclose(fp);    
getch();    
}    

C ftell() function
The ftell() function returns the current file position of the specified stream. We can use ftell()
function to get the total size of a file after moving file pointer at the end of file. We can use
SEEK_END constant to move the file pointer at the end of file.

Syntax:

long int ftell(FILE *stream)  
Example:

#include <stdio.h>  
#include <conio.h>  
void main (){  
   FILE *fp;  
   int length;  
   clrscr();  
   fp = fopen("file.txt", "r");  
   fseek(fp, 0, SEEK_END);  
  
   length = ftell(fp);  
  
   fclose(fp);  
   printf("Size of file: %d bytes", length);  
   getch();  
}  

Dynamic memory allocation in C


The concept of dynamic memory allocation in c language enables the C programmer to allocate
memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of
stdlib.h header file.

1. malloc()
2. calloc()
3. realloc()
4. free()

The difference between static memory allocation and dynamic memory allocation.

static memory allocation dynamic memory allocation

memory is allocated at compile time. memory is allocated at run time.

memory can't be increased while executing memory can be increased while executing
program program.

used in array. used in linked list.

The methods used for dynamic memory allocation.

malloc() allocates single block of requested memory.

calloc() allocates multiple block of requested memory.

realloc() reallocates the memory occupied by malloc() or calloc() functions.

free() frees the dynamically allocated memory.


malloc() function in C
The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

ptr=(cast-type*)malloc(byte-size)  

Example of malloc() function

#include<stdio.h>  
#include<stdlib.h>  
int main(){  
  int n,i,*ptr,sum=0;    
    printf("Enter number of elements: ");    
    scanf("%d",&n);    
    ptr=(int*)malloc(n*sizeof(int));  //memory allocated using malloc    
    if(ptr==NULL)                         
    {    
        printf("Sorry! unable to allocate memory");    
        exit(0);    
    }    
    printf("Enter elements of array: ");    
    for(i=0;i<n;++i)    
    {    
        scanf("%d",ptr+i);    
        sum+=*(ptr+i);    
    }    
    printf("Sum=%d",sum);    
    free(ptr);     
return 0;  
}    

calloc() function in C
The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

ptr=(cast-type*)calloc(number, byte-size)  
Example of calloc() function.

#include<stdio.h>  
#include<stdlib.h>  
int main(){  
 int n,i,*ptr,sum=0;    
    printf("Enter number of elements: ");    
    scanf("%d",&n);    
    ptr=(int*)calloc(n,sizeof(int));  //memory allocated using calloc    
    if(ptr==NULL)                         
    {    
        printf("Sorry! unable to allocate memory");    
        exit(0);    
    }    
    printf("Enter elements of array: ");    
    for(i=0;i<n;++i)    
    {    
        scanf("%d",ptr+i);    
        sum+=*(ptr+i);    
    }    
    printf("Sum=%d",sum);    
    free(ptr);    
return 0;  
}    

realloc() function in C
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc()
function. In short, it changes the memory size.

Syntax of realloc() function.

ptr=realloc(ptr, new-size)  

free() function in C
The memory occupied by malloc() or calloc() functions must be released by calling free() function.
Otherwise, it will consume memory until program exit.

Syntax of free() function.

free(ptr)  

Command Line Arguments in C


The arguments passed from command line are called command line arguments. These arguments
are handled by main() function.

To support command line argument, you need to change the structure of main() function as given
below.
int main(int argc, char *argv[] )  

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name always.

Example
Let's see the example of command line arguments where we are passing one argument with file
name.

#include <stdio.h>  
void main(int argc, char *argv[] )  {  
  
   printf("Program name is: %s\n", argv[0]);  
   
   if(argc < 2){  
      printf("No argument passed through command line.\n");  
   }  
   else{  
      printf("First argument is: %s\n", argv[1]);  
   }  

Run this program as follows in Linux:

1. ./program hello  

Run this program as follows in Windows from command line:

1. program.exe hello  

Output:

C Math
C Programming allows us to perform mathematical operations through the functions defined in
<math.h> header file. The <math.h> header file contains various methods for performing
mathematical operations such as sqrt(), pow(), ceil(), floor() etc.

C Math Functions
There are various methods in math.h header file. The commonly used functions of math.h header
file are given below.

No Function Description
.

1) ceil(number) rounds up the given number. It returns the integer value which is greater
than or equal to given number.
2) floor(number) rounds down the given number. It returns the integer value which is less
than or equal to given number.

3) sqrt(number) returns the square root of given number.

4) pow(base, returns the power of given number.


exponent)

5) abs(number) returns the absolute value of given number.

C Math Example

Example of math functions found in math.h header file

#include<stdio.h>  
#include <math.h>    
int main(){    
printf("\n%f",ceil(3.6));    
printf("\n%f",ceil(3.3));    
printf("\n%f",floor(3.6));    
printf("\n%f",floor(3.2));    
printf("\n%f",sqrt(16));    
printf("\n%f",sqrt(7));    
printf("\n%f",pow(2,4));    
printf("\n%f",pow(3,3));    
printf("\n%d",abs(-12));     
 return 0;    
}    

Enum in C
The enum in C is also known as the enumerated type. It is a user-defined data type that consists
of integer values, and it provides meaningful names to these values. The use of enum in C makes
the program easy to understand and maintain.

The enum is defined by using the enum keyword.

The following is the way to define the enum in C:

enum flag

{integer_const1, integer_const2,.....integter_constN};  

In the above declaration, we define the enum named as flag containing 'N' integer
constants. The default value of integer_const1 is 0, integer_const2 is 1, and so on. We can
also change the default value of the integer constants at the time of the declaration.
For example:

enum fruits{mango, apple, strawberry, papaya};  

enum fruits{  
mango=2,  
apple=1,  
strawberry=5,  
papaya=7,  
}; 

Enumerated type declaration


As we know that in C language, we need to declare the variable of a pre-defined type such as int,
float, char, etc. Similarly, we can declare the variable of a user-defined data type, such as enum.
Let's see how we can declare the variable of an enum type.

Suppose we create the enum of type status as shown below:

1. enum status{false,true};  

Now, we create the variable of status type:

1. enum status s; // creating a variable of the status type.  

In the above statement, we have declared the 's' variable of type status.

To create a variable, the above two statements can be written as:

1. enum status{false,true} s;  

In this case, the default value of false will be equal to 0, and the value of true will be equal to 1.

Program of enum.

#include <stdio.h>  
 enum weekdays{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};  
 int main()  
{  
 enum weekdays w; // variable declaration of weekdays type  
 w=Monday; // assigning value of Monday to w.  
 printf("The value of w is %d",w);  
    return 0;  
}  
Example to understand the enum more clearly.

#include <stdio.h>  
 enum months{jan=1, feb, march, april, may, june, july, august, september, october, november, dece
mber};  
int main()  
{  
// printing the values of months  
 for(int i=jan;i<=december;i++)  
 {  
 printf("%d, ",i);  
 }  
    return 0;  
}  

What is getch() in C?
The getch() is a predefined non-standard function that is defined in conio.h header file. It is
mostly used by the Dev C/C++, MS- DOS's compilers like Turbo C to hold the screen until the
user passes a single value to exit from the console screen. It can also be used to read a single byte
character or string from the keyboard and then print. It does not hold any parameters. It has no
buffer area to store the input character in a program.

Why we use a getch() function?


We use a getch() function in a C/ C++ program to hold the output screen for some time until the
user passes a key from the keyboard to exit the console screen. Using getch() function, we can
hide the input character provided by the users in the ATM PIN, password, etc.

Syntax:

int getch(void);  

Parameters: The getch() function does not accept any parameter from the user.

Return value: It returns the ASCII value of the key pressed by the user as an input.

Write a simple program to display the character entered by the user using the getch() function in
C.

Program.c

#include <stdio.h>   
#include <conio.h>   
int main()  
{  
       printf(" Passed value by the User is: %c", getch()); // print a character entered by the user  
    return 0;  
}  
Factorial Program using loop
#include<stdio.h>  
int main()    
{    
 int i,fact=1,number;    
 printf("Enter a number: ");    
  scanf("%d",&number);    
    for(i=1;i<=number;i++){    
      fact=fact*i;    
  }    
  printf("Factorial of %d is: %d",number,fact);    
return 0;  
}   

Factorial Program using recursion in C


#include<stdio.h>  
  
long factorial(int n)  
{  
  if (n == 0)  
    return 1;  
  else  
    return(n * factorial(n-1));  
}  
   
void main()  
{  
  int number;  
  long fact;  
  printf("Enter a number: ");  
  scanf("%d", &number);   
     fact = factorial(number);  
  printf("Factorial of %d is %ld\n", number, fact);  
  return 0;  
}  

Prime Number program in C


Prime number in C: Prime number is a number that is greater than 1 and divided by 1 or itself. In
other words, prime numbers can't be divided by other numbers than itself or 1. For example 2, 3,
5, 7, 11, 13, 17, 19, 23.... are the prime numbers.

#include<stdio.h>  
int main(){    
int n,i,m=0,flag=0;    
printf("Enter the number to check prime:");    
scanf("%d",&n);    
m=n/2;    
for(i=2;i<=m;i++)    
{    
if(n%i==0)    
{    
printf("Number is not prime");    
flag=1;    
break;    
}    
}    
if(flag==0)    
printf("Number is prime");     
return 0;  
 }    

Armstrong Number in C
Before going to write the c program to check whether the number is Armstrong or not, let's
understand what is Armstrong number.

Armstrong number is a number that is equal to the sum of cubes of its digits. For example 0, 1,
153, 370, 371 and 407 are the Armstrong numbers.

c program to check Armstrong Number in C.

#include<stdio.h>  
 int main()    
{    
int n,r,sum=0,temp;    
printf("enter the number=");    
scanf("%d",&n);    
temp=n;    
while(n>0)    
{    
r=n%10;    
sum=sum+(r*r*r);    
n=n/10;    
}    
if(temp==sum)    
printf("armstrong  number ");    
else    
printf("not armstrong number");    
return 0;  
}   

You might also like