Documente Academic
Documente Profesional
Documente Cultură
C Programming Language
The C Language is developed for creating system applications that direct interacts to the
hardware devices such as drivers, kernals etc.
C programming is considered as the base for other programming languages, that is why it is
known as mother language.
1. Mother language
2. System programming language
3. Procedure-oriented programming language
4. Structured programming language
5. Mid level programming language
1) C as a mother language
C language is considered as the mother language of all the modern languages because most of
the compilers, JVMs, Kernals etc. are written in C language and most of languages follows c
syntax e.g. C++, Java etc.
It provides the core concepts like array, functions, file handling etc. that is being used in many
languages like C++, java, C# etc.
3) C as a procedural language
A procedural language breaks the program into functions, data structures etc.
In C language, we break the program into parts using functions. It makes the program easier to
understand and modify.
C is considered as a middle level language because it supports the feature of both low-level
and high level language. C language program is converted into assembly code, supports pointer
arithmetic (low level), but it is machine independent (feature of high level).
Low level language is specific to one machine i.e. machine dependent. It is machine dependent,
fast to run. But it is not easy to understand.
High Level language is not specific to one machine i.e. machine independent. It is easy to
understand.
History of C Language
History of C language is interesting to know. Here we are going to discuss brief history of c
language.
It was developed to overcome the problems of previous languages such as B, BCPL etc.
Initially, C language was developed to be used in UNIX operating system. It inherits many
features of previous languages such as B and BCPL.
Let's see the programming languages that were developed before C language.
Features of C Language
C is the widely used language. It provides a lot of featuresthat are given below.
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
10. Extensible
1) Simple
C is a simple language in the sense that it provides structured approach (to break the problem
into parts), rich set of library functions, data types etc.
Unlike assembly language, c programs can be executed in many machines with little bit or no
change. But it is not platform-independent.
C is also used to do low level programming. It is used to develop system applications such as
kernel, driver etc. It also supports the feature of high level language. That is why it is known
as mid-level language.
C is a structured programming language in the sense that we can break the program into parts
using functions. So, it is easy to understand and modify.
5) Rich Library
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
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.
10) Extensible
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.
You can download turbo c++ from many sites. download Turbo c++
Now, you need to create a new directory turboc inside the c: drive. Now extract the tc3.zip file in
c:\truboc directory.
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:
1. #include <stdio.h>
2. main(){
3. printf("Hello C Language");
4. }
#include <stdio.h> includes the standard input output library functions. The printf() function
is defined in stdio.h .
main() The main() function is the entry point of every program in c language.
There are 2 ways to compile and run the c program, by menu and by shortcut.
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.
You can view the user screen any time by pressing the alt+f5 keys.
Press enter, it will look inside the c:\turboc directory for the required files.
Select Start installation by the down arrow key then press enter.
Now double click on the tc icon located in c:\TC\BIN directory to write the c program.
In windows 7 or window 8, it will show a dialog block to ignore and close the application
because fullscreen mode is not supported. Click on Ignore button.
Flow of C Program
The C program follows many steps in execution. To understand the flow of C program well, let
us see a simple program first.
File: simple.c
1. #include <stdio.h>
2. main(){
3. printf("Hello C Language");
4. }
Execution Flow
Let's try to understand the flow of above program by the figure given below.
2) Expanded source code is sent to compiler which compiles the code and converts it into
assembly code.
3) The assembly code is sent to assembler which assembles the code and converts it into object
code. Now a simple.obj file is generated.
4) The object code is sent to linker which links it to the library such as header files. Then it is
converted into executable code. A simple.exe file is generated.
5) The executable code is sent to loader which loads it into memory and then it is executed. After
execution, output is sent to console.
The printf() and scanf() functions are used for input and output in C language. Both functions are
inbuilt library functions, defined in stdio.h (header file).
printf() function
The printf() function is used for output. It prints the given statement to the console.
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);
Let's see a simple example of c language that gets input from the user and prints the cube of the
given number.
1. #include<stdio.h>
2. main()
3. {
4. int number;
5. printf("enter a number:");
6. scanf("%d",&number);
7. printf("cube of number is:%d ",number*number*number);
8. }
Output
enter a number:5
cube of number is:125
The scanf("%d",&number) statement reads integer number from the console and stores the
given value in number variable.
Let's see a simple example of input and output in C language that prints addition of 2 numbers.
1. #include<stdio.h>
2. main()
3. {
4. int x=0,y=0,result=0;
5.
6. printf("enter first number:");
7. scanf("%d",&x);
8. printf("enter second number:");
9. scanf("%d",&y);
10.
11. result=x+y;
Output
enter first number:9
enter second number:9
sum of 2 numbers:18
Variables in C
A variable is a name of memory location. It is used to store data. Its value can be changed and it
can be reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.
1. type variable_list;
1. int a;
2. float b;
3. char c;
We can also provide values while declaring the variables as given below:
o A variable name must not be any reserved word or keyword e.g. int, float etc.
1. int a;
2. int _ab;
3. int a30;
1. int 2;
2. int a b;
3. int long;
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 local variable.
1. void function1(){
2. int x=10;//local variable
3. }
Global Variable
A variable that is declared outside the function or block is called global variable. Any function
can change the value of the global variable. It is available to all the functions.
Static Variable
1. void function1(){
2. int x=10;//local variable
3. static int y=10;//static variable
4. x=x+1;
5. y=y+1;
6. printf("%d,%d",x,y);
7. }
If you call this function many times, local variable will print the same value for each function
call e.g, 11,11,11 and so on. But static variable will print the incremented value in each
function call e.g. 11, 12, 13 and so on.
Automatic Variable
All variables in C that is declared inside the block, are automatic variables by default. By we can
explicitly declare automatic variable using auto keyword.
1. void main()
2. {
3. int x=10;//local variable (also automatic)
External Variable
We can share a variable in multiple C source files by using external variable. To declare a
external variable, you need to use extern keyword.
myfile.h
1. #include "myfile.h"
2. #include <stdio.h>
3. void printValue(){
4. printf("Global variable: %d", global_variable);
5. }
Data Types in C
A data type specifies the type of data that a variable can store such as integer, floating, character
etc.
The basic data types are integer-based and floating-point based. C language supports both signed
and unsigned literals.
The memory size of basic data types may change according to 32 or 64 bit operating system.
Let's see the basic data types. Its size is given according to 32 bit architecture.
Float 4 byte
Double 8 byte
Keywords in C
A keyword is a reserved word. You cannot use it as a variable name, constant name etc.
There are only 32 reserved words (keywords) in C language.
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.
There are following types of operators to perform different types of operations in C language.
o Arithmetic Operators
o Relational Operators
o Shift Operators
o Logical Operators
o Bitwise Operators
o Ternary or Conditional Operators
o Assignment Operator
o Misc Operator
Precedence of Operators in C
The precedence of operator species that which operator will be evaluated first and next. The
associativity specifies the operators direction to be evaluated, it may be left to right or right to
left.
1. 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. There are 2 types of comments in C language.
Single line comments are represented by double slash \\. Let's see an example of single line
comment in C.
1. #include<stdio.h>
2. main()
3. {
4. //printing information
5. printf("Hello C");
6. }
Output:
Hello C
Multi line comments are represented by slash asterisk \* ... *\. It can occupy many lines of code
but it can't be nested. Syntax:
1. /*
2. code
3. to be commented
4. */
1. #include<stdio.h>
2. main(){
3. /*printing information
4. Multi Line Comment*/
5. printf("Hello C");
6. return 0;
7. }
Output:
Hello C
Escape Sequence in C
An escape sequence in C language is a sequence of characters that doesn't represent itself when
used inside string literal or character.
It is composed of two or more characters starting with backslash \. For example: \n represents
new line.
\a Alarm or Beep
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Tab (Horizontal)
\v Vertical Tab
\\ Backslash
\? Question Mark
\0 Null
1. #include<stdio.h>
2. main()
3. {
4. int number=50;
5. printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");
6. }
Output:
You
are
learning
'c' language
"Do you know C language"
Constants in C
A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a',
3.4, "c programming" etc.
List of Constants in C
Constant Example
1. const keyword
2. #define preprocessor
1) C const keyword
1. #include<stdio.h>
2. main()
3. {
4. const float PI=3.14;
5. printf("The value of PI is: %f",PI);
6. }
Output:
If you try to change the the value of PI, it will render compile time error.
1. #include<stdio.h>
2. main()
3. {
4. const float PI=3.14;
5. PI=4.5;
6. printf("The value of PI is: %f",PI);
7. }
Output:
2) C #define preprocessor
The #define preprocessor is also used to define constant. We will learn about #define
preprocessor directive later.
C Control Statements
C if else Statement
The if statement in C language is used to perform operation on the basis of condition. By using
if-else statement, you can perform operation either condition is true or false.
o If statement
o If-else statement
o If else-if ladder
o Nested if
If Statement
The single if statement in C language is used to execute the code if condition is true. The syntax
of if statement is given below:
1. if(expression){
2. //code to be executed
3. }
Flowchart of if statement in C
1. #include<stdio.h>
2. main()
3. {
4. int number=0;
5. printf("enter a number:");
6. scanf("%d",&number);
7. if(number%2==0){
8. printf("%d is even number",number);
9. }
10. }
Output
enter a number:4
4 is even number
enter a number:5
If-else Statement
The if-else statement in C language is used to execute the code if condition is true or false. The
syntax of if-else statement is given below:
1. if(expression){
2. //code to be executed if condition is true
3. }else{
4. //code to be executed if condition is false
5. }
Let's see the simple example of even and odd number using if-else statement in C language.
1. #include<stdio.h>
2. main()
3. {
4. int number=0;
5. printf("enter a number:");
6. scanf("%d",&number);
7. if(number%2==0){
8. printf("%d is even number",number);
9. }
10. else{
11. printf("%d is odd number",number);
12. }
13. }
Output
enter a number:4
4 is even number
enter a number:5
5 is odd number
The if else-if statement is used to execute one code from multiple conditions. The syntax of if
else-if statement is given below:
1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
4. //code to be executed if condition2 is true
5. }
6. else if(condition3){
7. //code to be executed if condition3 is true
8. }
9. ...
10. else{
11. //code to be executed if all the conditions are false
12. }
1. #include<stdio.h>
2. main()
3. {
4. int number=0;
5. printf("enter a number:");
6. scanf("%d",&number);
7. if(number==10){
8. printf("number is equals to 10");
9. }
10. else if(number==50){
11. printf("number is equal to 50");
12. }
13. else if(number==100){
Output
enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
C Switch Statement
The switch statement in C language is used to execute the code from multiple conditions. It is
like if else-if ladder statement.
1. switch(expression){
2. case value1:
3. //code to be executed;
4. break; //optional
5. case value2:
6. //code to be executed;
7. break; //optional
8. ......
9.
10. default:
11. code to be executed if all cases are not matched;
12. }
3) The case value can be used only inside the switch statement.
4) The break statement in switch case is not must. It is optional. If there is no break statement
found in switch case, all the cases will be executed after matching the case value. It is known
as fall through state of C switch statement.
Let's try to understand it by the examples. We are assuming there are following variables.
1. int x,y,z;
2. char a,b;
3. float f;
Valid Switch Invalid Switch Valid Case Invalid Case
1. #include<stdio.h>
2. main()
3. {
4. int number=0;
5. printf("enter a number:");
6. scanf("%d",&number);
7. switch(number){
8. case 10:
C Language notes Page 36
C Language Notes
Output
enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
In C language, switch statement is fall through, it means if you don't use break statement in
switch case, all the case after matching case will be executed.
Let's try to understand the fall through state of switch statement by the example given below.
1. #include<stdio.h>
2. main()
3. {
4. int number=0;
5.
6. printf("enter a number:");
7. scanf("%d",&number);
8.
9. switch(number){
10. case 10:
11. printf("number is equals to 10\n");
12. case 50:
13. printf("number is equal to 50\n");
Output
enter a number:10
number is equals to 10
number is equals to 50
number is equals to 100
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
number is equals to 100
number is not equal to 10, 50 or 100
C Loops
The loops in C language are used to execute a block of code or a part of the program several
times.
Suppose that you have to print table of 2, then you need to write 10 lines of code.
Advantage of loops in C
1) It saves code.
Types of C Loops
1. do while
2. while
3. for
do-while loop in C
It iterates the code until condition is false. Here, condition is given after the code. So at least
once, code is executed whether condition is true or false.
1. do{
2. //code to be executed
3. }while(condition);
Flowchart and Example of do-while loop
while loop in C
Like do while, it iterates the code until condition is false. Here, condition is given before the
code. So code may be executed 0 or more times.
1. while(condition){
2. //code to be executed
3. }
Flowchart and Example of while loop
for loop in C
Like while, it iterates the code until condition is false. Here, initialization, condition and
increment/decrement is given before the code. So code may be executed 0 or more times.
1. for(initialization;condition;incr/decr){
2. //code to be executed
3. }
do while loop in C
To execute a part of program or code several times, we can use do-while loop of C language.
The code given between the do and while block will be executed until condition is true.
In do while loop, statement is given before the condition, so statement or code will be executed
at lease one time. In other words, we can say it is executed 1 or more times.
1. do{
2. //code to be executed
3. }while(condition);
do while example
There is given the simple program of c language do while loop where we are printing the table of
1.
1. #include<stdio.h>
2. main(){
3. int i=1;
4. do{
5. printf("%d \n",i);
6. i++;
7. }while(i<=10);
8. }
Output
1
2
3
4
5
6
7
8
9
10
Program to print table for the given number using do while loop
1. #include<stdio.h>
2. main()
3. {
4. int i=1,number=0;
5. printf("Enter a number: ");
6. scanf("%d",&number);
7. do{
8. printf("%d \n",(number*i));
9. i++;
10. }while(i<=10);
11. }
Output
Enter a number: 5
5
10
15
20
25
30
35
40
45
50
Enter a number: 10
10
20
30
40
50
60
70
80
90
100
If you pass 1 as a expression in do while loop, it will run infinite number of times.
1. do{
2. //statement
3. }while(1);
while loop in C
The while loop in C language is used to iterate the part of program or statements many times.
In while loop, condition is given before the statement. So it is different from the do while loop. It
can execute the statements 0 or more times.
The C language while loop should be used if number of iteration is uncertain or unknown.
1. while(condition){
2. //code to be executed
3. }
Let's see the simple program of while loop that prints table of 1.
1. #include<stdio.h>
2. main()
3. {
4. int i=1;
5. while(i<=10){
6. printf("%d \n",i);
7. i++;
8. }
9. }
Output
1
2
3
4
5
6
7
8
9
10
Program to print table for the given number using while loop in C
1. #include<stdio.h>
2. main()
3. {
4. int i=1,number=0,b=9;
5. printf("Enter a number: ");
6. scanf("%d",&number);
7. while(i<=10){
8. printf("%d \n",(number*i));
9. i++;
10. }
11. }
Output
Enter a number: 50
50
100
150
200
250
300
350
400
450
500
Enter a number: 100
100
200
300
400
500
600
700
800
900
1000
C Language notes Page 45
C Language Notes
If you pass 1 as a expression in while loop, it will run infinite number of times.
1. while(1){
2. //statement
3. }
for loop in C
The for loop in C language is also used to iterate the statement or a part of the program several
times, like while and do-while loop.
But, we can initialize and increment or decrement the variable also at the time of checking the
condition in for loop.
Unlike do while loop, the condition or expression in for loop is given before the statement, so it
may execute the statement 0 or more times.
1. for(initialization;condition;incr/decr){
2. //code to be executed
3. }
Let's see the simple program of for loop that prints table of 1.
1. #include<stdio.h>
2. main()
3. {
4. int i=0;
5. for(i=1;i<=10;i++){
6. printf("%d \n",i);
7. }
8. }
Output
1
2
3
4
5
6
7
8
9
10
C Program : Print table for the given number using C for loop
1. #include<stdio.h>
2. main()
3. {
4. int i=1,number=0;
5. printf("Enter a number: ");
6. scanf("%d",&number);
7. for(i=1;i<=10;i++){
8. printf("%d \n",(number*i));
9. }
10. }
Output
Enter a number: 2
2
4
6
8
10
12
14
16
18
20
Enter a number: 1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
If you don't initialize any variable, check condition and increment or decrement variable in for
loop, it is known as infinitive for loop.
In other words, if you place 2 semicolons in for loop, it is known as infinitive for loop.
1. for(;;){
2. printf("infinitive for loop example by c language");
3. }
C break statement
The break statement in C language is used to break the execution of loop (while, do while and
for) and switch case.
Syntax:
1. jump-statement;
2. break;
The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.
Flowchart of break in c
1. #include<stdio.h>
2. main()
3. {
4. int i=1;//initializing a local variable
5. //starting a loop from 1 to 10
6. for(i=1;i<=10;i++){
7. printf("%d \n",i);
8. if(i==5){//if value of i is equal to 5, it will break the loop
9. break;
10. }
11. }
12. }
Output
1
2
3
4
5
As you can see on console output, loop from 1 to 10 is not printed after i==5.
In such case, it breaks only inner loop, but not outer loop.
1. #include<stdio.h>
2. main()
3. {
4. int i=1,j=1;//initializing a local variable
5. for(i=1;i<=3;i++){
6. for(j=1;j<=3;j++){
7. printf("%d &d\n",i,j);
8. if(i==2 && j==2){
9. break;//will break loop of j only
10. }
11. }//end of for loop
12. return 0;
13. }
Output
11
12
13
21
22
31
32
33
As you can see the output on console, 2 3 is not printed because there is break statement after
printing i==2 and j==2. But 3 1, 3 2 and 3 3 is printed because break statement works for inner
loop only.
C continue statement
The continue statement in C language is used to continue the execution of loop (while, do while
and for). It is used with if condition within the loop.
Syntax:
1. jump-statement;
2. continue;
1. #include<stdio.h>
2. int main(){
3. int i=1;//initializing a local variable
4. //starting a loop from 1 to 10
5. for(i=1;i<=10;i++){
6. if(i==5){//if value of i is equal to 5, it will continue the loop
7. continue;
8. }
9. printf("%d \n",i);
10. }//end of for loop
11. return 0;
12. }
Output
1
2
3
4
6
7
8
9
10
As you can see, 5 is not printed on the console because loop is continued at i==5.
In such case, C continue statement continues only inner loop, but not outer loop.
1. #include<stdio.h>
2. main()
3. {
4. int i=1,j=1;//initializing a local variable
5. for(i=1;i<=3;i++){
6. for(j=1;j<=3;j++){
7. if(i==2 && j==2){
8. continue;//will continue loop of j only
9. }
10. printf("%d %d\n",i,j);
11. }
12. }//end of for loop
13. }
Output
11
12
13
21
23
31
32
33
As you can see, 2 2 is not printed on the console because inner loop is continued at i==2 and
j==2.
C goto statement
The goto statement is known as jump statement in C language. It is used to unconditionally jump
to other label. It transfers control to other parts of the program.
It is rarely used today because it makes program less readable and complex.
Syntax:
1. goto label;
goto example
1. #include <stdio.h>
2. main()
3. {
4. int age;
5. ineligible:
6. printf("You are not eligible to vote!\n");
7.
8. printf("Enter you age:\n");
9. scanf("%d", &age);
10. if(age<18)
11. goto ineligible;
12. else
13. printf("You are eligible to vote!\n");
14.
15. }
Output:
C Functions
Functions in C
To perform any task, we can create function. A function can be called many times. It
provides modularity and code reusability.
Advantage of functions in C
1) Code Reusability
By creating functions in C, you can call it many times. So we don't need to write the same code
again and again.
2) Code optimization
Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or not.
Without using function, you need to write the prime number logic 3 times. So, there is repetition
of code.
But if you use functions, you need to write the logic only once and you can reuse it several times.
Types of Functions
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 complexity of a big program and optimizes
the code.
Declaration of a 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.
1. void hello(){
2. printf("hello c");
3. }
C Language notes Page 56
C Language Notes
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.
1. int get(){
2. return 10;
3. }
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.
1. float get(){
2. return 10.2;
3. }
Now, you need to call the function, to get the value of the function.
Parameters in C Function
A c function may have 0 or more parameters. You can have any type of parameter in C program
such as int, float, char etc. The parameters are also known as formal arguments.
1. void hello(){
2. printf("hello c");
3. }
2. return a+b;
3. }
Calling a function in C
If a function returns any value, you need to call function to get the value returned from the
function. The syntax of calling a function in c programming is given below:
1. variable=function_name(arguments...);
1) variable: The variable is not mandatory. If function return type is void, you must not provide
the variable because void functions doesn't return any value.
3) arguments: You need to provide arguments while calling the C function. It is also known
as actual arguments.
Let's see the simple program of C function that doesn't return any value from the function.
1. #include<stdio.h>
2. void hello(){
3. printf("hello c programming \n");
4. }
5. main(){
6. hello();//calling a function
7. hello();
8. hello();
9. return 0;
10. }
Output
hello c programming
hello c programming
hello c programming
1. #include<stdio.h>
2. //defining function
3. int cube(int n){
4. return n*n*n;
5. }
6. main(){
7. int result1=0,result2=0;
8.
9. result1=cube(2);//calling function
10. result2=cube(3);
11.
12. printf("%d \n",result1);
13. printf("%d \n",result2);
14. }
Output
8
27
There are two ways to pass value or data to function in C language: call by value and call by
reference. Original value is not modified in call by value but it is modified in call by reference.
Let's understand call by value and call by reference in c language one by one.
Call by value in C
In call by value, value being passed to the function is locally stored by the function parameter in
stack memory location. If you change the value of function parameter, it is changed for the
current function only. It will not change the value of variable inside the caller method such as
main().
Let's try to understand the concept of call by value in c language by the example given below:
1. #include<stdio.h>
2. void change(int num) {
3. printf("Before adding value inside function num=%d \n",num);
4. num=num+100;
5. printf("After adding value inside function num=%d \n", num);
6. }
7. main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(x);//passing value in function
11. printf("After function call x=%d \n", x);
12. }
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 reference in C
Here, address of the value is passed in the function, so actual and formal arguments shares the
same address space. Hence, value changed inside the function, is reflected inside as well as
outside the function.
Let's try to understand the concept of call by reference in c language by the example given
below:
1. #include<stdio.h>
2. void change(int *num) {
3. printf("Before adding value inside function num=%d \n",*num);
4. (*num) += 100;
5. printf("After adding value inside function num=%d \n", *num);
6. }
7. main()
8. {
9. int x=100;
10. printf("Before function call x=%d \n", x);
11. change(&x);//passing reference in function
12. printf("After function call x=%d \n", x);
13. }
Output
Before function call x=100
2 Changes made inside the function is not Changes made inside the function is
reflected on other functions reflected outside the function also
3 Actual and formal arguments will be Actual and formal arguments will be
created in different memory location created in same memory location
Storage Classes in C
Storage classes are used to define scope and life time of a variable. There are four storage classes
in C programming.
o auto
o extern
o static
o register
extern RAM Zero Global Till the end of main program, May be
declared anywhere in the program
static RAM Zero Local Till the end of main program, Retains
value between multiple functions call
1) auto
The auto keyword is applied to all local variables automatically. It is the default storage class
that is why it is known as automatic variable.
1. #include<stdio.h>
2. main()
3. {
4. int a=10;
5. auto int b=10;//same like above
6. printf("%d %d",a,b);
7. }
Output:
10 10
2) register
The register variable allocates memory in register than RAM. Its size is same of register size. It
has a faster access than other variables.
It is recommended to use register variable only for quick access such as in counter.
3) static
The static variable is initialized only once and exists till the end of the program. It retains its
value between multiple functions call.
The static variable has the default value 0 which is provided by compiler.
1. #include<stdio.h>
2. int func(){
3.
4. static int i=0;//static variable
5. int j=0;//local variable
6. i++;
7. j++;
8. printf("i= %d and j= %d\n", i, j);
9. }
10. main() {
11. func();
12. func();
13. func();
14. return 0;
15. }
Output:
i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1
4) extern
The extern variable is visible to all the programs. It is used if two or more files are sharing same
variable or function.
Arrays:-
Array in C language is a collection or group of elements (data). All the elements of c array
are homogeneous (similar). It has contiguous memory location.
C array is beneficial if you have to store similar elements. Suppose you have to store marks of 50
students, one way to do this is allotting 50 variables. So it will be typical and hard to manage.
For example we can not access the value of these variables with only 1 or 2 lines of code.
Another way to do this is array. By using array, we can access the elements easily. Only few
lines of code is required to access the elements of array.
Advantage of C Array
2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array easily.
3) Easy to sort data: To sort the elements of 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 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
1. data_type array_name[array_size];
1. int marks[5];
Here, int is the data_type, marks is the array_name and 5 is the array_size.
Initialization of C Array
A simple way to initialize array is by index. Notice that array index starts from 0 and ends with
[SIZE - 1].
1. marks[0]=80;//initialization of array
2. marks[1]=60;
3. marks[2]=70;
4. marks[3]=85;
5. marks[4]=75;
C array example
1. #include<stdio.h>
2. main()
3. {
4. int i=0;
5. int marks[5];//declaration of array
6. marks[0]=80;//initialization of array
7. marks[1]=60;
8. marks[2]=70;
9. marks[3]=85;
10. marks[4]=75;
11. //traversal of array
12. for(i=0;i<5;i++){
13. printf("%d \n",marks[i]);
14. }//end of for loop
15. }
Output
80
60
70
85
75
We can initialize the c array at the time of declaration. Let's see the code.
1. int marks[5]={20,30,40,50,60};
In such case, there is no requirement to define size. So it can also be written as the following
code.
1. int marks[]={20,30,40,50,60};
Let's see the full program to declare and initialize the array in C.
1. #include<stdio.h>
2. main()
3. {
4. int i=0;
5. int marks[5]={20,30,40,50,60};//declaration and initialization of array
6. //traversal of array
7. for(i=0;i<5;i++){
8. printf("%d \n",marks[i]);
9. }
10. return 0;
11. }
Output
20
30
40
50
60
The two dimensional array in C language is represented in the form of rows and columns, also
known as matrix. It is also known as array of arrays or list of arrays.
The two dimensional, three dimensional or other dimensional arrays are also known
as multidimensional arrays.
C Language notes Page 67
C Language Notes
1. data_type array_name[size1][size2];
1. int twodimen[4][3];
Initialization of 2D Array in C
A way to initialize the two dimensional array at the time of declaration is given below.
1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
1. #include<stdio.h>
2. main(){
3. int i=0,j=0;
4. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
5. //traversing 2D array
6. for(i=0;i<4;i++){
7. for(j=0;j<3;j++){
8. printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
9. }//end of j
10. }//end of i
11. return 0;
12. }
Output
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6
C Pointers
The pointer in C language is a variable, it is also known as locator or indicator that points to an
address of a value.
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.
3) It makes you able to access any memory location in the computer's memory.
Usage of pointer
In c language, we can dynamically allocate memory using malloc() and calloc() functions where
pointer is used.
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.
1. #include<stdio.h>
2. main(){
3. int number=50;
4. printf("value of number is %d, address of number is %u",number,&number);
5. return 0;
6. }
Output
value of number is 50, address of number is fff4
Declaring a pointer
Pointer example
An example of using pointers printing the address and value is given below.
As you can see in the above figure, pointer variable stores the address of number variable i.e.
fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.
By the help of * (indirection operator), we can print the value of pointer variable p.
1. #include<stdio.h>
2. main(){
3. int number=50;
4. int *p;
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %x \n",p);
7. printf("Value of p variable is %d \n",*p);
8. return 0;
9. }
Output
Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50
NULL Pointer
A pointer that is not assigned any value but NULL is known as 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 a better approach.
int *p=NULL;
1. #include<stdio.h>
2. main()
3. {
4. int a=10,b=20,*p1=&a,*p2=&b;
5. printf("Before swap: *p1=%d *p2=%d",*p1,*p2);
6. *p1=*p1+*p2;
7. *p2=*p1-*p2;
8. *p1=*p1-*p2;
9. printf("\nAfter swap: *p1=%d *p2=%d",*p1,*p2);
10.
11. return 0;
12. }
Output
Before swap: *p1=10 *p2=20
After swap: *p1=20 *p2=10
C Pointer to Pointer
In c language, a pointer can point to the address of another pointer which points to the address of
a value. Let's understand it by the diagram given below:
1. int **p2;
Let's see an example where one pointer points to the address of another pointer.
As you can see in the above figure, p2 contains the address of p (fff2) and p contains the address
of number variable (fff4).
1. #include<stdio.h>
2. main(){
3. int number=50;
4. int *p;//pointer to int
5. int **p2;//pointer to pointer
6. p=&number;//stores the address of number variable
7. p2=&p;
8. printf("Address of number variable is %x \n",&number);
9. printf("Address of p variable is %x \n",p);
10. printf("Value of *p variable is %d \n",*p);
11. printf("Address of p2 variable is %x \n",p2);
12. printf("Value of **p2 variable is %d \n",*p);
13. }
Output
Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50
C Strings
1. By char array
2. By string literal
While declaring string, size is not mandatory. So you can write the above code as given below:
You can also define string by string literal in C language. For example:
1. char ch[]="welcome";
In such case, '\0' will be appended at the end of string by the compiler.
The only difference is that string literal cannot be changed whereas string declared by char array
can be changed.
String Example in C
Let's see a simple example to declare and print string. The '%s' is used to print string in c
language.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[11]={‘w’,e’,’l’,’c’,’o’,’m’,’e’, '\0'};
5. char ch2[11]="welcome";
6.
7. printf("Char Array Value is: %s\n", ch);
8. printf("String Literal Value is: %s\n", ch2);
9. return 0;
10. }
Output:
The gets() function reads string from user and puts() function prints the string. Both functions are
defined in <stdio.h> header file.
Let's see a simple program to read and write string using gets() and puts() functions.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char name[50];
5. printf("Enter your name: ");
6. gets(name); //reads string from user
7. printf("Your name is: ");
8. puts(name); //displays string
9. return 0;
10. }
Output:
C String Functions
3) strcat(first_string, concats or joins first string with second string. The result
second_string) of the string is stored in first string.
4) strcmp(first_string, compares the first string with second string. If both strings
second_string) are same, it returns 0.
The strlen() function returns the length of the given string. It doesn't count null character '\0'.
1. #include<stdio.h>
2. #include <string.h>
3. main(){
4. char ch[20]={‘w’,’e’,’l’,’c’,’o’,’m’,’e’, '\0'};
5. printf("Length of string is: %d",strlen(ch));
6. return 0;
7. }
Output:
1. #include<stdio.h>
2. #include <string.h>
3. main(){
4. char ch[20]={ ]={‘w’,’e’,’l’,’c’,’o’,’m’,’e’, '\0'};
5. char ch2[20];
6. strcpy(ch2,ch);
7. printf("Value of second string is: %s",ch2);
8. return 0;
9. }
Output:
The strcat(first_string, second_string) function concatenates two strings and result is returned to
first_string.
1. #include<stdio.h>
2. #include <string.h>
3. main(){
4. char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
5. char ch2[10]={'c', '\0'};
6. strcat(ch,ch2);
7. printf("Value of first string is: %s",ch);
8. return 0;
9. }
Output:
The strcmp(first_string, second_string) function compares two string and returns 0 if both strings
are equal.
Here, we are using gets() function which reads string from the console.
1. #include<stdio.h>
2. #include <string.h>
3. main(){
4. char str1[20],str2[20];
5. printf("Enter 1st string: ");
6. gets(str1);//reads string from console
7. printf("Enter 2nd string: ");
8. gets(str2);
9. if(strcmp(str1,str2)==0)
10. printf("Strings are equal");
11. else
12. printf("Strings are not equal");
13. return 0;
14. }
Output:
The strrev(string) function returns reverse of the given string. Let's see a simple example of
strrev() function.
1. #include<stdio.h>
2. #include <string.h>
3. main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nReverse String is: %s",strrev(str));
9. return 0;
10. }
The strlwr(string) function returns string characters in lowercase. Let's see a simple example of
strlwr() function.
1. #include<stdio.h>
2. #include <string.h>
3. main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nLower String is: %s",strlwr(str));
9. return 0;
10. }
The strupr(string) function returns string characters in uppercase. Let's see a simple example of
strupr() function.
1. #include<stdio.h>
2. #include <string.h>
3. main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nUpper String is: %s",strupr(str));
9. return 0;
10. }
C Math
C Math Functions
1) ceil(numb rounds up the given number. It returns the integer value which is greater
er) than or equal to given number.
2) floor(num rounds down the given number. It returns the integer value which is
C Math Example
Let's see a simple example of math functions found in math.h header file.
1. #include<stdio.h>
2. #include <math.h>
3. main()
4. {
5. printf("\n%f",ceil(3.6));
6. printf("\n%f",ceil(3.3));
7. printf("\n%f",floor(3.6));
8. printf("\n%f",floor(3.2));
9. printf("\n%f",sqrt(16));
10. printf("\n%f",sqrt(7));
11. printf("\n%f",pow(2,4));
12. printf("\n%f",pow(3,3));
13. printf("\n%d",abs(-12));
14. return 0;
15. }
Output:
4.000000
4.000000
3.000000
3.000000
4.000000
2.645751
16.000000
27.000000
12
Structure in C
Structure in c language is a user defined datatype that allows you to hold different type of
elements.
It works like a template in C++ and class in Java. You can have different type of elements in it.
It is widely used to store student information, employee information, product information, book
information etc.
Defining structure
The struct keyword is used to define structure. Let's see the syntax to define structure in c.
1. struct structure_name
2. {
3. data_type member1;
4. data_type member2;
5. .
6. .
7. data_type memeberN;
8. };
1. struct employee
2. { int id;
3. char name[50];
4. float salary;
5. };
Here, struct is the keyword, employee is the tag name of structure; id, name and salary are the
members or fields of the structure. Let's understand it by the diagram given below:
We can declare variable for the structure, so that we can access the member of structure easily.
There are two ways to declare structure variable:
1st way:
Let's see the example to declare structure variable by struct keyword. It should be declared
within the main function.
1. struct employee
2. { int id;
3. char name[50];
4. float salary;
5. };
2nd way:
Let's see another way to declare variable at the time of defining structure.
1. struct employee
2. { int id;
3. char name[50];
4. float salary;
5. }e1,e2;
But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare the
structure variable many times.
If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in main()
fuction.
Let's see the code to access the id member of p1 variable by . (member) operator.
1. p1.id
C Structure example
1. #include<stdio.h>
2. #include <string.h>
3. struct employee
4. { int id;
5. char name[50];
6. }e1; //declaring e1 variable for structure
7. main( )
8. {
9. //store first employee information
10. e1.id=101;
11. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
12. //printing first employee information
13. printf( "employee 1 id : %d\n", e1.id);
14. printf( "employee 1 name : %s\n", e1.name);
15. return 0;
16. }
Output:
employee 1 id : 101
employee 1 name : Sonoo Jaiswal
Let's see another example of structure in C language to store many employees information.
1. #include<stdio.h>
2. #include <string.h>
3. struct employee
4. { int id;
5. char name[50];
6. float salary;
7. }e1,e2; //declaring e1 and e2 variables for structure
8. main( )
9. {
10. //store first employee information
11. e1.id=101;
12. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
13. e1.salary=56000;
14.
Output:
employee 1 id : 101
employee 1 name : Sonoo Jaiswal
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000
Array of Structures in C
There can be array of structures in C programming to store many information of different data
types. The array of structures is also known as collection of structures.
Let's see an example of structure with array that stores information of 5 students and prints it.
1. #include<stdio.h>
2. #include <string.h>
3. struct student{
4. int rollno;
5. char name[10];
6. };
7. main(){
8. int i;
9. struct student st[5];
10. printf("Enter Records of 5 students");
11. for(i=0;i<5;i++){
12. printf("\nEnter Rollno:");
13. scanf("%d",&st[i].rollno);
14. printf("\nEnter Name:");
15. scanf("%s",&st[i].name);
16. }
17. printf("\nStudent Information List:");
18. for(i=0;i<5;i++){
19. printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
20. }
21. return 0;
22. }
Output:
Nested Structure in C
Nested structure in c language can have another structure as a member. There are two ways to
define nested structure in c language:
1. By separate structure
2. By Embedded structure
1) Separate structure
We can create 2 structures, but dependent structure should be used inside the main structure as a
member. Let's see the code of nested structure.
1. struct Date
2. {
3. int dd;
4. int mm;
5. int yyyy;
6. };
7. struct Employee
8. {
9. int id;
10. char name[20];
11. struct Date doj;
12. }emp1;
As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in
Employee structure. In this way, we can use Date structure in many structures.
2) Embedded structure
We can define structure within the structure also. It requires less code than previous way. But it
can't be used in many structures.
1. struct Employee
2. {
3. int id;
4. char name[20];
5. struct Date
6. {
7. int dd;
8. int mm;
9. int yyyy;
10. }doj;
11. }emp1;
1. e1.doj.dd
2. e1.doj.mm
3. e1.doj.yyyy
1. #include <stdio.h>
2. #include <string.h>
3. struct Employee
4. {
5. int id;
6. char name[20];
7. struct Date
8. {
9. int dd;
10. int mm;
11. int yyyy;
12. }doj;
13. }e1;
14. main( )
15. {
16. //storing employee information
17. e1.id=101;
18. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
19. e1.doj.dd=10;
20. e1.doj.mm=11;
21. e1.doj.yyyy=2014;
22.
23. //printing first employee information
24. printf( "employee id : %d\n", e1.id);
25. printf( "employee name : %s\n", e1.name);
26. printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.y
yyy);
27. return 0;
28. }
Output:
employee id : 101
employee name : Sonoo Jaiswal
employee date of joining (dd/mm/yyyy) : 10/11/2014
C Union
Like structure, Union in c language is a user defined datatype that is used to hold different type
of elements.
But it doesn't occupy sum of all members size. It occupies the memory of largest member only. It
shares memory of largest member.
It occupies less memory because it occupies the memory of largest member only.
Defining union
The union keyword is used to define union. Let's see the syntax to define union in c.
1. union union_name
2. {
3. data_type member1;
4. data_type member2;
5. .
6. .
7. data_type memeberN;
8. };
1. union employee
2. { int id;
3. char name[50];
4. float salary;
5. };
C Union example
1. #include <stdio.h>
2. #include <string.h>
3. union employee
4. { int id;
5. char name[50];
6. }e1; //declaring e1 variable for union
7. main( )
8. {
9. //store first employee information
10. e1.id=101;
11. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
12. //printing first employee information
13. printf( "employee 1 id : %d\n", e1.id);
14. printf( "employee 1 name : %s\n", e1.name);
15. return 0;
16. }
Output:
employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal
C Preprocessor Directives
The C preprocessor is a micro processor that is used by compiler to transform your code before
compilation. It is called micro preprocessor because it allows us to add macros.
o #include
o #define
o #undef
o #ifdef
o #ifndef
o #if
o #else
o #elif
o #endif
o #error
o #pragma
C #define
The #define preprocessor directive is used to define constant or micro substitution. It can use any
basic data type.
Syntax:
1. #include <stdio.h>
2. #define PI 3.14
3. main() {
4. printf("%f",PI);
5. }
Output:
3.140000
1. #include <stdio.h>
2. #define MIN(a,b) ((a)<(b)?(a):(b))
3. void main() {
4. printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));
5. }
Output:
C #undef
The #undef preprocessor directive is used to undefine the constant or macro defined by #define.
Syntax:
1. #undef token
1. #include <stdio.h>
2. #define PI 3.14
3. #undef PI
4. main() {
5. printf("%f",PI);
6. }
Output:
The #undef directive is used to define the preprocessor constant to a limited scope so that you
can declare constant again.
Let's see an example where we are defining and undefining number variable. But before being
undefined, it was used by square variable.
1. #include <stdio.h>
2. #define number 15
3. int square=number*number;
4. #undef number
5. main() {
6. printf("%d",square);
7. }
Output:
225
C #ifdef
The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the
code otherwise #else code is executed, if present.
Syntax:
1. #ifdef MACRO
2. //code
3. #endif
1. #ifdef MACRO
2. //successful code
3. #else
4. //else code
5. #endif
C #ifdef example
1. #include <stdio.h>
2. #include <conio.h>
3. #define NOINPUT
4. void main() {
5. int a=0;
6. #ifdef NOINPUT
7. a=2;
8. #else
9. printf("Enter a:");
10. scanf("%d", &a);
11. #endif
12. printf("Value of a: %d\n", a);
13. getch();
14. }
Output:
Value of a: 2
But, if you don't define NOINPUT, it will ask user to enter a number.
1. #include <stdio.h>
2. #include <conio.h>
3. void main() {
4. int a=0;
5. #ifdef NOINPUT
6. a=2;
7. #else
8. printf("Enter a:");
9. scanf("%d", &a);
10. #endif
11.
12. printf("Value of a: %d\n", a);
13. getch();
14. }
Output:
Enter a:5
Value of a: 5
C #error
The #error preprocessor directive indicates error. The compiler gives fatal error if #error
directive is found and skips further compilation process.
C #error example
1. #include<stdio.h>
2. #ifndef __MATH_H
3. #error First include then compile
4. #else
5. void main(){
6. float a;
7. a=sqrt(7);
8. printf("%f",a);
9. }
10. #endif
Output:
1. #include<stdio.h>
2. #include<math.h>
3. #ifndef __MATH_H
4. #error First include then compile
5. #else
6. void main(){
7. float a;
8. a=sqrt(7);
9. printf("%f",a);
10. }
11. #endif
Output:
2.645751
C #if
The #if preprocessor directive evaluates the expression or condition. If condition is true, it
executes the code otherwise #elseif or #else or #endif code is executed.
Syntax:
1. #if expression
2. //code
3. #endif
1. #if expression
2. //if code
3. #else
4. //else code
5. #endif
1. #if expression
2. //if code
3. #elif expression
4. //elif code
5. #else
6. //else code
7. #endif
C #if example
1. #include <stdio.h>
2. #include <conio.h>
3. #define NUMBER 0
4. void main() {
5. #if (NUMBER==0)
6. printf("Value of Number is: %d",NUMBER);
7. #endif
8. getch();
9. }
Output:
1. #include <stdio.h>
2. #include <conio.h>
3. #define NUMBER 1
4. void main() {
5. clrscr();
6. #if (NUMBER==0)
7. printf("1 Value of Number is: %d",NUMBER);
8. #endif
9.
10. #if (NUMBER==1)
11. printf("2 Value of Number is: %d",NUMBER);
12. #endif
13. getch();
14. }
Output:
File Handling in C
File Handling in c language is used to open, read, write, search or close file. It is used for
permanent storage.
Advantage of File
It will contain the data even after program exit. Normally we use variable or array to store data,
but data is lost after program exit. Variables and arrays are non-permanent storage medium
whereas file is permanent storage medium.
There are many functions in C library to open, read, write, search and close file. A list of file
functions are given below:
The fopen() function is used to open a file. The syntax of fopen() function is given below:
You can use one of the following modes in the fopen() function.
Mode Description
The fclose() function is used to close a file. The syntax of fclose() function is given below:
The fprintf() function is used to write set of characters into file. It sends formatted output to a
stream.
Syntax:
Example:
1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. fp = fopen("file.txt", "w");//opening file
5. fprintf(fp, "Hello file by fprintf...\n");//writing data into file
6. fclose(fp);//closing file
7. }
The fscanf() function is used to read set of characters from file. It reads a word from the file and
returns EOF at the end of file.
Syntax:
Example:
1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. char buff[255];//creating char array to store data of file
5. fp = fopen("file.txt", "r");
6. while(fscanf(fp, "%s", buff)!=EOF){
7. printf("%s ", buff );
8. }
9. fclose(fp);
10. }
Output:
Let's see a file handling example to store employee information as entered by user from console.
We are going to store id, name and salary of the employee.
1. #include <stdio.h>
2. void main()
3. {
4. FILE *fptr;
5. int id;
6. char name[30];
7. float salary;
8. fptr = fopen("emp.txt", "w+");/* open for writing */
9. if (fptr == NULL)
10. {
11. printf("File does not exists \n");
12. return;
13. }
14. printf("Enter the id\n");
15. scanf("%d", &id);
16. fprintf(fptr, "Id= %d\n", id);
17. printf("Enter the name \n");
18. scanf("%s", name);
19. fprintf(fptr, "Name= %s\n", name);
20. printf("Enter the salary\n");
21. scanf("%f", &salary);
22. fprintf(fptr, "Salary= %.2f\n", salary);
23. fclose(fptr);
24. }
Output:
Enter the id
1
Enter the name
sonoo
Enter the salary
120000
Now open file from current directory. For windows operating system, go to TC\bin directory,
you will see emp.txt file. It will have following information.
emp.txt
Id= 1
Name= sonoo
Salary= 120000
The fputc() function is used to write a single character into file. It outputs a character to a stream.
Syntax:
Example:
1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. fp = fopen("file1.txt", "w");//opening file
5. fputc('a',fp);//writing single character into file
6. fclose(fp);//closing file
7. }
file1.txt
The fgetc() function returns a single character from the file. It gets a character from the stream. It
returns EOF at the end of file.
Syntax:
Example:
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char c;
6. clrscr();
7. fp=fopen("myfile.txt","r");
8.
9. while((c=fgetc(fp))!=EOF){
10. printf("%c",c);
11. }
12. fclose(fp);
13. getch();
14. }
myfile.txt
The fputs() and fgets() in C programming are used to write and read string from stream. Let's see
examples of writing and reading file using fgets() and fgets() functions.
The fputs() function writes a line of characters into file. It outputs string to a stream.
Syntax:
Example:
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. clrscr();
6.
7. fp=fopen("myfile2.txt","w");
8. fputs("hello c programming",fp);
9.
10. fclose(fp);
11. getch();
12. }
myfile2.txt
hello c programming
The fgets() function reads a line of characters from file. It gets string from a stream.
Syntax:
Example:
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char text[300];
6. clrscr();
7.
8. fp=fopen("myfile2.txt","r");
9. printf("%s",fgets(text,200,fp));
10.
11. fclose(fp);
12. getch();
13. }
Output:
hello c programming
C Programs
Fibonacci Series in C
Fibonacci Series in C: In case of fibonacci series, next number is the sum of previous two
numbers for example 0, 1, 1, 2, 3, 5, 8, 13, 21 etc. The first two numbers of fibonacci series are 0
and 1.
1. #include<stdio.h>
2. main()
3. {
4. int n1=0,n2=1,n3,i,number;
5. printf("Enter the number of elements:");
6. scanf("%d",&number);
7. printf("\n%d %d",n1,n2);//printing 0 and 1
8. for(i=2;i<number;++i)//loop starts from 2 because 0 and 1 are already printed
9. {
10. n3=n1+n2;
11. printf(" %d",n3);
12. n1=n2;
13. n2=n3;
14. }
15. return 0;
16. }
Output:
Prime number in C: Prime number is a number that is greater than 1 and divided by 1 or itself.
In other words, prime numbers can't be divided by other numbers than itself or 1. For example 2,
3, 5, 7, 11, 13, 17, 19, 23.... are the prime numbers.
1. #include<stdio.h>
2. main(){
3. int n,i,m=0,flag=0;
4. printf("Enter the number to check prime:");
5. scanf("%d",&n);
6. m=n/2;
7. for(i=2;i<=m;i++)
8. {
9. if(n%i==0)
10. {
11. printf("Number is not prime");
12. flag=1;
13. break;
14. }
15. }
16. if(flag==0)
Output:
Palindrome program in C
Palindrome number in c: A palindrome number is a number that is same after reverse. For
example 121, 34543, 343, 131, 48984 are the palindrome numbers.
Let's see the palindrome program in C. In this c program, we will get an input from the user and
check whether number is palindrome or not.
1. #include<stdio.h>
2. main()
3. {
4. int n,r,sum=0,temp;
5. printf("enter the number=");
6. scanf("%d",&n);
7. temp=n;
8. while(n>0)
9. {
10. r=n%10;
11. sum=(sum*10)+r;
12. n=n/10;
13. }
14. if(temp==sum)
15. printf("palindrome number ");
16. else
17. printf("not palindrome");
18. return 0;
19. }
Output:
Factorial Program in C
1. 5! = 5*4*3*2*1 = 120
2. 3! = 3*2*1 = 6
Here, 5! is pronounced as "5 factorial", it is also called "5 bang" or "5 shriek".
There are many ways to write the factorial program in c language. Let's see the 2 ways to
write the factorial program.
1. #include<stdio.h>
2. main()
3. {
4. int i,fact=1,number;
5. printf("Enter a number: ");
6. scanf("%d",&number);
7. for(i=1;i<=number;i++){
8. fact=fact*i;
9. }
10. printf("Factorial of %d is: %d",number,fact);
11. return 0;
12. }
Output:
Enter a number: 5
Factorial of 5 is: 120
Armstrong Number in C
Before going to write the c program to check whether the number is Armstrong or not, let's
understand what is Armstrong number.
Armstrong number is a number that is equal to the sum of cubes of its digits. For example 0, 1,
153, 370, 371 and 407 are the Armstrong numbers.
1. 153 = (1*1*1)+(5*5*5)+(3*3*3)
2. where:
3. (1*1*1)=1
4. (5*5*5)=125
5. (3*3*3)=27
6. So:
7. 1+125+27=153
1. 371 = (3*3*3)+(7*7*7)+(1*1*1)
2. where:
3. (3*3*3)=27
4. (7*7*7)=343
5. (1*1*1)=1
6. So:
7. 27+343+1=371
1. #include<stdio.h>
2. main()
3. {
4. int n,r,sum=0,temp;
5. printf("enter the number=");
6. scanf("%d",&n);
7. temp=n;
8. while(n>0)
9. {
10. r=n%10;
11. sum=sum+(r*r*r);
12. n=n/10;
13. }
14. if(temp==sum)
15. printf("armstrong number ");
16. else
17. printf("not armstrong number");
18. return 0;
19. }
Output:
We can write c program without using main() function. To do so, we need to use #define
preprocessor directive.
1. #include<stdio.h>
2. #define start main
3. void start() {
4. printf("Hello");
5. }
Output:
Hello
Matrix multiplication in C
Matrix multiplication in C: We can add, subtract, multiply and divide 2 matrices. To do so, we
are taking input from the user for row number, column number, first matrix elements and second
matrix elements. Then we are performing multiplication on the matrices entered by the user.
In matrix multiplication first matrix one row element is multiplied by second matrix all column
elements.
Let's try to understand the matrix multiplication of 2*2 and 3*3 matrices by the figure given
below:
1. #include<stdio.h>
2. #include<stdlib.h>
3. main(){
4. int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
5. system("cls");
6. printf("enter the number of row=");
7. scanf("%d",&r);
8. printf("enter the number of column=");
9. scanf("%d",&c);
10. printf("enter the first matrix element=\n");
11. for(i=0;i<r;i++)
12. {
13. for(j=0;j<c;j++)
14. {
15. scanf("%d",&a[i][j]);
16. }
17. }
18. printf("enter the second matrix element=\n");
19. for(i=0;i<r;i++)
20. {
21. for(j=0;j<c;j++)
22. {
23. scanf("%d",&b[i][j]);
24. }
25. }
26.
27. printf("multiply of the matrix=\n");
28. for(i=0;i<r;i++)
29. {
30. for(j=0;j<c;j++)
31. {
32. mul[i][j]=0;
33. for(k=0;k<c;k++)
34. {
35. mul[i][j]+=a[i][k]*b[k][j];
36. }
37. }
38. }
39. //for printing result
40. for(i=0;i<r;i++)
41. {
42. for(j=0;j<c;j++)
43. {
44. printf("%d\t",mul[i][j]);
45. }
46. printf("\n");
47. }
48. return 0;
49. }
Output:
Let's try to understand the matrix multiplication of 3*3 and 3*3 matrices by the figure given
below: