C Material
C Material
C Material
The C Language is developed by Dennis Ritchie for creating system applications that
directly interact with the hardware devices such as drivers, kernels, etc.
C programming is considered as the base for other programming languages, that is why
it is known as mother language.
Features of C Language
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
1) Simple
C is a simple language in the sense that it provides a structured approach (to break the
problem into parts), the rich set of library functions, data types, etc.
2) Machine Independent or Portable
Unlike assembly language, c programs can be executed on different machines with
some machine specific changes. Therefore, C is a machine independent language.
5) Rich Library
C provides a lot of inbuilt functions that make the development fast.
6) Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free the
allocated memory at any time by calling the free() function.
7) Speed
The compilation and execution time of C language is fast since there are lesser inbuilt
functions and hence the lesser overhead.
8) Pointer
C provides the feature of pointers. We can directly interact with the memory by using
the pointers. We can use pointers for memory, structures, functions, array, etc.
9) Recursion
In C, we can call the function within the function. It provides code reusability for
every function. Recursion enables us to use the approach of backtracking.
How to install C
There are many compilers available for c and c++. You need to download any one. Here,
we are going to use Turbo C++. It will work for both C and C++. To install the Turbo C
software, you need to follow following steps.
Download Turbo C++ for Windows 10 & 7(32-64 bit) Latest Version - 2021
First C Program
Before starting the abcd of C language, you need to learn how to write, compile and run
the first c program.
To write the first c program, open the C console and write the following code:
#include <stdio.h>
int main(){
printf("Hello C Language");
return 0;
}
return 0 The return 0 statement, returns execution status to the OS. The 0 value is used
for successful execution and 1 for unsuccessful execution.
By menu
Now click on the compile menu then compile sub menu to compile the c program.
Then click on the run menu then run sub menu to run the c program.
By shortcut
Or, press ctrl+f9 keys compile and run the program directly.
Compilation process in c
What is a compilation?
The compilation is a process of converting the source code into object code. It is done
with the help of the compiler. The compiler checks the source code for the syntactical or
structural errors, and if the source code is error-free, then it generates the object code.
The c compilation process converts the source code taken as input into the object code
or machine code. The compilation process can be divided into four steps, i.e., Pre-
processing, Compiling, Assembling, and Linking.
The preprocessor takes the source code as an input, and it removes all the comments
from the source code. The preprocessor takes the preprocessor directive and interprets
it. For example, if <stdio.h>, the directive is available in the program, then the
preprocessor interprets the directive and replace this directive with the content of
the 'stdio.h' file.
The following are the phases through which our program passes before being
transformed into an executable form:
23K
o Preprocessor
o Compiler
o Assembler
o Linker
Preprocessor
The source code is the code which is written in a text editor and the source code file is
given an extension ".c". This source code is first passed to the preprocessor, and then
the preprocessor expands this code. After expanding the code, the expanded code is
passed to the compiler.
Compiler
The code which is expanded by the preprocessor is passed to the compiler. The
compiler converts this code into assembly code. Or we can say that the C compiler
converts the pre-processed code into assembly code.
Assembler
The assembly code is converted into object code by using an assembler. The name of
the object file generated by the assembler is the same as the source file. The extension
of the object file in DOS is '.obj,' and in UNIX, the extension is 'o'. If the name of the
source file is 'hello.c', then the name of the object file would be 'hello.obj'.
Linker
Mainly, all the programs written in C use library functions. These library functions are
pre-compiled, and the object code of these library files is stored with '.lib' (or '.a')
extension. The main working of the linker is to combine the object code of library files
with the object code of our program. Sometimes the situation arises when our program
refers to the functions defined in other files; then linker plays a very important role in
this. It links the object code of these files to our program. Therefore, we conclude that
the job of the linker is to link the object code of our program with the object code of
the library files and other files. The output of the linker is the executable file. The name
of the executable file is the same as the source file but differs only in their extensions. In
DOS, the extension of the executable file is '.exe', and in UNIX, the executable file can be
named as 'a.out'. For example, if we are using printf() function in a program, then the
linker adds its associated code in an output file.
1. printf("format string",argument_list);
scanf() function
The scanf() function is used for input. It reads the input data from the console.
1. scanf("format string",argument_list);
Data Types in C
A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.
The memory size of the basic data types may change according to 32 or 64-bit
operating system.
float 4 byte
double 8 byte
Variables in C
A variable is a name of the memory location. It is used to store data. Its value can be
changed, and it can be reused many times.
1. type variable_list;
1. int a;
2. float b;
3. char c;
Here, a, b, c are variables. The int, float, char are the data types.
We can also provide values while declaring the variables as given below:
1. int a=10,b=20;//declaring 2 variable of integer type
2. float f=20.8;
3. char c='A';
Valid datatypes:
o int a;
o int _ab;
o int a30;
Types of Variables in C
There are many types of variables in c:
1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable
Local Variable
A variable that is declared inside the function or block is called a local variable.
Global Variable
A variable that is declared outside the function or block is called a global variable. Any
function can change the value of the global variable. It is available to all the functions.
int value=20;//global variable
void function1(){
int x=10;//local variable
}
Static Variable
A variable that is declared with the static keyword is called static variable.
void function1(){
int x=10;//local variable
static int y=10;//static variable
x=x+1;
y=y+1;
printf("%d,%d",x,y);
}
Automatic Variable
All variables in C that are declared inside the block, are automatic variables by default.
We can explicitly declare an automatic variable using auto keyword.
1. void main(){
2. int x=10;//local variable (also automatic)
3. auto int y=20;//automatic variable
4. }
External Variable
We can share a variable in multiple C source files by using an external variable. To
declare an external variable, you need to use extern keyword.
extern int x=10;//external variable (also global)
program1.c
#include "myfile.h"
#include <stdio.h>
void printValue(){
printf("Global variable: %d", global_variable);
}
C Identifiers
C identifiers represent the name in the C program, for example, variables, functions,
arrays, structures, unions, labels, etc. An identifier can be composed of letters such as
uppercase, lowercase letters, underscore, digits, but the starting letter should be either
an alphabet or an underscore. If the identifier is not used in the external linkage, then it
is called as an internal identifier. If the identifier is used in the external linkage, then it is
called as an external identifier.
1. total, sum, average, _m _, sum_1, etc.
C Operators
An operator is simply a symbol that is used to perform operations. There can be many
types of operations like arithmetic, logical, bitwise, etc.
o Arithmetic Operators
o Relational Operators
o Shift Operators
o Logical Operators
o Bitwise Operators
o Ternary or Conditional Operators
o Assignment Operator
Precedence of Operators in C
The precedence of operator species that which operator will be evaluated first and next.
The associativity specifies the operator direction to be evaluated; it may be left to right
or right to left.
int value=10+20*10;
The value variable will contain 210 because * (multiplicative operator) is evaluated
before + (additive operator).
Comments in C
Comments in C language are used to provide information about lines of code. It is
widely used for documenting code.
#include<stdio.h>
int main(){
//printing information
printf("Hello C");
return 0;
}
/*
code
to be commented
*/
#include<stdio.h>
int main(){
/*printing information
Multi-Line Comment*/
printf("Hello C");
return 0;
}
C Format Specifier
The Format specifier is a string used in the formatted input and output functions.
The format string determines the format of the input and output. The format
string always starts with a '%' character.
Format Description
specifier
%d or %i It is used to print the signed integer value where signed integer means that
the variable can hold both positive and negative values.
%u It is used to print the unsigned integer value where the unsigned integer
means that the variable can hold only positive value.
%o It is used to print the octal unsigned integer where octal integer value
always starts with a 0 value.
%g It is used to print the decimal floating-point values, and it uses the fixed
precision, i.e., the value after the decimal in input would be exactly the same
as the value in the output.
int main()
{
int b=6;
int c=8;
printf("Value of b is:%d", b);
printf("\nValue of c is:%d",c);
return 0;
}
Control Statements
C if else Statement
The if-else statement in C is used to perform the operations based on some specific
condition. The operations specified in if block are executed if and only if the given
condition is true.
There are the following variants of if statement in C language.
o If statement
o If-else statement
o If else-if ladder
o Nested if
If Statement
The if statement is used to check some given condition and perform some operations
depending upon the correctness of that condition. It is mostly used in the scenario
where we need to perform the different operations for the different conditions. The
syntax of the if statement is given below.
1. if(expression){
2. //code to be executed
3. }
#include<stdio.h>
int main(){
int number=0;
printf("Enter a number:");
scanf("%d",&number);
if(number%2==0){
printf("%d is even number",number);
}
return 0;
}
Output
If-else Statement
The if-else statement is used to perform two operations for a single condition. The if-
else statement is an extension to the if statement using which, we can perform two
different operations, i.e., one is for the correctness of that condition, and the other is for
the incorrectness of the condition. Here, we must notice that if and else block cannot be
executed simiulteneously. Using if-else statement is always preferable since it always
invokes an otherwise case with every if condition. The syntax of the if-else statement is
given below.
if(expression){
//code to be executed if condition is true
}else{
//code to be executed if condition is false
}
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
C Switch Statement
The switch statement in C is an alternate to if-else-if ladder statement which allows us to
execute multiple operations for the different possibles values of a single variable called
switch variable. Here, We can define various statements in the multiple cases for the
different values of a single variable.
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
Examples.
1. int x,y,z;
2. char a,b;
3. float f;
#include<stdio.h>
int main(){
int number=0;
printf("enter a number:");
scanf("%d",&number);
switch(number){
case 10:
printf("number is equals to 10");
break;
case 50:
printf("number is equal to 50");
break;
case 100:
printf("number is equal to 100");
break;
default:
printf("number is not equal to 10, 50 or 100");
}
return 0;
}
C Loops
The looping can be defined as repeating the same process multiple times until a specific
condition satisfies. There are three types of loops used in the C language. In this part of
the tutorial, we are going to learn all the aspects of C loops.
Advantage of loops in C
1) It provides code reusability.
2) Using loops, we do not need to write the same code again and again.
2.1M
54
Types of C Loops
There are three types of loops in C language that is given below:
1. do while
2. while
3. for
do-while loop in C
The do-while loop continues until a given condition satisfies. It is also called post tested
loop. It is used when it is necessary to execute the loop at least once (mostly menu
driven programs).
do{
//code to be executed
}while(condition);
while loop in C
The while loop in c is to be used in the scenario where we don't know the number of
iterations in advance. The block of statements is executed in the while loop until the
condition specified in the while loop is satisfied. It is also called a pre-tested loop.
while(condition){
//code to be executed
}
for loop in C
The for loop is used in the case where we need to execute some part of the code until
the given condition is satisfied. The for loop is also called as a per-tested loop. It is
better to use for loop if the number of iteration is known in advance.
for(initialization;condition;incr/decr){
//code to be executed
}
Flow Chart for For:
do while loop in C
The do while loop is a post tested loop. Using the do-while loop, we can repeat the
execution of several parts of the statements. The do-while loop is mainly used in the
case where we need to execute the loop at least once. The do-while loop is mostly used
in menu-driven programs where the termination condition depends upon the end user.
do while loop syntax
do{
//code to be executed
}while(condition);
Example
#include<stdio.h>
#include<stdlib.h>
void main ()
{
char c;
int choice,dummy;
do{
printf("\n1. Print Hello\n2. Print java\n3. Exit\n");
scanf("%d",&choice);
switch(choice)
{
case 1 :
printf("Hello");
break;
case 2:
printf("Javatpoint");
break;
case 3:
exit(0);
break;
default:
printf("please enter valid choice");
}
printf("do you want to enter more?");
scanf("%d",&dummy);
scanf("%c",&c);
}while(c=='y');
}
Flowchart of do while loop
while loop in C
While loop is also known as a pre-tested loop. In general, a while loop allows a part of
the code to be executed multiple times depending upon a given boolean condition. It
can be viewed as a repeating if statement. The while loop is mostly used in the case
where the number of iterations is not known in advance.
while(condition){
//code to be executed
}
#include<stdio.h>
int main(){
int i=1;
while(i<=10){
printf("%d \n",i);
i++;
}
return 0;
}
for loop in C
The for loop in C language is used to iterate the statements or a part of the program
several times. It is frequently used to traverse the data structures like the array and
linked list.
for(Expression 1; Expression 2; Expression 3){
//code
}
#include<stdio.h>
int main(){
int i=0;
for(i=1;i<=10;i++){
printf("%d \n",i);
}
return 0;
}
C Program: Print table for the given number using C for loop
#include<stdio.h>
int main(){
int i=1,number=0;
printf("Enter a number: ");
scanf("%d",&number);
for(i=1;i<=10;i++){
printf("%d \n",(number*i));
}
return 0;
}
C Array
An array is defined as the collection of similar type of data items stored at contiguous memory locations.
Arrays are the derived data type in C programming language which can store the primitive type of data
such as int, char, double, float, etc. It also has the capability to store the collection of derived data types,
such as pointers, structure, etc. The array is the simplest data structure where each data element can be
randomly accessed by using its index number.
C array is beneficial if you have to store similar elements. For example, if we want to store the marks of a
student in 6 subjects, then we don't need to define different variables for the marks in the different
subject. Instead of that, we can define an array which can store the marks in each subject at the
contiguous memory locations.
By using the array, we can access the elements easily. Only a few lines of code are required to access the
elements of the array.
Properties of Array
o Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
o Elements of the array are stored at contiguous memory locations where the first element is stored
at the smallest memory location.
o Elements of the array can be randomly accessed since we can calculate the address of each
element of the array with the given base address and the size of the data element.
Advantage of C Array
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed the limit.
So, it doesn't grow the size dynamically like LinkedList which we will learn later.
Declaration of C Array
We can declare an array in the c language in the following way.
1. data_type array_name[array_size];
1. int marks[5];
Initialization of C Array
The simplest way to initialize an array is by using the index of each element. We can initialize each
element of the array by using the index.
1. marks[0]=80;//initialization of array
2. marks[1]=60;
3. marks[2]=70;
4. marks[3]=85;
5. marks[4]=75;
#include<stdio.h>
int main(){
int i=0;
int marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}//end of for loop
return 0;
}
1. int marks[5]={20,30,40,50,60};
n such case, there is no requirement to define the size. So it may also be written as the following code.
1. int marks[]={20,30,40,50,60};
#include<stdio.h>
int main(){
int i=0;
int marks[5]={20,30,40,50,60};//declaration and initialization of array
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}
return 0;
}
#include<stdio.h>
void main ()
{
int i, j,temp;
int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
for(i = 0; i<10; i++)
{
for(j = i+1; j<10; j++)
{
if(a[j] > a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("Printing Sorted Element List ...\n");
for(i = 0; i<10; i++)
{
printf("%d\n",a[i]);
}
1. }
Program to print the largest and second largest element of the array.
#include<stdio.h>
void main ()
{
int arr[100],i,n,largest,sec_largest;
printf("Enter the size of the array?");
scanf("%d",&n);
printf("Enter the elements of the array?");
for(i = 0; i<n; i++)
{
scanf("%d",&a[i]);
}
largest = a[0];
sec_largest = a[1];
for(i=0;i<n;i++)
{
if(a[i]>largest)
{
sec_largest = largest;
largest = a[i];
}
else if (a[i]>sec_largest && a[i]!=largest)
{
sec_largest=a[i];
}
}
printf("largest = %d, second largest = %d",largest,sec_largest);
}
1. data_type array_name[rows][columns];
Initialization of 2D Array in C
In the 1D array, we don't need to specify the size of the array if the declaration and initialization are being
done simultaneously. However, this will not work with 2D arrays. We will have to define at least the
second dimension of the array. The two-dimensional array can be declared and defined in the following
way.
1. int a[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Return an Array in C
What is an Array?
An array is a type of data structure that stores a fixed-size of a homogeneous collection of data. In short,
we can say that array is a collection of variables of the same type.
For example, if we want to declare 'n' number of variables, n1, n2...n., if we create all these variables
individually, then it becomes a very tedious task. In such a case, we create an array of variables having the
same type. Each element of an array can be accessed using an index of the element.
#include <stdio.h>
void getarray(int a[])
{
printf("Elements of array are : ");
for(int i=0;i<5;i++)
{
printf("%d ", a[i]);
}
}
int main()
{
int arr[5]={45,67,34,78,90};
getarray(arr);
return 0;
}
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.
1. By char array
2. By string literal
1. char ch[10]={ 'w', 'e', 'l', 'c', 'o', 'm', 'e', '\0'};
As we know, array index starts from 0, so it will be represented as in the figure given below.
We can also define the string by the string literal in C language. For example:
1. char ch[]="welcome";
In such case, '\0' will be appended at the end of the string by the compiler.
There are two main differences between char array and literal.
o 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.
o The string literal cannot be reassigned to another set of characters whereas, we can reassign the
characters of the array.
String Example in C
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]={ 'w', 'e', 'l', 'c', 'o', 'm', 'e', '\0''};
char ch2[11]="javadotnet";
printf("Char Array Value is: %s\n", ch);
printf("String Literal Value is: %s\n", ch2);
return 0;
}
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.
#include<stdio.h>
void main ()
{
char s[11] = "welcome";
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);
}
#include<stdio.h>
void main ()
{
char s[11] = "welcome";
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);
}
#include<stdio.h>
void main ()
{
char s[20];
printf("Enter the string?");
scanf("%s",s);
printf("You entered %s",s);
}
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
1. char[] gets(char[]);
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
1. int puts(char[])
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;
}
C String Functions
There are many important string functions defined in "string.h" library.
No Function Description
.
3) strcat(first_string, concats or joins first string with second string. The result of the
second_string) string is stored in first string.
4) strcmp(first_string, compares the first string with second string. If both strings are
second_string) same, it returns 0.
#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={ 'w', 'e', 'l', 'c', 'o', 'm', 'e', '\0'};
printf("Length of string is: %d",strlen(ch));
return 0;
#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={ 'w', 'e', 'l', 'c', 'o', 'm', 'e', '\0'};
char ch2[20];
strcpy(ch2,ch);
printf("Value of second string is: %s",ch2);
return 0;
}
#include<stdio.h>
#include <string.h>
int main(){
char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
char ch2[10]={'c', '\0'};
strcat(ch,ch2);
printf("Value of first string is: %s",ch);
return 0;
}
#include<stdio.h>
#include <string.h>
int main(){
char str1[20],str2[20];
printf("Enter 1st string: ");
gets(str1);//reads string from console
printf("Enter 2nd string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
}
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
return 0;
}
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nLower String is: %s",strlwr(str));
return 0;
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nUpper String is: %s",strupr(str));
return 0;
}
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.
o By using functions, we can avoid rewriting same logic/code again and again in a program.
o We can call C functions any number of times in a program and from any place in a program.
o We can track a large C program easily when it is divided into multiple functions.
o Reusability is the main achievement of C functions.
o However, Function calling is always a overhead in a C program.
Function Aspects
There are three aspects of a C function.
o 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.
o 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.
o 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.
return_type function_name(data_type parameter...){
//code to be executed
}
Types of Functions
There are two types of functions in C programming:
1. Library Functions: are the functions which are declared in the C header files such as scanf(),
printf(), gets(), puts(), ceil(), floor() etc.
2. 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.
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.
Example of C function that doesn't return any value from the function.
void hello(){
printf("hello c");
}
Next 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.
int get(){
return 10;
}
float get(){
return 10.2;
}
#include<stdio.h>
void printName();
void main ()
{
printf("Hello ");
printName();
}
void printName()
{
printf("welcome");
}
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);
}
#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;
}
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;
}
#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);
}
#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);
}
#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;
}
#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;
}
}
What is Structure
Structure in c is a user-defined data type that enables us to store the collection of different data types.
Each element of a structure is called a member. Structures ca; simulate the use of classes and templates as
it can store various information
The following image shows the memory allocation of the structure employee that is defined in the above
example.
Here, struct is the keyword; employee is the name of the structure; id, name, and salary are the
members or fields of the structure. Let's understand it by the diagram given below:
1st way:
Example to declare the structure variable by struct keyword. It should be declared within the main
function.
struct employee
{ int id;
char name[50];
float salary;
};
1. struct employee e1, e2;
The variables e1 and e2 can be used to access the values stored in the structure.
Here, e1 and e2 can be treated in the same way as the objects in C++ and Java.
2nd way:
struct employee
{ int id;
char name[50];
float salary;
}e1,e2;
If number of variables are not fixed, use the 1st approach. It provides you the flexibility to declare the
structure variable many times.
If no. of variables are fixed, use 2nd approach. It saves your code to declare a variable in main() function.
1. p1.id
C Structure example
include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
}e1; //declaring e1 variable for structure
int main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
return 0;
}
Example 2
#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
float salary;
}e1,e2; //declaring e1 and e2 variables for structure
int main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
e1.salary=56000;
//store second employee information
e2.id=102;
strcpy(e2.name, "James Bond");
e2.salary=126000;
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
printf( "employee 1 salary : %f\n", e1.salary);
//printing second employee information
printf( "employee 2 id : %d\n", e2.id);
printf( "employee 2 name : %s\n", e2.name);
printf( "employee 2 salary : %f\n", e2.salary);
return 0;
}
C Array of Structures
#include<stdio.h>
struct student
{
char name[20];
int id;
float marks;
};
void main()
{
struct student s1,s2,s3;
printf("Enter the name, id, and marks of student 1 ");
scanf("%s %d %f",s1.name,&s1.id,&s1.marks);
printf("Enter the name, id, and marks of student 2 ");
scanf("%s %d %f",s2.name,&s2.id,&s2.marks);
printf("Enter the name, id, and marks of student 3 ");
scanf("%s %d %f",s3.name,&s3.id,&s3.marks);
printf("Printing the details....\n");
printf("%s %d %f\n",s1.name,s1.id,s1.marks);
printf("%s %d %f\n",s2.name,s2.id,s2.marks);
printf("%s %d %f\n",s3.name,s3.id,s3.marks);
}
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;
}
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).
union abc{
int a;
char b;
float c;
double d;
};
int main()
{
printf("Size of union abc is %d", sizeof(union abc));
return 0;
}
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.
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
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.
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.
#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 d
ereference a pointer therefore 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 o
f an integer array arr.
Pointer to a function
void show (int);
void(*p)(int) = &display; // Pointer p is pointing to the address of a funct
ion
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.
Usage of pointer
There are many applications of pointers in c language.
#include<stdio.h>
int main(){
int number=50;
printf("value of number is %d, address of number is %u",number,&numb
er);
return 0;
}
Pointers to Arrays
#include <stdio.h>
int main () {
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) );
}
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("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.
FILE *fopen( const char * filename, const char * mode );
Mode Description
r opens a text file in read 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 ) ;
}
int fclose( FILE *fp );
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
}
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);
}
#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);
}
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
}
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();
}
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();
}
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)
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();
}
1. malloc()
2. calloc()
3. realloc()
4. free()
ptr=(cast-type*)malloc(byte-size)
#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.
ptr=(cast-type*)calloc(number, byte-size)
#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.
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.
free(ptr)
int main(int argc, char *argv[] )
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]);
}
}
1. ./program hello
1. program.exe hello
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
.
C Math Example
#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.
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,
};
1. enum status{false,true};
1. enum status s; // creating a variable of the status type.
In the above statement, we have declared the 's' variable of type status.
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, Fri
day, 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, septembe
r, october, november, december};
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.
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.
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;
}
#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.
#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;
}