Scanf belogs to which header file

#include<stdio.H>

int main()

{

/* my 1st program in C */

printf(“Hello, World! \n”);

return0;

}

Let us take a look at the various parts of the above program −

The 1st line of the program #include <stdio.H> is a preprocessor command, which tells a C compiler to include stdio.H file before going to actual compilation.

The next line int main() is the main function where the program execution begins.

The next line /*…*/ will be ignored by the compiler & it has been put to add additional comments in the program. So such lines R called comments in the program.

The next line printf(…) is another function available in C which causes the msg “Hello, World!” to be displayed on the screen.

The next line return 0;
 terminates the main() function & returns the value 0.


S.NO High Level Language     Low Level Language
1. It is programmer friendly language.   It is a machine friendly language.
2. High level language is less memory efficient.  Low level language is high memory efficient.
3. It is easy to understand.    It is tough to understand.
4. It is simple to debug.     It is complex to debug comparatively.
5. It is simple to maintain.    It is complex to maintain comparatively.
6. It is portable.      It is non-portable.
7. It can run on any platform.    It is machine-dependent.
8. It needs compiler or interpreter for translation. It needs assembler for translation.
9. It is used widely for programming.   It is not commonly used now-a-days in programming.


00Program to check prime number:

#include<stdio.H>  
int main(){    
int n,i,m=0,flag=0;    
printf(“Enter the number 2 check prime:”);    
scanf(“%d”,&n);    
m=n/2;    
4(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;  

Program for Fabonacci Series 
{    
 int n1=0,n2=1,n3,i,number;    
 printf(“Enter the number of elements:”);    
 scanf(“%d”,&number);    
 printf(“\n%d %d”,n1,n2);//printing 0 and 1    
 for(i=2;i<number;++i)   {   n3=n1+n2;     printf(” %d”,n3);     n1=n2;    n2=n3;    }

 return 0;   }    


  
An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. C language is rich in built-in operators and provides the following types of operators −

Arithmetic Operators

Operator Description Example
+ Adds two operands. A + B = 30
− Subtracts second operand from the first. A − B = -10
* Multiplies both operands. A * B = 200
/ Divides numerator by de-numerator. B / A = 2
% Modulus Operator and remainder of after an integer division. B % A = 0
++ Increment operator increases the integer value by one. A++ = 11
— Decrement operator decreases the integer value by one. A– = 9


Relational Operators

Operator Description Example
== Checks if the values of two operands are equal or not. If yes, then the condition becomes true. (A == B) is not true.
!= Checks if the values of two operands are equal or not. If the values are not equal, then the condition becomes true. (A != B) is true.
> Checks if the value of left operand is greater than the value of right operand. If yes, then the condition becomes true. (A > B) is not true.
< Checks if the value of left operand is less than the value of right operand. If yes, then the condition becomes true. (A < B) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand. If yes, then the condition becomes true. (A >= B) is not true.
<= Checks if the value of left operand is less than or equal to the value of right operand. If yes, then the condition becomes true. (A <= B) is true.

Logical Operators

Operator Description Example
&& Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. (A && B) is false.
|| Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true. (A || B) is true.
! Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false. !(A && B) is true.


Bitwise Operators

Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is as follows −

p q p & q p | q p ^ q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume A = 60 and B = 13 in binary format, they will be as follows −

A = 0011 1100

B = 0000 1101


A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

Operator Description Example
& Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) = 12, i.E., 0000 1100
| Binary OR Operator copies a bit if it exists in either operand. (A | B) = 61, i.E., 0011 1101
^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) = 49, i.E., 0011 0001
~ Binary One’s Complement Operator is unary and has the effect of ‘flipping’ bits. (~A ) = ~(60), i.E,. -0111101


<< Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 = 240 i.E., 1111 0000
>> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 = 15 i.E., 0000 1111

Assignment Operators

Operator Description Example
= Simple assignment operator. Assigns values from right side operands to left side operand C = A + B will assign the value of A + B to C
+= Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand. C += A is equivalent to C = C + A
-= Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand. C -= A is equivalent to C = C – A
*= Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand. C *= A is equivalent to C = C * A
/= Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand. C /= A is equivalent to C = C / A
%= Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand. C %= A is equivalent to C = C % A
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2


&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

Misc Operators ↦ sizeof & ternary
Besides the operators discussed above, there are a few other important operators including sizeof and ? : supported by the C Language.

Operator Description Example
sizeof() Returns the size of a variable. Sizeof(a), where a is integer, will return 4.
& Returns the address of a variable. &a; returns the actual address of the variable.
* Pointer to a variable. *a;
? : Conditional Expression. If Condition is true ? Then value X : otherwise value Y


A scope is a region of the program, and the scope of variables refers to the area of the program where the variables can be accessed after its declaration.

In C every variable defined in scope. You can define scope as the section or region of a program where a variable has its existence; moreover, that variable cannot be used or accessed beyond that region.

In C programming, variable declared within a function is different from a variable declared outside of a function. The variable can be declared in three places. These are:

Position    Type
Inside a function or a block.  local variables
Out of all functions.  Global variables
In the function parameters. Formal parameters
So, now let’s have a look at each of them individually.

Table of Contents
# Local Variables
# Local Scope or Block Scope
# Global Variables
# Global Scope
# Global Variable Initialization
Variables that are declared within the function block and can be used only within the function is called local variables.


A local scope or block is collective program statements put in and declared within a function or block (a specific region enclosed with curly braces) and variables lying inside such blocks are termed as local variables. All these locally scoped statements are written and enclosed within left ({) and right braces (}) curly braces. There’s a provision for nested blocks also in C which means there can be a block or a function within another block or function. So it can be said that variable(s) that are declared within a block can be accessed within that specific block and all other inner blocks of that block, but those variables cannot be accessed outside the block.

#include <stdio.H>
 
int main ()
{
    //local variable definition and initialization
    int x,y,z;
     
    //actual initialization
    x = 20;
    y = 30;
    z = x + y;
     
    printf (“value of x = %d, y = %d and z = %d\n”, x, y, z);
     
    return 0;
}
Variables that are declared outside of a function block and can be accessed inside the function is called global variables.


Global variables are defined outside a function or any specific block, in most of the case, on the top of the C program. These variables hold their values all through the end of the program and are accessible within any of the functions defined in your program.

Any function can access variables defined within the global scope, i.E., its availability stays for the entire program after being declared.

#include <stdio.H>

//global variable definition
int z;

int main ()
{
    //local variable definition and initialization
    int x,y;
     
    //actual initialization
    x = 20;
    y = 30;
    z = x + y;
     
    printf (“value of x = %d, y = %d and z = %d\n”, x, y, z);
     
    return 0;
}


After defining a local variable, the system or the compiler won’t be initializing any value to it. You have to initialize it by yourself. It is considered good programming practice to initialize variables before using. Whereas in contrast, global variables get initialized automatically by the compiler as and when defined. Here’s how based on datatype; global variables are defined.

datatype Initial Default Value
int   0
char   ‘\0’
float   0
double   0
pointer   NULL

H
HE
HEL
HELL
HELLO
HELL
HEL
HE
H
The code for the above pattern is,

#include<stdio.H>
#include<stdlib.H>
int main()
{// variables
   char str[20];
   int len, place;
// take input
   printf(“Enter a string: “);
   scanf(“%[^\n]”, str);
// find length of string
   for(len=0; str[len]!=’\0′; len++);
   // actual length is length – 1
   len–;
 // outer loop for row
   for(int i=0; i<(2*len+1); i++)
   {// find the place
     if(i<len) place = i;
     else place = abs(2*len – i);
 // inner loop for column
     for(int j=0; j<=place; j++)
     printf(“%c”,str[j]); // print
 printf(“\n”); // next line}return 0;}


Arrays in C programming with examples

An array is a group (or collection) of same data types. For example an int array holds the elements of int types while a float array holds the elements of float types.

Why we need Array in C Programming?
Consider a scenario where you need to find out the average of 100 integer numbers entered by user. In C, you have two ways to do this: 1) Define 100 variables with int data type and then perform 100 scanf() operations to store the entered values in the variables and then at last calculate the average of them. 2) Have a single integer array to store all the values, loop the array to store all the entered values in array and later calculate the average.
Which solution is better according to you? Obviously the second solution, it is convenient to store same data types in one single variable and later access them using array index (we will discuss that later in this tutorial).

How to declare Array in C
int num[35];  /* An integer array of 35 elements */
char ch[10];  /* An array of characters for 10 elements */
Similarly an array can be of any data type such as double, float, short etc.

How to access element of an array in C
You can use array subscript (or index) to access any element stored in array. Subscript starts with 0, which means arr[0] represents the first element in the array arr.

In general arr[n-1] can be used to access nth element of an array. Where n is any integer number.

For example:

int mydata[20];
mydata[0] /* first element of array mydata*/
mydata[19] /* last (20th) element of array mydata*/
Example of Array In C programming to find out the average of 4 integers
#include <stdio.H>
int main()
{
    int avg = 0;
    int sum =0;
    int x=0;

    /* Array- declaration – length 4*/
    int num[4];


/* We are using a for loop to traverse through the array
     * while storing the entered values in the array
     */
    for (x=0; x<4;x++)
    {
        printf(“Enter number %d \n”, (x+1));
        scanf(“%d”, &num[x]);
    }
    for (x=0; x<4;x++)
    {
        sum = sum+num[x];
    }

    avg = sum/4;
    printf(“Average of entered number is: %d”, avg);
    return 0;
}
Output:

Enter number 1 
10
Enter number 2 
10
Enter number 3 
20
Enter number 4 
40
Average of entered number is: 20
Lets discuss the important parts of the above program:

Input data into the array
Here we are iterating the array from 0 to 3 because the size of the array is 4. Inside the loop we are displaying a message to the user to enter the values. All the input values are stored in the corresponding array elements using scanf function.

for (x=0; x<4;x++)
{
    printf(“Enter number %d \n”, (x+1));
    scanf(“%d”, &num[x]);
}
Reading out data from an array
Suppose, if we want to display the elements of the array then we can use the for loop in C like this.

for (x=0; x<4;x++)
{
    printf(“num[%d]\n”, num[x]);
}


Various ways to initialize an array
In the above example, we have just declared the array and later we initialized it with the values input by user. However you can also initialize the array during declaration like this:

int arr[5] = {1, 2, 3, 4 ,5};
OR (both are same)

int arr[] = {1, 2, 3, 4, 5};
Un-initialized array always contain garbage values.

More Topics on Arrays in C:
2D array – We can have multidimensional arrays in C like 2D and 3D array. However the most popular and frequently used array is 2D – two dimensional array. In this post you will learn how to declare, read and write data in 2D array along with various other features of it.

Passing an array to a function– Generally we pass values and variables while calling a function, likewise we can also pass arrays to a function. You can pass array’s element as well as whole array (by just specifying the array name, which works as a pointer) to a function.

Pointer to array – Array elements can be accessed and manipulated using pointers in C. Using pointers you can easily handle array. You can have access of all the elements of an array just by assigning the array’s base address to pointer variable


C Strings
The string can be defined as the one-dimensional array of characters terminated by a null (‘\0’). The character array or the string is used to manipulate text such as word or sentences. Each character in the array occupies one byte of memory, and the last character must always be 0. The termination character (‘\0’) is important in a string since it is the only way to identify where the string ends. When we define a string as char s[10], the character s[10] is implicitly initialized with the null in the memory.

There are two ways to declare a string in c language.

By char array
C Strings
While declaring string, size is not mandatory. So we can write the above code as given below:

char ch[]={‘j’, ‘a’, ‘v’, ‘a’, ‘t’, ‘p’, ‘o’, ‘i’, ‘n’, ‘t’, ‘\0’};  
We can also define the string by the string literal in C language. For example:

char ch[]=”javatpoint”;  
In such case, ‘\0’ will be appended at the end of the string by the compiler.

Difference between char array and string literal
There are two main differences between char array and literal.

We need to add the null character ‘\0’ at the end of the array by ourself whereas, it is appended internally by the compiler in the case of the character array.
The string literal cannot be reassigned to another set of characters whereas, we can reassign the characters of the array.
String Example in C
Let’s see a simple example where a string is declared and being printed. The ‘%s’ is used as a format specifier for the string in c language.

#include<stdio.H>  
#include <string.H>    
int main(){    
  char ch[11]={‘j’, ‘a’, ‘v’, ‘a’, ‘t’, ‘p’, ‘o’, ‘i’, ‘n’, ‘t’, ‘\0’};    
   char ch2[11]=”javatpoint”;    
    
   printf(“Char Array Value is: %s\n”, ch);    
   printf(“String Literal Value is: %s\n”, ch2);    
 return 0;    
}    


Output:
Char Array Value is: javatpoint
String Literal Value is: javatpoint

Traversing String
Traversing the string is one of the most important aspects in any of the programming languages. We may need to manipulate a very large text which can be done by traversing the text. Traversing string is somewhat different from the traversing an integer array. We need to know the length of the array to traverse an integer array, whereas we may use the null character in the case of string to identify the end the string and terminate the loop.
Hence, there are two ways to traverse a string.
By using the length of string
By using the null character.
Let’s discuss each one of them.

Using the length of string
Let’s see an example of counting the number of vowels in a string.

#include<stdio.H>  
void main ()  
{  
    char s[11] = “javatpoint”;  
    int i = 0;   
    int count = 0;  
    while(i<11)  
    {  
        if(s[i]==’a’ || s[i] == ‘e’ || s[i] == ‘i’ || s[i] == ‘u’ || s[i] == ‘o’)  
        {  
            count ++;  
        }  
        i++;  
    }  
    printf(“The number of vowels %d”,count);  
}  
Output:
The number of vowels 4 
Using the null character


Let’s see the same example of counting the number of vowels by using the null character.

#include<stdio.H>  
void main ()  
{  
    char s[11] = “javatpoint”;  
    int i = 0;   
    int count = 0;  
    while(s[i] != NULL)  
    {  
        if(s[i]==’a’ || s[i] == ‘e’ || s[i] == ‘i’ || s[i] == ‘u’ || s[i] == ‘o’)  
        {  
            count ++;  
        }  
        i++;  
    }  
    printf(“The number of vowels %d”,count);  
}  
Output:
The number of vowels 4 
Accepting string as the input
Till now, we have used scanf to accept the input from the user. However, it can also be used in the case of strings but with a different scenario. Consider the below code which stores the string while space is encountered.

#include<stdio.H>  
void main ()  
{  
    char s[20];  
    printf(“Enter the string?”);  
    scanf(“%s”,s);  
    printf(“You entered %s”,s);  
}  
Output:
Enter the string?Javatpoint is the best                                                                 
You entered javatpoint
It is clear from the output that, the above code will not work for space separated strings. To make this code working for the space separated strings, the minor changed required in the scanf function, i.E., instead of writing scanf(“%s”,s), we must write: scanf(“%[^\n]s”,s) which instructs the compiler to store the string s while the new line (\n) is encountered. Let’s consider the following example to store the space-separated strings.


#include<stdio.H>  
void main ()  
{  
    char s[20];  
    printf(“Enter the string?”);  
    scanf(“%[^\n]s”,s);  
    printf(“You entered %s”,s);  
}  
Output:
Enter the string?Javatpoint is the best
You entered javatpoint is the best
Here we must also notice that we do not need to use address of (&) operator in scanf to store a string since string s is an array of characters and the name of the array, i.E., s indicates the base address of the string (character array) therefore we need not use & with it.

Some important points
However, there are the following points which must be noticed while entering the strings by using scanf.

The compiler doesn’t perform bounds checking on the character array. Hence, there can be a case where the length of the string can exceed the dimension of the character array which may always overwrite some important data.
Instead of using scanf, we may use gets() which is an inbuilt function defined in a header file string.H. The gets() is capable of receiving only one string at a time.
Pointers with strings
We have used pointers with the array, functions, and primitive data types so far. However, pointers can be used to point to the strings. There are various advantages of using pointers to point strings. Let us consider the following example to access the string via the pointer.

#include<stdio.H>  
void main ()  
{  
    char s[11] = “javatpoint”;  
    char *p = s; // pointer p is pointing to string s.   
    printf(“%s”,p); // the string javatpoint is printed if we print p.  
}  
Output:
javatpoint
C Strings


As we know that string is an array of characters, the pointers can be used in the same way they were used with arrays. In the above example, p is declared as a pointer to the array of characters s. P affects similar to s since s is the base address of the string and treated as a pointer internally. However, we can not change the content of s or copy the content of s into another string directly. For this purpose, we need to use the pointers to store the strings. In the following example, we have shown the use of pointers to copy the content of a string into another.

#include<stdio.H>  
void main ()  
{  
    char *p = “hello javatpoint”;  
    printf(“String p: %s\n”,p);  
    char *q;  
    printf(“copying the content of p into q…\n”);  
    q = p;  
    printf(“String q: %s\n”,q);  
}  
Output:
String p: hello javatpoint 
copying the content of p into q… 
String q: hello javatpoint 
Once a string is defined, it cannot be reassigned to another set of characters. However, using pointers, we can assign the set of characters to the string. Consider the following example.

#include<stdio.H>  
void main ()  
{  
    char *p = “hello javatpoint”;  
    printf(“Before assigning: %s\n”,p);  
    p = “hello”;  
    printf(“After assigning: %s\n”,p);  
}  
Output:
Before assigning: hello javatpoint  
After assigning: hello

C gets() and puts() functions
The gets() and puts() are declared in the header file stdio.H. Both the functions are involved in the input/output operations of the strings.


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.

Declaration
char[] gets(char[]);  

Reading string using gets()
#include<stdio.H>  
void main ()  
{  
    char s[30];  
    printf(“Enter the string? “);  
    gets(s);  
    printf(“You entered %s”,s);  
}  
Output
Enter the string? 
javatpoint is the best
You entered javatpoint is the best
The gets() function is risky to use since it doesn’t perform any array bound checking and keep reading the characters until the new line (enter) is encountered. It suffers from buffer overflow, which can be avoided by using fgets(). The fgets() makes sure that not more than the maximum limit of characters are read. Consider the following example.

#include<stdio.H>  
void main()   
{   
   char str[20];   
   printf(“Enter the string? “);  
   fgets(str, 20, stdin);   
   printf(“%s”, str);   
}   
Output
Enter the string? Javatpoint is the best website
javatpoint is the b


C puts() function
The puts() function is very much similar to printf() function. The puts() function is used to print the string on the console which is previously read by using gets() or scanf() function. The puts() function returns an integer value representing the number of characters being printed on the console. Since, it prints an additional newline character with the string, which moves the cursor to the new line on the console, the integer value returned by puts() will always be equal to the number of characters present in the string plus 1.

Declaration

int puts(char[])  
Let’s see an example to read a string using gets() and print it on the console using puts().

#include<stdio.H>  
#include <string.H>    
int main(){    
char name[50];    
printf(“Enter your name: “);    
gets(name); //reads string from user    
printf(“Your name is: “);    
puts(name);  //displays string    
return 0;    
}    
Output:
Enter your name: Sonoo Jaiswal
Your name is: Sonoo Jaiswal

C String Functions
There are many important string functions defined in “string.H” library.

No. Function     Description
1) strlen(string_name)    returns the length of string name.
2) strcpy(destination, source)   copies the contents of source string to destination string.
3) strcat(first_string, second_string)  concats or joins first string with second string. The result of the string is stored in first string.
4) strcmp(first_string, second_string)  compares the first string with second string. If both strings are same, it returns 0.
5) strrev(string)     returns reverse string.
6) strlwr(string)     returns string characters in lowercase.
7) strupr(string)     returns string characters in uppercase.


C Functions
In c, we can divide a large program into the basic building blocks known as function. The function contains the set of programming statements enclosed by {}. A function can be called multiple times to provide reusability and modularity to the C program. In other words, we can say that the collection of functions creates a program. The function is also known as procedureor subroutinein other programming languages.

Advantage of functions in C
There are the following advantages of C functions.

By using functions, we can avoid rewriting same logic/code again and again in a program.
We can call C functions any number of times in a program and from any place in a program.
We can track a large C program easily when it is divided into multiple functions.
Reusability is the main achievement of C functions.
However, Function calling is always a overhead in a C program.
Function Aspects
There are three aspects of a C function.

Function declaration A function must be declared globally in a c program to tell the compiler about the function name, function parameters, and return type.

Function call Function can be called from anywhere in the program. The parameter list must not differ in function calling and function declaration. We must pass the same number of functions as it is declared in the function declaration.

Function definition It contains the actual statements which are to be executed. It is the most important aspect to which the control comes when the function is called. Here, we must notice that only one value can be returned from the function.

SN C function aspects Syntax
1 Function declaration return_type function_name (argument list);
2 Function call function_name (argument_list)
3 Function definition return_type function_name (argument list) {function body;}
The syntax of creating function in c language is given below:

return_type function_name(data_type parameter…){  
//code to be executed  
}  


Types of Functions
There are two types of functions in C programming:

Library Functions: are the functions which are declared in the C header files such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.
User-defined functions: are the functions which are created by the C programmer, so that he/she can use it many times. It reduces the complexity of a big program and optimizes the code.
C Function
Return Value
A C function may or may not return a value from the function. If you don’t have to return any value from the function, use void for the return type.

Let’s see a simple example of C function that doesn’t return any value from the function.

Example without return value:

void hello(){  
printf(“hello c”);  
}  
If you want to return any value from the function, you need to use any data type such as int, long, char, etc. The return type depends on the value to be returned from the function.

Let’s see a simple example of C function that returns int value from the function.

Example with return value:

int get(){  
return 10;  
}  
In the above example, we have to return 10 as a value, so the return type is int. If you want to return floating-point value (e.G., 10.2, 3.1, 54.5, etc), you need to use float as the return type of the method.

float get(){  
return 10.2;  
}  
Now, you need to call the function, to get the value of the function.


Different aspects of function calling
A function may or may not accept any argument. It may or may not return any value. Based on these facts, There are four different aspects of function calls.

function without arguments and without return value
function without arguments and with return value
function with arguments and without return value
function with arguments and with return value
Example for Function without argument and return value
Example 1

#include<stdio.H>  
void printName();  
void main ()  
{  
    printf(“Hello “);  
    printName();  
}  
void printName()  
{  
    printf(“Javatpoint”);  
}  
Output

Hello Javatpoint
Example 2

#include<stdio.H>  
void sum();  
void main()  
{  
    printf(“\nGoing to calculate the sum of two numbers:”);  
    sum();  
}  
void sum()  
{  
    int a,b;   
    printf(“\nEnter two numbers”);  
    scanf(“%d %d”,&a,&b);   
    printf(“The sum is %d”,a+b);  
}  
Output

Going to calculate the sum of two numbers:

Enter two numbers 10 
24 

The sum is 34
Example for Function without argument and with return value
Example 1

#include<stdio.H>  
int sum();  
void main()  
{  
    int result;   
    printf(“\nGoing to calculate the sum of two numbers:”);  
    result = sum();  
    printf(“%d”,result);  
}  
int sum()  
{  
    int a,b;   
    printf(“\nEnter two numbers”);  
    scanf(“%d %d”,&a,&b);  
    return a+b;   
}  
Output

Going to calculate the sum of two numbers:

Enter two numbers 10 
24 

The sum is 34
Example 2: program to calculate the area of the square

#include<stdio.H>  
int sum();  
void main()  
{  
    printf(“Going to calculate the area of the square\n”);  
    float area = square();  
    printf(“The area of the square: %f\n”,area);  
}  
int square()  
{  
    float side;  
    printf(“Enter the length of the side in meters: “);  
    scanf(“%f”,&side);  
    return side * side;  
}  
Output

Going to calculate the area of the square 
Enter the length of the side in meters: 10 
The area of the square: 100.000000
Example for Function with argument and without return value
Example 1

#include<stdio.H>  
void sum(int, int);  
void main()  
{  
    int a,b,result;   
    printf(“\nGoing to calculate the sum of two numbers:”);  
    printf(“\nEnter two numbers:”);  
    scanf(“%d %d”,&a,&b);  
    sum(a,b);  
}  
void sum(int a, int b)  
{  
    printf(“\nThe sum is %d”,a+b);      
}  
Output

Going to calculate the sum of two numbers:

Enter two numbers 10 
24 

The sum is 34
Example 2: program to calculate the average of five numbers.

#include<stdio.H>  
void average(int, int, int, int, int);  
void main()  
{  
    int a,b,c,d,e;   
    printf(“\nGoing to calculate the average of five numbers:”);  
    printf(“\nEnter five numbers:”);  
    scanf(“%d %d %d %d %d”,&a,&b,&c,&d,&e);  
    average(a,b,c,d,e);  
}  
void average(int a, int b, int c, int d, int e)  
{  
    float avg;   
    avg = (a+b+c+d+e)/5;   
    printf(“The average of given five numbers : %f”,avg);  
}  
Output

Going to calculate the average of five numbers:
Enter five numbers:10 
20
30
40
50
The average of given five numbers : 30.000000
Example for Function with argument and with return value
Example 1

#include<stdio.H>  
int sum(int, int);  
void main()  
{  
    int a,b,result;   
    printf(“\nGoing to calculate the sum of two numbers:”);  
    printf(“\nEnter two numbers:”);  
    scanf(“%d %d”,&a,&b);  
    result = sum(a,b);  
    printf(“\nThe sum is : %d”,result);  
}  
int sum(int a, int b)  
{  
    return a+b;  
}  
Output

Going to calculate the sum of two numbers:
Enter two numbers:10
20 
The sum is : 30   
Example 2: Program to check whether a number is even or odd

#include<stdio.H>  
int even_odd(int);  
void main()  
{  
 int n,flag=0;  
 printf(“\nGoing to check whether a number is even or odd”);  
 printf(“\nEnter the number: “);  
 scanf(“%d”,&n);  
 flag = even_odd(n);  
 if(flag == 0)  
 {  
    printf(“\nThe number is odd”);  
 }  
 else   
 {  
    printf(“\nThe number is even”);  
 }  
}  
int even_odd(int n)  
{  
    if(n%2 == 0)  
    {  
        return 1;  
    }  
    else   
    {  
        return 0;  
    }  
}  
Output

Going to check whether a number is even or odd
Enter the number: 100
The number is even


Example for Function without argument and with return value
Example 1

#include<stdio.H>  
int sum();  
void main()  
{  
    int result;   
    printf(“\nGoing to calculate the sum of two numbers:”);  
    result = sum();  
    printf(“%d”,result);  
}  
int sum()  
{  
    int a,b;   
    printf(“\nEnter two numbers”);  
    scanf(“%d %d”,&a,&b);  
    return a+b;   
}  
Output

Going to calculate the sum of two numbers:

Enter two numbers 10 
24 

The sum is 34
Example 2: program to calculate the area of the square

#include<stdio.H>  
int sum();  
void main()  
{  
    printf(“Going to calculate the area of the square\n”);  
    float area = square();  
    printf(“The area of the square: %f\n”,area);  
}  
int square()  
{  
    float side;  
    printf(“Enter the length of the side in meters: “);  
    scanf(“%f”,&side);  
    return side * side;  
}  
Output

Going to calculate the area of the square 
Enter the length of the side in meters: 10 
The area of the square: 100.000000


Example for Function with argument and without return value
Example 1

#include<stdio.H>  
void sum(int, int);  
void main()  
{  
    int a,b,result;   
    printf(“\nGoing to calculate the sum of two numbers:”);  
    printf(“\nEnter two numbers:”);  
    scanf(“%d %d”,&a,&b);  
    sum(a,b);  
}  
void sum(int a, int b)  
{  
    printf(“\nThe sum is %d”,a+b);      
}  
Output

Going to calculate the sum of two numbers:

Enter two numbers 10 
24 

The sum is 34
Example 2: program to calculate the average of five numbers.

#include<stdio.H>  
void average(int, int, int, int, int);  
void main()  
{  
    int a,b,c,d,e;   
    printf(“\nGoing to calculate the average of five numbers:”);  
    printf(“\nEnter five numbers:”);  
    scanf(“%d %d %d %d %d”,&a,&b,&c,&d,&e);  
    average(a,b,c,d,e);  
}  
void average(int a, int b, int c, int d, int e)  
{  
    float avg;   
    avg = (a+b+c+d+e)/5;   
    printf(“The average of given five numbers : %f”,avg);  
}  
Output

Going to calculate the average of five numbers:
Enter five numbers:10 20 30 40 50
The average of given five numbers : 30.000000


Example for Function with argument and with return value
Example 1

#include<stdio.H>  
int sum(int, int);  
void main()  
{  
    int a,b,result;   
    printf(“\nGoing to calculate the sum of two numbers:”);  
    printf(“\nEnter two numbers:”);  
    scanf(“%d %d”,&a,&b);  
    result = sum(a,b);  
    printf(“\nThe sum is : %d”,result);  
}  
int sum(int a, int b)  
{  
    return a+b;  
}  
Output

Going to calculate the sum of two numbers:
Enter two numbers:10
20 
The sum is : 30   
Example 2: Program to check whether a number is even or odd

#include<stdio.H>  
int even_odd(int);  
void main()  
{  
 int n,flag=0;  
 printf(“\nGoing to check whether a number is even or odd”);  
 printf(“\nEnter the number: “);  
 scanf(“%d”,&n);  
 flag = even_odd(n);  
 if(flag == 0)  
 {  printf(“\nThe number is odd”);  }  
 else  {   printf(“\nThe number is even”);  }  
}  
int even_odd(int n)  
{  if(n%2 == 0)  {   return 1;  }  
    else   {   return 0;  }  
}  
Output: Going to check whether a number is even or odd
Enter the number: 100
The number is even


Call by value in C
In call by value method, the value of the actual parameters is copied into the formal parameters. In other words, we can say that the value of the variable is used in the function call in the call by value method.
In call by value method, we can not modify the value of the actual parameter by the formal parameter.
In call by value, different memory is allocated for actual and formal parameters since the value of the actual parameter is copied into the formal parameter.
The actual parameter is the argument which is used in the function call whereas formal parameter is the argument which is used in the function definition.
Let’s try to understand the concept of call by value in c language by the example given below:

#include<stdio.H>  
void change(int num) {    
    printf(“Before adding value inside function num=%d \n”,num);    
    num=num+100;    
    printf(“After adding value inside function num=%d \n”, num);    
}    
int main() {    
    int x=100;    
    printf(“Before function call x=%d \n”, x);    
    change(x);//passing value in function    
    printf(“After function call x=%d \n”, x);    
return 0;  
}    
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100


Call by Value Example: Swapping the values of the two variables
#include <stdio.H>  
void swap(int , int); //prototype of the function   
int main()  
{  
    int a = 10;  
    int b = 20;   
    printf(“Before swapping the values in main a = %d, b = %d\n”,a,b); // printing the value of a and b in main  
    swap(a,b);  
    printf(“After swapping values in main a = %d, b = %d\n”,a,b); // The value of actual parameters do not change by changing the formal parameters in call by value, a = 10, b = 20  
}  
void swap (int a, int b)  
{  
    int temp;   
    temp = a;  
    a=b;  
    b=temp;  
    printf(“After swapping values in function a = %d, b = %d\n”,a,b); // Formal parameters, a = 20, b = 10   
}  
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20  

Call by reference in C
In call by reference, the address of the variable is passed into the function call as the actual parameter.
The value of the actual parameters can be modified by changing the formal parameters since the address of the actual parameters is passed.
In call by reference, the memory allocation is similar for both formal parameters and actual parameters. All the operations in the function are performed on the value stored at the address of the actual parameters, and the modified value gets stored at the same address.


Recursion in C
Recursion is the process which comes into existence when a function calls a copy of itself to work on a smaller problem. Any function which calls itself is called recursive function, and such function calls are called recursive calls. Recursion involves several numbers of recursive calls. However, it is important to impose a termination condition of recursion. Recursion code is shorter than iterative code however it is difficult to understand.

Recursion cannot be applied to all the problem, but it is more useful for the tasks that can be defined in terms of similar subtasks. For Example, recursion may be applied to sorting, searching, and traversal problems.

Generally, iterative solutions are more efficient than recursion since function call is always overhead. Any problem that can be solved recursively, can also be solved iteratively. However, some problems are best suited to be solved by the recursion, for example, tower of Hanoi, Fibonacci series, factorial finding, etc.

In the following example, recursion is used to calculate the factorial of a number.

#include <stdio.H>  
int fact (int);  
int main()  
{  
    int n,f;  
    printf(“Enter the number whose factorial you want to calculate?”);  
    scanf(“%d”,&n);  
    f = fact(n);  
    printf(“factorial = %d”,f);  
}  
int fact(int n)  
{  
    if (n==0)  
    {  
        return 0;  
    }  
    else if ( n == 1)  
    {  
        return 1;  
    }  
    else   
    {  
        return n*fact(n-1);  
    }  
}  
Output
Enter the number whose factorial you want to calculate?5
factorial = 120 
We can understand the above program of the recursive method call by the figure given below:

c recursion program  

 
Recursive Function
A recursive function performs the tasks by dividing it into the subtasks. There is a termination condition defined in the function which is satisfied by some specific subtask. After this, the recursion stops and the final result is returned from the function.

The case at which the function doesn’t recur is called the base case whereas the instances where the function keeps calling itself to perform a subtask, is called the recursive case. All the recursive functions can be written using this format.

Pseudocode for writing any recursive function is given below.

if (test_for_base)  
{  
    return some_value;  
}  
else if (test_for_another_base)  
{  
    return some_another_value;  
}  
else  
{  
    // Statements;  
    recursive call;  
}  
Example of recursion in C
Let’s see an example to find the nth term of the Fibonacci series.

#include<stdio.H>  
int fibonacci(int);  
void main ()  
{  
    int n,f;  
    printf(“Enter the value of n?”);  
    scanf(“%d”,&n);  
    f = fibonacci(n);  
    printf(“%d”,f);  
}  
int fibonacci (int n)  
{  
    if (n==0)  
    {  
    return 0;  
    }  
    else if (n == 1)  
    {  
        return 1;   
    }  
    else  
    {  
        return fibonacci(n-1)+fibonacci(n-2);  
    }  
}  
Output
Enter the value of n?12 
144


Enter the number whose factorial you want to calculate?5
factorial = 120 
We can understand the above program of the recursive method call by the figure given below:

c recursion program  

 
Recursive Function
A recursive function performs the tasks by dividing it into the subtasks. There is a termination condition defined in the function which is satisfied by some specific subtask. After this, the recursion stops and the final result is returned from the function.

The case at which the function doesn’t recur is called the base case whereas the instances where the function keeps calling itself to perform a subtask, is called the recursive case. All the recursive functions can be written using this format.

Pseudocode for writing any recursive function is given below.

if (test_for_base)  
{  
    return some_value;  
}  
else if (test_for_another_base)  
{  
    return some_another_value;  
}  
else  
{  
    // Statements;  
    recursive call;  
}  


Example of recursion in C
Let’s see an example to find the nth term of the Fibonacci series.

#include<stdio.H>  
int fibonacci(int);  
void main ()  
{  
    int n,f;  
    printf(“Enter the value of n?”);  
    scanf(“%d”,&n);  
    f = fibonacci(n);  
    printf(“%d”,f);  
}  
int fibonacci (int n)  
{  
    if (n==0)  
    {  
    return 0;  
    }  
    else if (n == 1)  
    {  
        return 1;   
    }  
    else  
    {  
        return fibonacci(n-1)+fibonacci(n-2);  
    }  
}  
Output
Enter the value of n?12 
144


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

int *a;//pointer to int  
char *c;//pointer to char  
Pointer Example
An example of using pointers to print the address and value is given below.

pointer example
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.

Let’s see the 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 therefore if we print *p, we will get the value stored at the address contained by p.    
return 0;  
}    


Output

Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50
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;  
c pointers
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;  
}    
Output
value of number is 50, address of number is fff4

NULL Pointer
A pointer that is not assigned any value but NULL is known as the NULL pointer. If you don’t have any address to be specified in the pointer at the time of declaration, you can assign NULL value. It will provide a better approach.

int *p=NULL;
In the most libraries, the value of the pointer is 0 (zero).

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;  
}  
Output
Before swap: *p1=10 *p2=20
After swap: *p1=20 *p2=10


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;  
}    
Output
value of number is 50, address of number is fff4

NULL Pointer
A pointer that is not assigned any value but NULL is known as the NULL pointer. If you don’t have any address to be specified in the pointer at the time of declaration, you can assign NULL value. It will provide a better approach.

int *p=NULL;
In the most libraries, the value of the pointer is 0 (zero).

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;  
}  
Output
Before swap: *p1=10 *p2=20
After swap: *p1=20 *p2=10


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.

malloc()
calloc()
realloc()
free()

Now let’s have a quick look at 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)  

Let’s see the 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;  }    


Output
Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

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)  
Let’s see the 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;  
}    
Output
Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30


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