Nothing Special   »   [go: up one dir, main page]

Write An Algorithm and Draw Corresponding Flowchart To Calculate The Factorial of A Given Number

Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

write an algorithm and draw corresponding flowchart to calculate the factorial of a given number

/*c program to find out factorial value of a number*/


#include<stdio.h>
#include<conio.h>
int main()
{
int n,i,fact=1;
printf(“Enter any number : “);
scanf(“%d”, &n);
for(i=1; i<=n; i++)
fact = fact * i;
printf(“Factorial value of %d = %d”,n,fact);
return 0;
}

The output of above program would be:

Algorithm for calculate factorial value of a number:

[algorithm to calculate the factorial of a number]


step 1. Start
step 2. Read the number n
step 3. [Initialize]
i=1, fact=1
step 4. Repeat step 4 through 6 until i=n
step 5. fact=fact*i
step 6. i=i+1
step 7. Print fact
step 8. Stop
[process finish of calculate the factorial value of a number]
using recursion generate n terms of fibonacci series n-
0
C code to print Fibonacci series by recursion
2. Fibonacci series in c by using recursion

3. C code for Fibonacci series using recursion


4. Program to generate Fibonacci series using recursion
in c

#include<stdio.h>

void printFibonacci(int);

int main(){

int k,n;
long int i=0,j=1,f;

printf("Enter the range of the Fibonacci series:


");
scanf("%d",&n);

printf("Fibonacci Series: ");


printf("%d %d ",0,1);
printFibonacci(n);

return 0;
}

void printFibonacci(int n){

static long int first=0,second=1,sum;

if(n>0){
sum = first + second;
first = second;
second = sum;
printf("%ld ",sum);
printFibonacci(n-1);
}

}
Using file handling create a file insert some character and count down

// C Program to count
// the Number of Characters in a Text File

#include <stdio.h>
#define MAX_FILE_NAME 100

int main()
{
FILE* fp;

// Character counter (result)


int count = 0;

char filename[MAX_FILE_NAME];

// To store a character read from file


char c;

// Get file name from user.


// The file should be either in current folder
// or complete path should be provided
printf("Enter file name: ");
scanf("%s", filename);

// Open the file


fp = fopen(filename, "r");

// Check if file exists


if (fp == NULL) {
printf("Could not open file %s",
filename);
return 0;
}

// Extract characters from file


// and store in character c
for (c = getc(fp); c != EOF; c = getc(fp))

// Increment count for this character


count = count + 1;

// Close the file


fclose(fp);

// Print the count of characters


printf("The file %s has %d characters\n ",
filename, count);

return 0;
}
using pointers concept reverse a given string
#include <stdio.h>
#include <string.h>
// Function to reverse the string
// using pointers
void reverseString(char* str)
{
int l, i;
char *begin_ptr, *end_ptr, ch;
// Get the length of the string
l = strlen(str);
// Set the begin_ptr and end_ptr
// initially to start of string
begin_ptr = str;
end_ptr = str;
// Move the end_ptr to the last character
for (i = 0; i < l - 1; i++)
end_ptr++;
// Swap the char from start and end
// index using begin_ptr and end_ptr
for (i = 0; i < l / 2; i++) {

// swap character
ch = *end_ptr;
*end_ptr = *begin_ptr;
*begin_ptr = ch;

// update pointers positions


begin_ptr++;
end_ptr--;
}
}
// Driver code
int main()
{
// Get the string
char str[100] = "GeeksForGeeks";
printf("Enter a string: %s\n", str);

// Reverse the string


reverseString(str);

// Print the result


printf("Reverse of the string: %s\n", str);

return 0;
write programe to find string length without using strlen function
/* C Program to find the length of a String without
* using any standard library function
*/
#include <stdio.h>
int main()
{
/* Here we are taking a char array of size
* 100 which means this array can hold a string
* of 100 chars. You can change this as per requirement
*/
char str[100],i;
printf("Enter a string: \n");
scanf("%s",str);

// '\0' represents end of String


for(i=0; str[i]!='\0'; ++i);
printf("\nLength of input string: %d",i);

return 0;
}
write a programe using c to calculate the net salary if the basic,TA,DA ALLOWANCEs and deductions are
given using structures concept

#include
#include
/* structure to store employee salary details */
struct employee {
int empId;
char name[32];
int basic, hra, da, ma;
int pf, insurance;
float gross, net;
};

/* prints payslip for the requested employee */


void printSalary(struct employee e1) {
printf(“Salary Slip of %s:\n”, e1.name);
printf(“Employee ID: %d\n”, e1.empId);
printf(“Basic Salary: %d\n”, e1.basic);
printf(“House Rent Allowance: %d\n”, e1.hra);
printf(“Dearness Allowance: %d\n”, e1.da);
printf(“Medical Allowance: %d\n”, e1.ma);
printf(“Gross Salary: %.2f Rupees\n”, e1.gross);

printf(“\nDeductions: \n”);
printf(“Provident fund: %d\n”, e1.pf);
printf(“Insurance: %d\n”, e1.insurance);
printf(“\nNet Salary: %.2f Rupees\n\n”, e1.net);
return;
}

int main() {
int i, ch, num, flag, empID;
struct employee *e1;
/* get the number of employees from the user */
printf(“Enter the number of employees:”);
scanf(“%d”, &num);
/* dynamically allocate memory to store employee salary details */
e1 = (struct employee *)malloc(sizeof(struct employee) * num);
/* get the employee salary details from the customer */
printf(“Enter your input for every employee:\n”);
for (i = 0; i < num; i++) {
printf(“Employee ID:”);
scanf(“%d”, &(e1[i].empId));
getchar();
printf(“Employee Name:”);
fgets(e1[i].name, 32, stdin);
e1[i].name[strlen(e1[i].name) – 1] = ‘\0’;
printf(“Basic Salary, HRA:”);
scanf(“%d%d”, &(e1[i].basic), &(e1[i].hra));
printf(“DA, Medical Allowance:”);
what is the use of continue statement explain with example

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.
#include <stdio.h>

int main () {

/* local variable definition */


int a = 10;

/* do loop execution */
do {

if( a == 15) {
/* skip the iteration */
a = a + 1;
continue;
}

printf("value of a: %d\n", a);


a++;

} while( a < 20 );

return 0;
}
Explain any four string functions with example of each

Following are some of the useful string handling functions supported by C.


1. strlen()
2. strcpy()
3. strncpy()
4. strcat()
These functions are defined in string.h header file. Hence you need to include this header file
whenever you use these string handling functions in your program.
All these functions take either character pointer or character arrays as arguments.

strlen()
strlen() function returns the length of the string. strlen() function returns integer value.
Example:
char *str = “Learn C Online”;
int strLength;
strLength = strlen(str); //strLength contains the length of the string i.e. 14

strcpy()
strcpy() function is used to copy one string to another. The Destination_String
should be a variable and Source_String can either be a string constant or a
variable.
Syntax:
strcpy(Destination_String,Source_String);
Example:
char *Destination_String;

char *Source_String = “Learn C Online”;

strcpy(Destination_String,Source_String);
printf(“%s”, Destination_String);
strncpy()
strncpy() is used to copy only the left most n characters from source to
destination. The Destination_String should be a variable and Source_String
can either be a string constant or a variable.
Syntax:
strncpy(Destination_String, Source_String,no_of_characters);
strcat()

char *Destination_String =”Learn “;

char *Source_String = “C Online”;


strcat(Destination_String, Source_String);
puts( Destination_String);
how will you write a function with no arguments and with return value ?give
an example
First of all, you have to include the iostream header file using the "include" preceding by
# which tells that hat the header file needs to be process before compilation, hence
named preprocessor directive.
Next is int main(). As you know that all the execution of any C++ program starts from
main() function. So the main() function is defined with return type as integer. Now, you
have to take a user defined function name and declare it within main() having no return
type and hence void. Then you have to call that user defined function. And finally the
return 0; statement is used to return an integer type value back to main().
Now in the function definition in this program you have to use a for loop with integer
type variable I initialized with 1 till 35. Then on the next line, the cout statement will print
asterisk. The next cout statement with the help of "\n" will take the cursor to the next
line.
#include <iostream>
using namespace std;

int main()
{
void print(); //function declaration
print(); //function call
cout<<"\no parameter and no return type \n";
print();
return 0;
}

void print(void) //called function


{
for (int i=1;i<35;i++)
cout<<"*";
cout<<"\n";
}
write a programe swap two values using cell by value method
#include<stdio.h>

int swap(int a, int b);

int main()
{
int num1, num2;
printf("\nEnter The First Number:\t");
scanf("%d", &num1);
printf("\nEnter The Second Number:\t");
scanf("%d", &num2);
swap(num1, num2);
printf("\nOld Values\n");
printf("\nFirst Number = %d\nSecond Number = %d\n", num1, num2);
printf("\n");
return 0;
}

int swap(int a, int b)


{
int temp;
temp = a;
a = b;
b = temp;
printf("\nNew Values\n");
printf("\nFirst Number = %d\nSecond Number = %d\n", a, b);
}
write a programe in c multiply two matrics A and B
/**
* C program to multiply two matrices
*/
#include <stdio.h>

#define SIZE 3 // Size of the matrix

int main()
{
int A[SIZE][SIZE]; // Matrix 1
int B[SIZE][SIZE]; // Matrix 2
int C[SIZE][SIZE]; // Resultant matrix
int row, col, i, sum;
/* Input elements in first matrix from user */
printf("Enter elements in matrix A of size %dx%d: \n", SIZE, SIZE);
for(row=0; row<SIZE; row++)
{
for(col=0; col<SIZE; col++)
{
scanf("%d", &A[row][col]);
}
}
/* Input elements in second matrix from user */
printf("\nEnter elements in matrix B of size %dx%d: \n", SIZE, SIZE);
for(row=0; row<SIZE; row++)
{
for(col=0; col<SIZE; col++)
{
scanf("%d", &B[row][col]);
}
}
/*
* Multiply both matrices A*B
*/
for(row=0; row<SIZE; row++)
{
for(col=0; col<SIZE; col++)
{
sum = 0;
/*
* Multiply row of first matrix to column of second matrix
* and store sum of product of elements in sum.
*/
for(i=0; i<SIZE; i++)
{
sum += A[row][i] * B[i][col];
}

C[row][col] = sum;
}
}
define a macro to find maximum among of 3 given numbers using #ifdef #else
#ifdef
The syntax is as follows:
#ifdef IDENTIFIER_NAME
{
statements;
}
This will accept a name as an argument, and returns true if the name has a current definition. The
name may be defined using a # define, the -d option of the compiler, or certain names which are
automatically defined by the UNIX environment. If the identifier is defined then the statements
below #ifdef will be executed
#else
The syntax is as follows:
#else
{
statements;
}
#else is optional and ends the block started with #ifdef. It is used to create a 2 way optional
selection. If the identifier is not defined then the statements below #else will be executed.
#endif
Ends the block started by #ifdef or #else.
Where the #ifdef is true, statements between it and a following #else or #endif are included in the
program. Where it is false, and there is a following #else, statements between the #else and the
following #endif are included. Let us look into the illustrative example given below to get an idea.

What is call by value

Call by value
In call by value mechanism, the called function creates a new set of variables in stack
and copies the values of the arguments into them.
Example: Program showing the Call by Value mechanism.

void swap(int x, int y)


{
int z;
z = x;
x = y;
y = z;
printf("Swapped values are a = %d and b = %d", x, y);
}

int main (int argc, char *argv[])


{
int a = 7, b = 4;
printf("Original values are a = %d and b = %d", a, b);
swap(a, b);
printf("The values after swap are a = %d and b = %d", a, b);
}
rules for naming variables in c

To Declare any variable in C language you need to follow rules and regulation of C Language,

which is given below;

• Every variable name should start with alphabets or underscore (_).

• No spaces are allowed in variable declaration.

• Except underscore (_) no other special symbol are allowed in the middle of the
variable declaration (not allowed -> roll-no, allowed -> roll_no).

• Maximum length of variable is 8 characters depend on compiler and operation


system.

• Every variable name always should exist in the left hand side of assignment operator
(invalid -> 10=a; valid -> a=10;).

• No keyword should access variable name (int for <- invalid because for is keyword).
what recursion program with suitable example
A process in which a function calls itself directly or indirectly is called Recursion in C and the
corresponding function is called a Recursive function.

1. Direct Recursion:If function definition contains, the function call itself then it is direct
recursion.Example:

Fun( )

Fun( );
}2. Indirect Recursion:If function fun1() calls another function fun2() and function fun2() calls
function fun1(), then it is known as indirect recursion.

Example:

Fun2( )
{
…..
Fun1( );
}

Fun1( )
{
…..
Fun2( );

//Learnprogramo
#include<stdio.h>
int fact(int);
int main()
{
int num;
printf("Enter the number whose factorial is to be find :");
scanf("%d" ,&num);
if(num<0)
{
printf("ERROR. Factorial is not defined for negative integers");
}
printf("Factorial of %d is %d", num, fact(num));
return 0;
}
int fact(int num)
{
if(num==0) //base condition
{
return 1;
}
else
{
return(num*fact(num-1)); //recursive call
}
design an algorithm and draw a corresponding flow chart and write a cprograme to devide
two numbers
Step 1: Input String

Step 2: Initilise Pointer C to initial character of String

Step 3: while(C != NULL)

if (*C>=’A’ && *C<=’Z’)

*C=*C+32

}
Step 4: Print converted Lower case String

Step 5: Stop

FlowChart:
write a programe to calculate the smallest diviserof a number using break statement

/*Program to calculate smallest divisor of a number */

#include <stdio.h>

main( )

int div,num,i;

printf(“Enter any number:\n”);

scanf(“%d”,&num);

for (i=2;i<=num;++i)

if ((num % i) == 0)

printf(“Smallest divisor for number %d is %d”,num,i);

Also Learn - First C program

break;

OUTPUT
Enter any number:
9
Smallest divisor for number 9 is 3
write a program in c to swap the values of two variables using pointer concept
#include<stdio.h>

void swap(int *num1, int *num2) {


int temp;
temp = *num1;
*num1 = *num2;
*num2 = temp;
}

int main() {
int num1, num2;

printf("\nEnter the first number : ");


scanf("%d", &num1);
printf("\nEnter the Second number : ");
scanf("%d", &num2);

swap(&num1, &num2);

printf("\nFirst number : %d", num1);


printf("\nSecond number : %d", num2);

return (0);
}
Enter the first number : 12
Enter the Second number : 22
First number : 22
Second number : 12
write a programe that initialises 3 names in an array of string and display them

/*C - Initialize Array of Strings in C,


C Program for of Array of Strings.*/

#include <stdio.h>

int main(){

char string[3][30]={"String 1","String 2","String 3"};


int loop;

//print all strings


for(loop=0;loop<3;loop++){
printf("%s\n",string[loop]);
}
return 0;
}
String 1
String 2
String 3
write a program in c sort list of integers using any of the sorting algorithm

#include<stdio.h>

void quick_sort(int elements[], int min, int max);


int sublist_builder(int elements[], int min, int max);

int main()
{
int elements[30], limit, count;
printf("Enter Limit for Array:\t");
scanf("%d", &limit);
printf("\nEnter %d Elements in the Array\n", limit);
for(count = 0; count < limit; count++)
{
scanf("%d", &elements[count]);
}
quick_sort(elements, 0, limit - 1);
printf("\nSorted List:\n");
for(count = 0; count < limit; count++)
{
printf("%d\t", elements[count]);
}
printf("\n");
return 0;
}

void quick_sort(int elements[], int min, int max)


{
int pivot_index;
if(min >= max)
{
return;
}
pivot_index = sublist_builder(elements, min, max);
quick_sort(elements, min, pivot_index - 1);
quick_sort(elements, pivot_index + 1, max);
}

int sublist_builder(int elements[], int min, int max)


{
int temp, x, y, pivot_element;
x = min + 1;
y = max;
pivot_element = elements[min];
while(x <= y)
{
while((elements[x] < pivot_element) && (x < max))
{
write a programe to print first 10 even numbers using goto statement

#include<stdio.h>
void main()
{
printf("1");
printf("2");
printf("3");
printf("4");
printf("5");
printf("6");
printf("7");
printf("8");
printf("9");
printf("10");
}

int main()
{
//declare variable
int count,t,r;

//Read value of t
printf("Enter number: ");
scanf("%d",&t);

count=1;

start:
if(count<=10)
{
//Formula of table
r=t*count;
printf("%d*%d=%d\n",t,count,r);
count++;
goto start;
}

return 0;
}
explain function prototype with an example of each
Function prototype is the important feature of C programming which was borrowed from
C++. Early versions of C programming did not use function prototype.

Function prototype in C is a function declaration that provides information to the


compiler about the return type of the function and the number, types, and order of the
parameters the called function expect to receive.

Function prototype in C is used by the compiler to ensure whether the function call
matches the return type and the correct number of arguments or parameters with its
data type of the called function.

In the absence of the function prototype, a coder might call function improperly without
the compiler detecting errors that may lead to fatal execution-time errors that are difficult
to detect.

int area( int length, int breadth ) //function definition

.... //function body

Now, the corresponding prototype declaration of the above function is:

int area( int length, int breadth ); //function prototype


write aprograme to perform the comparison of two stings
/* C program to Compare Two Strings without using strcmp() */

#include <stdio.h>

#include <string.h>

int main()

char Str1[100], Str2[100];

int result, i;

printf("\n Please Enter the First String : ");

gets(Str1);

printf("\n Please Enter the Second String : ");

gets(Str2);

for(i = 0; Str1[i] == Str2[i] && Str1[i] == '\0'; i++);

if(Str1[i] < Str2[i])

printf("\n str1 is Less than str2");

else if(Str1[i] > Str2[i])

printf("\n str2 is Less than str1");

else
write a programe to test whether the given string is paindrome or not

/* C Program to Check the given string is Palindrome or not */

#include <stdio.h>

#include <string.h>

int main()

char str[100];

int i, len, flag;

flag = 0;

printf("\n Please Enter any String : ");

gets(str);

len = strlen(str);

for(i = 0; i < len; i++)

if(str[i] != str[len - i - 1])

flag = 1;

break;

if(flag == 0)

{
write a macro to demonstrate#define#if#else preprocessor commands

#include <stdio.h>
#define CHOICE 100
int my_int = 0;
#if (CHOICE == 100)
void set_my_int()
{ my_int = 35; }
#else
void set_my_int()
{
my_int = 27;
}
#endif
main ()
{
set_my_int();
clrscr();
printf(“%d\n”, my_int);
getch();
}
write a c programe using fread fwrite to create a file of records and then read and print the same file

#include<stdio.h>
#include<conio.h>
#include<process.h>

typedef struct student {


int roll;
char name[20];
float marks;

} stud;

void sort(int n)
{
FILE *fp_index, *fp_record;
int i, j, r1, r2, r3;
stud s1, s2, s3;

fp_index = fopen(“index.txt”, “r+b”);


fp_record = fopen(“record.txt”, “r+b”);
for (i = 0; i < n – 1; i++)
{
for (j = 0; j < n – 1; j++)
{

fseek(fp_record, sizeof(s1) * j, SEEK_SET);


fseek(fp_index, sizeof(int) * j, SEEK_SET);

fread(&r1, sizeof(int), 1, fp_index);

fread(&r2, sizeof(int), 1, fp_index);

if (r1 > r2) //swap record and index


{
fread(&s1, sizeof(s1), 1, fp_record);
fread(&s2, sizeof(s2), 1, fp_record);

fseek(fp_record, (sizeof(s1)) * j, SEEK_SET);


fseek(fp_index, (sizeof(int)) * j, SEEK_SET);
fwrite(&r2, sizeof(int), 1, fp_index);
fwrite(&r1, sizeof(int), 1, fp_index);

fwrite(&s2, sizeof(s1), 1, fp_record);


fwrite(&s1, sizeof(s1), 1, fp_record);
}
}
}

.txt”, “r+b”);
what is syntax error give an example of syntax error c program

Syntax errors: Errors that occur when you violate the rules of writing C/C++ syntax are
known as syntax errors. This compiler error indicates something that must be fixed before
the code can be compiled. All these errors are detected by compiler and thus are known as
compile-time errors.

• Missing Parenthesis (})


• Printing the value of variable without declaring it
• Missing semicolon like this:
// C program to illustrate syntax error
#include<stdio.h>
void main()
{
int x = 10;
int y = 15;
printf("%d", (x, y)) // semicolon missed
}

error: expected ';' before '}' token

the use of malloc function in c


The malloc() function stands for memory allocation. It is a function which is
used to allocate a block of memory dynamically. It reserves memory space of
specified size and returns the null pointer pointing to the memory location. The
pointer returned is usually of type void. It means that we can assign malloc
function to any pointer.
what is string ? write a function in c for string concatenation without the use of inbuilt
string function
/* C program to Concatenate Two Strings without using strcat() *

#include <stdio.h>

#include <string.h>

int main()

char Str1[100], Str2[100];

int i, j;

printf("\n Please Enter the First String : ");

gets(Str1);

printf("\n Please Enter the Second String : ");

gets(Str2);

// To iterate First String from Start to end

for (i = 0; Str1[i]!='\0'; i++);

// Concatenating Str2 into Str1

for (j = 0; Str2[j]!='\0'; j++, i++)

Str1[i] = Str2[j];

Str1[i] = '\0';

printf("\n String after the Concatenate = %s", Str1);


getch

The getch() function is very useful if you want to read a character input from
the keyboard.

While this is not a part of the C standard, this is still a POSIX C function. So,
we can still use this function from Windows / Linux / Mac.

Basic Syntax of getch() in C/C++

This function takes in a single character from the standard input (stdin), and
returns an integer.
This is there as part of the <conio.h> header file, so you must include it in
your program.
#include <conio.h>

int getch();

Strcmp
In the C Programming Language, the strcmp function returns a negative, zero, or
positive integer depending on whether the object pointed to by s1 is less than, equal to,
or greater than the object pointed to by s2.

Syntax
The syntax for the strcmp function in the C Language is:

int strcmp(const char *s1, const char *s2);

getchar
• The C library function int getchar (void) gets a character (an unsigned char) from
stdin. This is equivalent to getc with stdin as its argument.
• Declaration. Following is the declaration for getchar () function.
• Parameters
• Return Value. This function returns the character read as an unsigned char cast to an
int or EOF on end of file or error.
Gets()
C gets() function. The gets() function enables the user to enter some
characters followed by the enter key. All the characters entered by the user
get stored in a character array. The null character is added to the array to
make it a string. The gets() allows the user to enter the space-separated
strings. It returns the string entered by the user.

C library function - puts ()


• Description. The C library function int puts (const char
• str) writes a string to stdout up to but not including the...
• Declaration. Following is the declaration for puts () function.
• Parameters.
• Return Value. If successful, non-negative value is returned. On error, the function
returns EOF.
write a program to multiply 2 matrics of size 3*3
#include<stdio.h>
int main() {
int a[10][10], b[10][10], c[10][10], i, j, k;
int sum = 0;

printf("\nEnter First Matrix : n");


for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
scanf("%d", &a[i][j]);
}
}
printf("\nEnter Second Matrix:n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
scanf("%d", &b[i][j]);
}
}
printf("The First Matrix is: \n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf(" %d ", a[i][j]);
}
printf("\n");
}
printf("The Second Matrix is : \n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf(" %d ", b[i][j]);
}
printf("\n");
}
//Multiplication Logic
for (i = 0; i <= 2; i++) {
for (j = 0; j <= 2; j++) {
sum = 0;
for (k = 0; k <= 2; k++) {
sum = sum + a[i][k] * b[k][j];
}
c[i][j] = sum;
}
}
printf("\nMultiplication Of Two Matrices : \n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf(" %d ", c[i][j]);
whatt is the difference betwwen while do and do while loop
What do you mean by scope of a variable ? Differentiate between Global
and Local variables giving an example of each.
Scope of a Variable
Scope of a Variable means the bondaries of the variable in which it appears and can be accessible.

Global vs. Static variables:


Global variables are recognized through out the program whereas local valuables are recognized
only within the function where they are defined.

External (Global) Variables


These are not confined to a single function. Their scope ranges from the point of declaration to the
entire remaining program. Therefore, their scope may be the entire program or two or more functions
depending upon where they are declared.

Points to remember:

• These are global and can be accessed by any function within its scope.

Therefore value may be assigned in one and can be written in another.

• There is difference in external variable definition and declaration.

• External Definition is the same as any variable declaration:

• Usually lies outside or before the function accessing it.

• It allocates storage space required.

• Initial values can be assigned.

• The external specifier is not required in external variable definition.

• A declaration is required if the external variable definition comes after the function definition.

• A declaration begins with an external specifier.

• Only when external variable is defined is the storage space allocated.

• External variables can be assigned initial values as a part of variable definitions, but the values
must be constants rather than expressions.

• If initial value is not included then it is automatically assigned a value of zero.

Let us study these variables by a sample program given below:


# include <stdio.h>

int gv; /*global variable*/

main ( )

void function1(); /*function declaration*/

gv = 10;

printf (“%d is the value of gv before function call\n”, gv);

function1( );

printf (“%d is the value of gv after function call\n”, gv);

void function1 ( )

gv = 15: }

OUTPUT

10 is the value of gv before function call

15 is the value of gv after function call

You might also like