EdisoftIndia C Tutorials
EdisoftIndia C Tutorials
Website: edusoftindia.com
AN INTRODUCTION TO C LANGUAGE
Introduction
C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the
UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in
1972.
In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now
known as the K&R standard.
The UNIX operating system, the C compiler, and essentially all UNIX application programs have been written
in C. C has now become a widely used professional language for various reasons −
• Easy to learn
• Structured language
• It produces efficient programs
• It can handle low-level activities
• It can be compiled on a variety of computer platforms
Facts about C
• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Print Spoolers
• Network Drivers
• Modern Programs
• Databases
• Language Interpreters
• Utilities
C Programs
A C program can vary from 3 lines to millions of lines and it should be written into one or more text files with
extension ".c"; for example, hello.c. You can use "vi", "vim" or any other text editor to write your C program
into a file.
Local Environment Setup
If you want to set up your environment for C programming language, you need the following two software
tools available on your computer, (a) Text Editor and (b) The C Compiler.
Text Editor
This will be used to type your program. Examples of few a editors include Windows Notepad, OS Edit
command, Brief, Epsilon, EMACS, and vim or vi.
The name and version of text editors can vary on different operating systems. For example, Notepad will be
used on Windows, and vim or vi can be used on windows as well as on Linux or UNIX.
The files you create with your editor are called the source files and they contain the program source codes. The
source files for C programs are typically named with the extension ".c".
Before starting your programming, make sure you have one text editor in place and you have enough
experience to write a computer program, save it in a file, compile it and finally execute it.
The C Compiler
The source code written in source file is the human readable source for your program. It needs to be
"compiled", into machine language so that your CPU can actually execute the program as per the instructions
given.
The compiler compiles the source codes into final executable programs. The most frequently used and free
available compiler is the GNU C/C++ compiler, otherwise you can have compilers either from HP or Solaris if
you have the respective operating systems.
The following section explains how to install GNU C/C++ compiler on various OS. We keep mentioning
C/C++ together because GNU gcc compiler works for both C and C++ programming languages.
Installation on UNIX/Linux
If you are using Linux or UNIX, then check whether GCC is installed on your system by entering the
following command from the command line −
$ gcc -v
If you have GNU compiler installed on your machine, then it should print a message as follows −
Using built-in specs.
Target: i386-redhat-linux
Configured with: ../configure --prefix=/usr .......
Thread model: posix
gcc version 4.1.2 20080704 (Red Hat 4.1.2-46)
If GCC is not installed, then you will have to install it yourself using the detailed instructions available
at http://gcc.gnu.org/install/
This tutorial has been written based on Linux and all the given examples have been compiled on the Cent OS
flavor of the Linux system.
Installation on Mac OS
If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode development environment from
Apple's web site and follow the simple installation instructions. Once you have Xcode setup, you will be able
to use GNU compiler for C/C++.
Xcode is currently available at developer.apple.com/technologies/tools/.
Installation on Windows
To install GCC on Windows, you need to install MinGW. To install MinGW, go to the MinGW
homepage, www.mingw.org, and follow the link to the MinGW download page. Download the latest version
of the MinGW installation program, which should be named MinGW-<version>.exe.
While installing Min GW, at a minimum, you must install gcc-core, gcc-g++, binutils, and the MinGW
runtime, but you may wish to install more.
Add the bin subdirectory of your MinGW installation to your PATH environment variable, so that you can
specify these tools on the command line by their simple names.
After the installation is complete, you will be able to run gcc, g++, ar, ranlib, dlltool, and several other GNU
tools from the Windows command line.
Hello World Example
A C program basically consists of the following parts −
• Preprocessor Commands
• Functions
• Variables
• Statements & Expressions
• Comments
Let us look at a simple code that would print the words "Hello World" −
#include <stdio.h>
int main()
{
/* my first program in C */
printf("Hello, World! \n");
return 0;
}
Let us take a look at the various parts of the above program −
• The first line of the program #include <stdio.h> is a preprocessor command, which tells a C compiler
to include stdio.h file before going to actual compilation.
• The next line int main() is the main function where the program execution begins.
• The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments in
the program. So such lines are called comments in the program.
• The next line printf(...) is another function available in C which causes the message "Hello, World!" to
be displayed on the screen.
• The next line return 0; terminates the main() function and returns the value 0.
Identifiers
A C identifier is a name used to identify a variable, function, or any other user-defined item. An identifier
starts with a letter A to Z, a to z, or an underscore '_' followed by zero or more letters, underscores, and digits
(0 to 9).
C does not allow punctuation characters such as @, $, and % within identifiers. C is a case-
sensitive programming language. Thus, Manpower and manpowerare two different identifiers in C. Here are
some examples of acceptable identifiers −
mohd zara abc move_name a_123
myname50 _temp j a23b9 retVal
Keywords
The following list shows the reserved words in C. These reserved words may not be used as constants or
variables or any other identifier names.
auto else long switch
break enum register typedef
case extern return union
char float short unsigned
const for signed void
continue goto sizeof volatile
default if static while
do int struct _Packed
double
Data Types
Data types in c refer to an extensive system used for declaring variables or functions of different types. The
type of a variable determines how much space it occupies in storage and how the bit pattern stored is
interpreted.
The types in C can be classified as follows −
S.N. Types & Description
1 Basic Types
They are arithmetic types and are further classified into:
(a) integer types
(b) floating-point types.
int main() {
return 0;
}
When you compile and execute the above program, it produces the following result on Linux −
Storage size for float : 4
Minimum float positive value: 1.175494E-38
Maximum float positive value: 3.402823E+38
Precision value: 6
Variable
A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C
has a specific type, which determines the size and layout of the variable's memory; the range of values that can
be stored within that memory; and the set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must begin with
either a letter or an underscore. Upper and lowercase letters are distinct because C is case-sensitive. Based on
the basic types explained in the previous chapter, there will be the following basic variable types −
Type Description
char Typically a single octet(one byte). This is an integer type.
int The most natural size of integer for the machine.
float A single-precision floating point value.
double A double-precision floating point value.
void Represents the absence of type.
Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the variable. A variable
definition specifies a data type and contains a list of one or more variables of that type as follows −
type variable_list;
Here, type must be a valid C data type including char, char, int, float, double, bool, or any user-defined object;
and variable_list may consist of one or more identifier names separated by commas. Some valid declarations
are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to create variables
named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal
sign followed by a constant expression as follows −
type variable_name = value;
Some examples are −
extern int d = 3, f = 5; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
•rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is
an expression that cannot have a value assigned to it which means an rvalue may appear on the right-
hand side but not on the left-hand side of an assignment.
Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric literals are
rvalues and so they may not be assigned and cannot appear on the left-hand side. Take a look at the following
valid and invalid statements −
int main()
{
printf("Hello\tWorld\n\n");
return 0;
}
When the above code is compiled and executed, it produces the following result −
Hello World
String Literals
String literals or constants are enclosed in double quotes "". A string contains characters that are similar to
character literals: plain characters, escape sequences, and universal characters.
You can break a long line into multiple lines using string literals and separating them using white spaces.
Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"
"hello, \
dear"
"hello, " "d" "ear"
Defining Constants
There are two simple ways in C to define constants −
• Using #define preprocessor.
• Using const keyword.
The #define Preprocessor
Given below is the form to use #define preprocessor to define a constant −
#define identifier value
The following example explains it in detail −
#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main()
{
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of area : 50
The const Keyword
You can use const prefix to declare constants with a specific type as follows −
const type variable = value;
The following example explains it in detail −
#include <stdio.h>
int main()
{
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of area : 50
C Programming Operators
Operators are the symbol which operates on value or a variable. For example: + is a operator to
perform addition.
C programming language has wide range of operators to perform various operations. For better
understanding of operators, these operators can be classified as:
Operators in C programming
Arithmetic Operators
Increment and Decrement Operators
Assignment Operators
Relational Operators
Logical Operators
Conditional Operators
Bitwise Operators
Special Operators
Arithmetic Operators
Operator Meaning of Operator
+ addition or unary plus
- subtraction or unary minus
* multiplication
/ division
% remainder after division( modulo division)
Example of working of arithmetic operators
/* Program to demonstrate the working of arithmetic operators in C. */
#include <stdio.h>
int main(){
int a=9,b=4,c;
c=a+b;
printf("a+b=%d\n",c);
c=a-b;
printf("a-b=%d\n",c);
c=a*b;
printf("a*b=%d\n",c);
c=a/b;
printf("a/b=%d\n",c);
c=a%b;
printf("Remainder when a divided by b=%d\n",c);
return 0;
}
a+b=13
a-b=5
a*b=36
a/b=2
Relational Operator
Relational operators checks relationship between two operands. If the relation is true, it returns value
1 and if the relation is false, it returns value 0. For example:
a>b
Here, > is a relational operator. If a is greater than b, a>b returns 1 if not then, it returns 0.
Relational operators are used in decision making and loops in C programming.
Operator Meaning of Operator Example
== Equal to 5==3 returns false (0)
> Greater than 5>3 returns true (1)
Logical Operators
Logical operators are used to combine expressions containing relation operators. In C, there are 3
logical operators:
Operator Meaning of Operator Example
&& Logial AND If c=5 and d=2 then,((c==5) && (d>5)) returns false.
|| Logical OR If c=5 and d=2 then, ((c==5) || (d>5)) returns true.
! Logical NOT If c=5 then, !(c==5) returns false.
Explanation
For expression, ((c==5) && (d>5)) to be true, both c==5 and d>5 should be true but, (d>5) is false
in the given example. So, the expression is false. For expression ((c==5) || (d>5)) to be true, either
the expression should be true. Since, (c==5) is true. So, the expression is true. Since,
expression (c==5) is true, !(c==5) is false.
Conditional Operator
Conditional operator takes three operands and consists of two symbols ? and : . Conditional
operators are used for decision making in C. For example:
c=(c>0)?10:-10;
If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.
Bitwise Operators
A bitwise operator works on each bit of data. Bitwise operators are used in bit level programming.
Operators Meaning of operators
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right
Bitwise operator is advance topic in programming . Learn more about bitwise operator in C
programming.
Other Operators
Comma Operator
Comma operators are used to link related expressions together. For example:
int a,c=5,d;
The sizeof operator
It is a unary operator which is used in finding the size of data type, constant, arrays, structure etc.
For example:
#include <stdio.h>
int main(){
int a;
float b;
double c;
char d;
printf("Size of int=%d bytes\n",sizeof(a));
printf("Size of float=%d bytes\n",sizeof(b));
printf("Size of double=%d bytes\n",sizeof(c));
printf("Size of char=%d byte\n",sizeof(d));
return 0;
INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 11
AN INTRODUCTION TO C LANGUAGE
}
Output
conditional_expression?expression1:expression2
If the test condition is true, expression1 is returned and if false expression2 is returned.
Example of conditional operator
#include <stdio.h>
int main(){
char feb;
int days;
printf("Enter l if the year is leap year otherwise enter 0: ");
scanf("%c",&feb);
days=(feb=='l')?29:28;
/*If test condition (feb=='l') is true, days will be equal to 29. */
/*If test condition (feb=='l') is false, days will be equal to 28. */
printf("Number of days in February = %d",days);
return 0;
}
Output
C if Statement
if (test expression)
{
statement/s to be executed if test expression is true;
}
The if statement checks whether the text expression inside parenthesis () is true or not. If the test
expression is true, statement/s inside the body of if statement is executed but if test is false,
statement/s inside body of if is ignored.
Flowchart of if statement
Example 1: C if statement
Write a C program to print the number entered by user only if the number entered is negative.
#include <stdio.h>
int main(){
int num;
printf("Enter a number to check.\n");
scanf("%d",&num);
if(num<0) { /* checking whether number is less than 0 or not. */
printf("Number = %d\n",num);
}
/*If test condition is true, statement above will be executed, otherwise it will not be executed */
printf("The if statement in C programming is easy.");
return 0;
}
Output 1
Enter a number to check.
-2
Number = -2
The if statement in C programming is easy.
When user enters -2 then, the test expression (num<0) becomes true. Hence, Number = -2 is
displayed in the screen.
Output 2
Enter a number to check.
5
The if statement in C programming is easy.
When the user enters 5 then, the test expression (num<0) becomes false. So, the statement/s inside
body of if is skipped and only the statement below it is executed.
C if...else statement
The if...else statement is used if the programmer wants to execute some statement/s when the test
expression is true and execute some other statement/s if the test expression is false.
Syntax of if...else
if (test expression) {
statements to be executed if test expression is true;
}
else {
statements to be executed if test expression is false;
}
while loop
while loop is a control flow statement that allows code to be executed repeatedly based on a given
boolean condition. The while loop can be thought of as a repeating if statement.
while(condition_to_continue)
{
……………………;
……Statements…..;
……………………;
}
// Write a program to print numbers between 1 to 20.
#include<stdio.h>
void main()
{
int i=1;
while(i<=20)
{
printf(“\n%d”,i);
i++;
}
}
#include<stdio.h>
void main()
{
int n, num, i =1, sum=0;
INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 17
AN INTRODUCTION TO C LANGUAGE
Break & Continue: “Break” and “Continue” are ‘C’ keywords that work with a loop. The work of
“break” is to stop the execution of the loop whereas the work of “continue” is to continue the
execution of the loop. Consider the following example:
#include<stdio.h>
void main()
{
int a=0;
while(a<20)
{
a++;
if(a%7==0)
break;
printf(“%d”,a);
}
}
#include<stdio.h>
void main()
{
int a=0;
while(a<20)
{
a++;
if(a%3==0)
continue;
printf(“%d”,a);
}
}
Nested While: Nesting of while means using “while” loop within another “while” loop. For example:
int i=1,j=1;
while(i<=3)
while(j<=3)
printf(“\n%d%d”,i,j);
DO-WHILE: It works exactly like “while” but the main difference between the two is that
“while” loop first checks the condition and then executes the statements within it. If the condition
evaluates to False on the very first time, loop will terminate.
INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 18
AN INTRODUCTION TO C LANGUAGE
On the other hand, a “do-while loop first executes the statements at least once and then
checks the condition.
do
{
……………………;
……Statements…..;
……………………;
}while(condition);
int a=5;
do
{
printf(“%d”,a);
a++;
}while(a>5&&a<10);
int a=5;
while(a>5&&a<10)
{
printf(“%d”,a);
a++;
}
#include<stdio.h>
void main()
{
int n;
n=1;
while(n<=100)
{
printf(“%d”,n);
n++;
}
#include<stdio.h>
void main()
{
long int n, num;
printf(“Enter a number:”);
scanf(“%ld”,&n);
printf(“The reverse order of %ld is”,n);
while(n>0)
{
num=n%10;
printf(“%d”,num);
n=n/10;
}
}
FOR LOOP: for loop is another looping structure with some extra facilities over “while” loop.
#include<stdio.h>
void main()
{
INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 20
AN INTRODUCTION TO C LANGUAGE
int n;
for(n=1;n<=100;n++ )
{
Printf(“%d”,n);
}
}
#include<stdio.h>
void main()
{
long int n, sum;
printf(“Enter a number: ”);
scanf(“%ld”,&n);
printf(“The reverse number is “);
for( sum = 0 ; n ; )
{
sum=sum*10+n%10;
n=n/10;
}
printf(“%ld”,sum);
}
Nested for: Nesting of for means using “for” loop within another “for” loop. For example:
int i=1,j=1;
for(a=1;a<=3;a++)
for(j=1;j<=3;j++)
printf(“\n%d%d”,a,j);
#include<stdio.h>
void main()
{
float sum=0,f;
int a,j;
printf(“Enter the length of the series: ”);
scanf(“%d”,&n);
for(a=1;a<=n;a++)
{
for(j=1, f=1;j<=a;j++)
{
f=f*j;
sum=sum+(2*a-1)/f;
}
printf(“\nThe sum of the series of %d elements is %f”,n,sum);
}
GOTO: Goto transfers the control of the program to any marked line or label in the program.
INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 21
AN INTRODUCTION TO C LANGUAGE
// WAP to calculate the sum of n numbers entered by the user using goto.
#include<stdio.h>
void main()
{
int n,sum=0;
char more;
again:
printf(“Enter a number:”);
scanf(“%d”,&n);
fflush(stdin);
sum+=n;
printf(“Do you want to enter number(y / n)?”);
scanf(“%c”,&more);
if(more==’y’||more==’Y’)
goto again;
printf(“The sum of numbers is %d”, sum);
}
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j,prime;
clrscr();
printf("\n Prime no upto what?");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
prime=1;
for(j=2;j<i;j++)
if(i%j==0)
{
prime=0;
break;
}
if(prime)
printf("\n%d",i);
}
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int f1,f2,f3,n,i;
printf("Enter how many terms");
scanf("%d",&n);
if(n<2)
{
printf("\n Invalid Input");
// exit(0);
}
f1=1;
f2=1;
i=0;
do
{
f3=f1+f2;
printf("\n%d",f3);
i++;
f1=f2;
f2=f3;
}
while(i<n);
getch();
}
#include<stdio.h>
void main()
{
int dividend,divisor,n,m,remainder,a;
printf("enter two numbers:");
scanf("%d%d",&n,&m);
if(n>m)
{
dividend=n;
divisor=m;
}
else
{
dividend=m;
divisor=n;
}
for(a=0;;a++)
{
remainder=dividend%divisor;
if(!remainder)
{
printf("\nh.c.f.is %d",divisor);
break;
}
else
{
dividend=divisor;
divisor=remainder;
}
}
void main() * * * * *
{ * * * * * *
int n,a,j; * * * * * * *
printf("Enter the length :"); * * * * * * * *
scanf("%d",&n);
for(a=1;a<=n;++a)
{
for(j=1;j<=5-a;j++)
printf("A");
for(j=1;j<=a;j++)
printf("* ");
printf("\n");
}
}
#include<stdio.h>
void main()
{ * * * * * *
int n,a,j; * * * * *
printf("Enter the length:"); * * * *
scanf("%d",&n); * * *
for(a=1;a<=n-1;a++) * *
{ *
for(j=15-n+a;j>=1;j--)
printf(" ");
for(j=1;j<=n-a;j++)
printf("* ");
printf("\n");
}
}
#include<stdio.h>
void main()
{
int COL,ROW,row,column,y;
printf("Enter the Column and Row :");
scanf("%d%d",&COL,&ROW);
row=1;
do {
column=1;
do {
y=row*column;
printf("%4d",y);
column++;
}
while(column<=COL);
printf("\n");
row++;
}while(row<=ROW);
}
#include<stdio.h>
void main()
{
int row,column,y;
for(row=1;row<=10;row++)
{
for(column=1;column<=10;column++)
{
y=row*column;
printf(“%4d”,y);
}
printf(“\n”);
}
}
#include<stdio.h>
void main()
{
int count,n;
float x,y;
printf(“Enter the value of x and n: “);
scanf(“%f%d”,&x,&n);
y=1.0;
count=1;
while(count<=n)
{
y=y*x;
count++;
}
printf(“\nx=%f; n=%d; x to power n=%f\n”,x,n,y);
}
Write a program to find the sum of first n natural numbers where n is entered by user. Note:
1,2,3... are called natural numbers.
#include <stdio.h>
int main(){
int n, count, sum=0;
printf("Enter the value of n.\n");
scanf("%d",&n);
for(count=1;count<=n;++count) //for loop terminates if count>n
{
sum+=count; /* this statement is equivalent to sum=sum+count */
}
printf("Sum=%d",sum);
return 0;
}
Enter a number.
Factorial=120
do...while loop
In C, do...while loop is very similar to while loop. Only difference between these two loops is that,
in while loops, test expression is checked at first but, in do...while loop code is executed at first then
the condition is checked. So, the code are executed at least once in do...while loops.
do {
some code/s;
break;
The break statement can be used in terminating all three loops for, while and do...while loops.
The figure below explains the working of break statement in all three type of loops.
/* C program to demonstrate the working of break statement by terminating a loop, if user inputs
negative number*/
# include <stdio.h>
int main(){
float num,average,sum;
int i,n;
printf("Maximum no. of inputs\n");
scanf("%d",&n);
for(i=1;i<=n;++i){
printf("Enter n%d: ",i);
scanf("%f",&num);
if(num<0.0)
break; //for loop breaks if num<0.0
sum=sum+num;
}
average=sum/(i-1);
printf("Average=%.2f",average);
return 0;
}
Output
Syntax of continue Statement
continue;
Just like break, continue is also used with conditional if statement.
For better understanding of how continue statements works in C programming. Analyze the figure
below which bypasses some code/s inside loops using continue statement.
product*=num;
}
printf("product=%d",product);
return 0;
}
The switch statements evaluate the expression and then look for its value among the case constants. If the value
is found among a constraints listed, then the statements in that statements area executed. Otherwise if there is a
default then the program branches to that statement list. The syntax of the
Syntax of switch...case
switch (n) {
case constant1:
break;
case constant2:
code/s to be executed if n equals to constant2;
break;
.
.
.
default:
code/s to be executed if n doesn't match to any cases;
}
The value of n is either an integer or a character in above syntax. If the value of n matches constant
in case, the relevant codes are executed and control moves out of the switch statement. If
the ndoesn't matches any of the constant in case, then the default codes are executed and control
moves out of switch statement.
A, a=Very good
B, a= Good
C, c= Satisfactory
F, f= Fail
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
printf("give the charector");
scanf("%c",&ch);
switch(ch)
{
case 'a':
case 'A': printf("very good");
break;
case 'b':
case 'B': printf("good");
break;
case 'c':
case 'C': printf("satisfactory");
break;
case 'F':
case 'f': printf("fail");
break;
default :printf("invalid input");
}
getch();
}
3. Write a program to check that the inputted value is vowel or not.
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
printf("\n Give a charector:");
scanf("%c",&ch);
switch(ch)
{
case 'a':
case 'A':printf("you have typed the vowel A");
break;
case 'e':
case 'E':printf("you have typed the vowel E");
break;
case 'i':
case 'I':printf("you have typed the vowel I");
break;
INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 34
AN INTRODUCTION TO C LANGUAGE
case 'o':
case 'O':printf("you have typed the vowel O");
break;
case 'u':
case 'U':printf("you have typed the vowel U");
break;
case 0: printf("\n the end");
default :printf("\n You have typed a consonants:");
}
getch();
}
4. Write a program to make the computer work like a pocket calculator that is it should
input the two number and perform all the arithmetic operation on the given number’s.
#include<stdio.h>
#include<conio.h>
main()
{
int a,b,c,op;
printf("\n 1. To add");
printf("\n 2. To subtract");
printf("\n 3. To multiply");
printf("\n 4. To Divide");
printf("\n 5. To exit");
printf("\n Enter your choice:");
scanf("%d",&op);
switch(op)
{
case 1: printf("Give the value of a and b");
scanf("%d %d",&a,&b);
c=a+b;
printf("the addition of two no's are=%d",c);
break;
case 2: printf("Give the value of a and b");
scanf("%d %d",&a,&b);
c=a-b;
printf("the subtraction of two no's are=%d",c);
break;
case 3: printf("Give the value of a and b");
scanf("%d %d",&a,&b);
c=a*b;
printf("the multiplication of two no's are=%d",c);
break;
break;
case 0: printf("\n the end");
default :printf("\n invalid choice");
}
getch();
}
5. Write a program that asks user an arithmetic operator('+','-','*' or '/') and two
operands and perform the corresponding calculation on the operands.
# include <stdio.h>
int main() {
char o;
float num1,num2;
printf("Select an operator either + or - or * or / \n");
scanf("%c",&o);
printf("Enter two operands: ");
scanf("%f%f",&num1,&num2);
switch(o) {
case '+':
printf("%.1f + %.1f = %.1f",num1, num2, num1+num2);
break;
case '-':
printf("%.1f - %.1f = %.1f",num1, num2, num1-num2);
break;
case '*':
printf("%.1f * %.1f = %.1f",num1, num2, num1*num2);
break;
case '/':
printf("%.1f / %.1f = %.1f",num1, num2, num1/num2);
break;
default:
/* If operator is other than +, -, * or /, error message is shown */
printf("Error! operator is not correct");
break;
}
return 0;
}
goto label;
.............
.............
.............
label:
statement;
In this syntax, label is an identifier. When, the control of program reaches to goto statement, the
control of the program will jump to the label: and executes the code below it.
C Programming Functions
In programming, a function is a segment that groups code to perform a specific task.
A C program has at least one function main( ). Without main() function, there is technically no C
program.
Types of C functions
There are two types of functions in C programming:
• Library function
• User defined function
Library function
Library functions are the in-built function in C programming system. For example:
main()
- The execution of every C program starts from this main() function.
printf()
- prinf() is used for displaying output in C.
scanf()
- scanf() is used for taking input in C.
Visit this page to learn more about library functions in C programming language.
User defined function
C allows programmer to define their own function according to their requirement. These types of
functions are known as user-defined functions. Suppose, a programmer wants to find factorial of a
number and check whether it is prime or not in same program. Then, he/she can create two separate
user-defined functions in that program: one for finding factorial and other for checking whether it is
prime or not.
#include <stdio.h>
void function_name(){
................
................
int main(){
...........
...........
function_name();
...........
...........
}
As mentioned earlier, every C program begins from main() and program starts executing the codes
inside main() function. When the control of program reaches
to function_name() inside main()function. The control of program jumps to void
function_name() and executes the codes inside it. When all the codes inside that user -defined
function are executed, control of the program jumps to the statement just after function_name() from
where it is called. Analyze the figure below for understanding the concept of function in C
programming. Visit this page to learn in detail about user-defined functions.
Function prototype(declaration):
Every function in C programming should be declared before they are used. These type of declaration
are also called function prototype. Function prototype gives compiler information about function
name, type of arguments to be passed and return type.
Syntax of function prototype
Function call
Control of the program cannot be transferred to user -defined function unless it is called invoked.
Syntax of function call
function_name(argument(1),....argument(n));
In the above example, function call is made using statement add(num1,num2); from main(). This
make the control of program jump from that statement to function definition and executes the codes
inside that function.
Function definition
Function definition contains programming codes to perform specific task.
Syntax of function definition
//body of function
}
Function definition has two major components:
1. Function declarator
Function declarator is the first line of function definition. When a function is called, control of the
program is transferred to function declarator.
Syntax of function declarator
Arguments that are passed in function call and arguments that are accepted in function definition
should have same data type. For example:
If argument num1 was of int type and num2 was of float type then, argument variable a should be of
type int and b should be of type float,i.e ., type of argument during function call and function
definition should be same.
A function can be called with or without an argument.
Return Statement
Return statement is used for returning a value from function definition to calling function.
Syntax of return statement
return (expression);
For example:
return a;
return (a+b);
In above example, value of variable add in add() function is returned and that value is stored in
variable sum in main() function. The data type of expression in return statement should also match
the return type of function.
/*C program to check whether a number entered by user is prime or not using function with no
arguments and no return value*/
#include <stdio.h>
void prime();
int main(){
prime(); //No argument is passed to prime().
return 0;
}
void prime(){
/* There is no return value to calling function main(). Hence, return type of prime() is void */
int num,i,flag=0;
printf("Enter positive integer enter to check:\n");
scanf("%d",&num);
for(i=2;i<=num/2;++i){
if(num%i==0){
flag=1;
}
}
if (flag==1)
printf("%d is not prime",num);
else
printf("%d is prime",num);
}
Function prime() is used for asking user a input, check for whether it is prime of not and display it
accordingly. No argument is passed and returned form prime() function.
/*C program to check whether a number entered by user is prime or not using function with no
arguments but having return value */
#include <stdio.h>
int input();
int main(){
int num,i,flag = 0;
num=input(); /* No argument is passed to input() */
for(i=2; i<=num/2; ++i){
if(num%i==0){
flag = 1;
break;
}
}
if(flag == 1)
printf("%d is not prime",num);
else
printf("%d is prime", num);
return 0;
}
int input(){ /* Integer value is returned from input() to calling function */
int n;
printf("Enter positive integer to check:\n");
scanf("%d",&n);
return n;
}
There is no argument passed to input() function But, the value of n is returned
from input() tomain() function.
/*Program to check whether a number entered by user is prime or not using function with
arguments and no return value */
#include <stdio.h>
void check_display(int n);
int main(){
int num;
printf("Enter positive enter to check:\n");
scanf("%d",&num);
check_display(num); /* Argument num is passed to function. */
return 0;
}
void check_display(int n){
/* There is no return value to calling function. Hence, return type of function is void. */
int i, flag = 0;
for(i=2; i<=n/2; ++i){
if(n%i==0){
flag = 1;
break;
}
}
if(flag == 1)
printf("%d is not prime",n);
else
printf("%d is prime", n);
}
Here, check_display() function is used for check whether it is prime or not and display it
accordingly. Here, argument is passed to user-defined function but, value is not returned from it to
calling function.
/* Program to check whether a number entered by user is prime or not using function with
argument and return value */
#include <stdio.h>
int check(int n);
int main(){
int num,num_check=0;
printf("Enter positive enter to check:\n");
scanf("%d",&num);
num_check=check(num); /* Argument num is passed to check() function. */
if(num_check==1)
printf("%d is not prime",num);
else
printf("%d is prime",num);
return 0;
}
int check(int n){
/* Integer value is returned from function check() */
int i;
for(i=2;i<=n/2;++i){
if(n%i==0)
return 1;
}
return 0;
}
Here, check() function is used for checking whether a number is prime or not. In this program, input
from user is passed to function check() and integer value is returned from it. If input the number is
prime, 0 is returned and if number is not prime, 1 is returned.
C Programming Recursion
A function that calls itself is known as recursive function and this technique is known as recursion in
C programming.
Example of recursion in C programming
Write a C program to find sum of first n natural numbers using recursion. Note: Positive
integers are known as natural number i.e. 1, 2, 3....n
#include <stdio.h>
int sum(int n);
int main(){
int num,add;
printf("Enter a positive integer:\n");
scanf("%d",&num);
add=sum(num);
printf("sum=%d",add);
}
int sum(int n){
if(n==0)
return n;
else
return n+sum(n-1); /*self call to function sum() */
}
Output
15
In, this simple C program, sum() function is invoked from the same function. If n is not equal to 0
then, the function calls itself passing argument 1 less than the previous argument it was called with.
Suppose, n is 5 initially. Then, during next function calls, 4 is passed to function and the value of
argument decreases by 1 in each recursive call. When, n becomes equal to 0, the value of n is
returned which is the sum numbers from 5 to 1.
For better visualization of recursion in this example:
sum(5)
=5+sum(4)
=5+4+sum(3)
=5+4+3+sum(2)
=5+4+3+2+sum(1)
=5+4+3+2+1+sum(0)
=5+4+3+2+1+0
=5+4+3+2+1
=5+4+3+3
=5+4+6
=5+10
=15
Every recursive function must be provided with a way to end the recursion. In this example
when, n is equal to 0, there is no recursive call and recursion ends.
Advantages and Disadvantages of Recursion
Recursion is more elegant and requires few variables which make program clean. Recursion can be
used to replace complex nesting code by dividing the problem into same problem of its sub -type.
In other hand, it is hard to think the logic of a recursive function. It is also difficult to debug the
code containing recursion.
C Programming Storage Class
Every variable in C programming has two properties: type and storage class. Type refers to the data
type of variable whether it is character or integer or floating -point value etc. And storage class
determines how long it stays in existence.
There are 4 types of storage class:
1. automatic
2. external
3. static
4. register
auto
Variables declared inside the function body are automatic by default. These variable are also known
as local variables as they are local to the function and doesn't have meaning outside that function
Since, variable inside a function is automatic by default, keyword auto are rarely used.
#include
void Check();
int a=5;
/* a is global variable because it is outside every function */
int main(){
a+=4;
Check();
return 0;
}
void Check(){
++a;
/* ----- Variable a is not declared in this function but, works in any function as they are global
variable ------- */
printf("a=%d\n",a);
}
Output
a=10
register
Example of register variable
register int a;
Register variables are similar to automatic variable and exists inside that particular function only.
If the compiler encounters register variable, it tries to store variable in microprocessor's register
rather than memory. Value stored in register are much faster than that of memory.
In case of larger program, variables that are used in loops and function parameters are declared
register variables.
Since, there are limited number of register in processor and if it couldn't store the variable in
register, it will automatically store it in memory.
static int i;
Here, i is a static variable.
Example to demonstrate the static variable
#include <stdio.h>
void Check();
int main(){
Check();
Check();
Check();
}
void Check(){
static int c=0;
printf("%d\t",c);
c+=5;
}
Output
0 5 10
During first function call, it will display 0. Then, during second function call, variable c will not be
initialized to 0 again, as it is static variable. So, 5 is displayed in second function call and 10 in third
call.
If variable c had been automatic variable, the output would have been:
0 0 0
C Programming Function Example
This page contains examples and source code on how to work with user -defined function. To
understand all the program on this page, you should have knowledge of following function topics:
1. User-Defined Function
2. User-Defined Function Types
3. Storage class( Specially, local variables )
4. Recursion
C Function Examples
data_type array_name[array_size];
For example:
int age[5];
Here, the name of array is age. The size of array is 5,i.e., there are 5 items(elements) of array age.
All element in an array are of the same type (int, in this case).
Array elements
Size of array defines the number of elements in an array. Each element of array can be accessed and
used by user according to the need of program. For example:
int age[5];
int age[5]={2,4,34,3,4};
It is not necessary to define the size of arrays during initialization.
int age[]={2,4,34,3,4};
In this case, the compiler determines the size of array by calculating the number of elements of an
array.
scanf("%d",&age[2]);
scanf("%d",&age[i]);
/* Because, the first element of array is age[0], second is age[1], ith is age[i -1] and (i+1)th is
age[i]. */
printf("%d",age[0]);
printf("%d",age[i]);
#include <stdio.h>
int main(){
int marks[10],i,n,sum=0;
printf("Enter number of students: ");
scanf("%d",&n);
for(i=0;i<n;++i){
printf("Enter marks of student%d: ",i+1);
scanf("%d",&marks[i]);
sum+=marks[i];
}
printf("Sum= %d",sum);
return 0;
}
Output
sum=45
Important thing to remember in C arrays
Suppose, you declared the array of 10 students. For example: arr[10]. You can use array members
from arr[0] to arr[9]. But, what if you want to use element arr[10], arr[13] etc. Compiler may not
show error using these elements but, may cause fatal error during program execution.
C Programming Multidimensional Arrays
C programming language allows programmer to create arrays of arrays known as multidimensional
arrays. For example:
float a[2][6];
Here, a is an array of two dimension, which is an example of multidimensional array.
For better understanding of multidimensional arrays, array elements of above example can be thinked
of as below:
OR
OR
int c[2][3]={1,3,0,-1,5,9};
Initialization Of three-dimensional Array
double cprogram[3][2][4]={
};
Suppose there is a multidimensional array arr[i][j][k][m]. Then this array can hold i*j*k*m numbers
of data.
Similarly, the array of any dimension can be initialized in C programming.
Example of Multidimensional Array In C
Write a C program to find sum of two matrix of order 2*2 using multidimensional arrays
where, elements of matrix are entered by user.
#include <stdio.h>
int main(){
float a[2][2], b[2][2], c[2][2];
int i,j;
printf("Enter the elements of 1st matrix\n");
/* Reading two dimensional Array with the help of two for loop. If there was an array of 'n'
dimension, 'n' numbers of loops are needed for inserting data to array.*/
for(i=0;i<2;++i)
for(j=0;j<2;++j){
printf("Enter a%d%d: ",i+1,j+1);
scanf("%f",&a[i][j]);
}
printf("Enter the elements of 2nd matrix\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j){
printf("Enter b%d%d: ",i+1,j+1);
scanf("%f",&b[i][j]);
}
for(i=0;i<2;++i)
for(j=0;j<2;++j){
/* Writing the elements of multidimensional array using loop. */
c[i][j]=a[i][j]+b[i][j]; /* Sum of corresponding elements of two arrays. */
}
printf("\nSum Of Matrix:");
for(i=0;i<2;++i)
for(j=0;j<2;++j){
printf("%.1f\t",c[i][j]);
if(j==1) /* To display matrix sum in order. */
printf("\n");
}
return 0;
}
Ouput
Enter a11: 2;
Enter a22: 2;
Enter b12: 0;
Sum Of Matrix:
2.2 0.5
-0.9 25.0
C Programming Arrays and Functions
In C programming, a single array element or an entire array can be passed to a function. Also, both
one-dimensional and multi-dimensional array can be passed to function as argument.
#include <stdio.h>
void display(int a)
{
printf("%d",a);
}
int main(){
int c[]={2,3,4};
display(c[2]); //Passing array element c[2] only.
return 0;
}
Output
4
Single element of an array can be passed in similar manner as passing variable to a function.
Passing entire one-dimensional array to a function
While passing arrays to the argument, the name of the array is passed as an argument(,i.e, starting
address of memory area is passed as argument).
Write a C program to pass an array containing age of person to a function. This function
should find average age and display the average age in main function.
#include <stdio.h>
float average(float a[]);
int main(){
float avg, c[]={23.4, 55, 22.6, 3, 40.5, 18};
avg=average(c); /* Only name of array is passed as argument. */
printf("Average age=%.2f",avg);
return 0;
}
float average(float a[]){
int i;
float avg, sum=0.0;
for(i=0;i<6;++i){
sum+=a[i];
}
avg =(sum/6);
return avg;
}
Output
Average age=27.08
#include
void Function(int c[2][2]);
int main(){
int c[2][2],i,j;
printf("Enter 4 numbers:\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j){
scanf("%d",&c[i][j]);
}
Function(c); /* passing multi-dimensional array to function */
return 0;
}
void Function(int c[2][2]){
/* Instead to above line, void Function(int c[][2]){ is also valid */
int i,j;
printf("Displaying:\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j)
printf("%d\n",c[i][j]);
}
Output
Enter 4 numbers:
Displaying:
5
C Programming Array and Pointer Examples
This page contains examples and source code on arrays and pointers. To understand all program on
this page, you should have knowledge of following array and pointer topics:
1. Arrays
2. Multi-dimensional Arrays
3. Pointers
4. Array and Pointer Relation
5. Call by Reference
6. Dynamic Memory Allocation
C Programming Structure
Structure is the collection of variables of different types under a single name for better handling. For
example: You want to store the information about person about his/her name, citizenship number and
salary. You can create these information separately but, better approach will be collection of these
information under single name because all these information are related to person.
Structure Definition in C
Keyword struct is used for creating a structure.
Syntax of structure
struct structure_name
data_type member1;
data_type member2;
data_type memeber;
};
INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 54
AN INTRODUCTION TO C LANGUAGE
struct person
char name[50];
int cit_no;
float salary;
};
This declaration above creates the derived data type struct person.
struct person
char name[50];
int cit_no;
float salary;
};
struct person
char name[50];
int cit_no;
float salary;
p2.salary
Example of structure
Write a C program to add two distances entered by user. Measurement of distance should be in
inch and feet.(Note: 12 inches = 1 foot)
#include <stdio.h>
struct Distance{
int feet;
float inch;
}d1,d2,sum;
int main(){
printf("1st distance\n");
printf("Enter feet: ");
scanf("%d",&d1.feet); /* input of feet for structure variable d1 */
printf("Enter inch: ");
scanf("%f",&d1.inch); /* input of inch for structure variable d1 */
printf("2nd distance\n");
printf("Enter feet: ");
scanf("%d",&d2.feet); /* input of feet for structure variable d2 */
printf("Enter inch: ");
scanf("%f",&d2.inch); /* input of inch for structure variable d2 */
sum.feet=d1.feet+d2.feet;
sum.inch=d1.inch+d2.inch;
if (sum.inch>12){ //If inch is greater than 12, changing it to feet.
++sum.feet;
sum.inch=sum.inch-12;
}
printf("Sum of distances=%d\'-%.1f\"",sum.feet,sum.inch);
/* printing sum of distance d1 and d2 */
return 0;
}
Output
1st distance
Enter feet: 12
2nd distance
Enter feet: 2
int imag;
float real;
}comp;
Inside main:
comp c1,c2;
Here, typedef keyword is used in creating a type comp(which is of type as struct complex). Then,
two structure variables c1 and c2 are created by this comp type.
struct complex
int imag_value;
float real_value;
};
struct number{
int real;
}n1,n2;
Suppose you want to access imag_value for n2 structure variable then, structure
membern1.c1.imag_value is used.
Programming Structure and Pointer
Pointers can be accessed along with structures. A pointer variable of structure can be created as
below:
struct name {
member1;
member2;
};
ptr=(cast-type*)malloc(byte-size)
Example to use structure's member through pointer using malloc() function.
#include <stdio.h>
#include<stdlib.h>
struct name {
int a;
float b;
char c[30];
};
int main(){
struct name *ptr;
int i,n;
printf("Enter n: ");
scanf("%d",&n);
ptr=(struct name*)malloc(n*sizeof(struct name));
/* Above statement allocates the memory for n structures with pointer ptr pointing to base address
*/
for(i=0;i<n;++i){
printf("Enter string, integer and floating number respectively:\n");
scanf("%s%d%f",&(ptr+i)->c,&(ptr+i)->a,&(ptr+i)->b);
}
printf("Displaying Infromation:\n");
for(i=0;i<n;++i)
printf("%s\t%d\t%.2f\n",(ptr+i)->c,(ptr+i)->a,(ptr+i)->b);
return 0;
}
Output
Enter n: 2
Programming
3.2
Structure
2.3
Displaying Information
Programming 2 3.20
Structure 6 2.30
C Programming Structure and Function
In C, structure can be passed to functions by two methods:
1. Passing by value (passing actual value as argument)
2. Passing by reference (passing address of an argument)
Passing structure by value
A structure variable can be passed to the function as an argument as normal variable. If structure is
passed by value, change made in structure variable in function definition does not reflect in original
structure variable in calling function.
Write a C program to create a structure student, containing name and roll. Ask user the name and roll
of a student in main function. Pass this structure to a function and display the information in that
function.
#include <stdio.h>
struct student{
char name[50];
int roll;
};
void Display(struct student stu);
/* function prototype should be below to the structure declaration otherwise compiler shows error
*/
int main(){
struct student s1;
printf("Enter student's name: ");
scanf("%s",&s1.name);
Output
Roll: 149
Passing structure by reference
The address location of structure variable is passed to function while passing it by reference. If
structure is passed by reference, change made in structure variable in function definition reflects in
original structure variable in the calling function.
Write a C program to add two distances(feet-inch system) entered by user. To solve this
program, make a structure. Pass two structure variable (containing distance in feet and inch) to
add function by reference and display the result in main function without returning it.
#include <stdio.h>
struct distance{
int feet;
float inch;
};
void Add(struct distance d1,struct distance d2, struct distance *d3);
int main()
{
struct distance dist1, dist2, dist3;
printf("First distance\n");
printf("Enter feet: ");
scanf("%d",&dist1.feet);
printf("Enter inch: ");
scanf("%f",&dist1.inch);
printf("Second distance\n");
printf("Enter feet: ");
scanf("%d",&dist2.feet);
printf("Enter inch: ");
scanf("%f",&dist2.inch);
Add(dist1, dist2, &dist3);
/*passing structure variables dist1 and dist2 by value whereas passing structure variable dist3 by
reference */
printf("\nSum of distances = %d\'-%.1f\"",dist3.feet, dist3.inch);
return 0;
}
void Add(struct distance d1,struct distance d2, struct distance *d3)
{
/* Adding distances d1 and d2 and storing it in d3 */
d3->feet=d1.feet+d2.feet;
d3->inch=d1.inch+d2.inch;
if (d3->inch>=12) { /* if inch is greater or equal to 12, converting it to feet. */
d3->inch-=12;
++d3->feet;
}
}
Output
First distance
Enter feet: 12
Second distance
Enter feet: 5
union car{
char name[50];
int price;
};
Union variables can be created in similar manner as structure variable.
union car{
char name[50];
int price;
OR;
INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 61
AN INTRODUCTION TO C LANGUAGE
union car{
char name[50];
int price;
};
-------Inside Function-----------
size of union = 32
size of structure = 40
There is difference in memory allocation between union and structure as suggested in above example. The
amount of memory required to store a structure variables is the sum of memory size of all members.
But, the memory required to store a union variable is the memory required for largest element of an union.
#include <stdio.h>
union job {
char name[32];
float salary;
int worker_no;
}u;
int main(){
printf("Enter name:\n");
scanf("%s",&u.name);
scanf("%f",&u.salary);
printf("Displaying\nName :%s\n",u.name);
printf("Salary: %.1f",u.salary);
return 0;
}
Output
Enter name
Hillary
Enter salary
1234.23
Displaying
Name: f%Bary
Salary: 1234.2
Note: You may get different garbage value of name.
Why this output?
Initially, Hillary will be stored in u.name and other members of union will contain garbage value. But when
user enters value of salary, 1234.23 will be stored in u.salary and other members will contain garbage value.
Thus in output, salary is printed accurately but, name displays some random string.
Passing Union To a Function
Union can be passed in similar manner as structures in C programming. Visit this page to learn more
about: How structure can be passed to function in C programming?
◄ Previous Page
C Programming Structure Examples
This page contains examples and source code on structures in C programming language. To
understand all examples in this page, you should have knowledge of following structure topics.
1. Structure Introduction
2. Structure and Pointers
3. Passing Structure to Function
File Operations
1. Creating a new file
2. Opening an existing file
3. Reading from and writing information to a file
4. Closing a file
Working with file
While working with file, you need to declare a pointer of type file. This declaration is needed for
communication between file and program.
FILE *ptr;
Opening a file
Opening a file is performed using library function fopen(). The syntax for opening a file in standard
I/O is:
ptr=fopen("fileopen","mode")
For Example:
fopen("E:\\cprogram\program.txt","w");
/* --------------------------------------------------------- */
/* --------------------------------------------------------- */
Here, the program.txt file is opened for writing mode.
Closing a File
The file should be closed after reading/writing of a file. Closing a file is performed using library
function fclose().
#include <stdio.h>
int main()
{
int n;
FILE *fptr;
fptr=fopen("C:\\program.txt","w");
if(fptr==NULL){
printf("Error!");
exit(1);
}
printf("Enter n: ");
scanf("%d",&n);
fprintf(fptr,"%d",n);
fclose(fptr);
return 0;
}
This program takes the number from user and stores in file. After you compile and run this program,
you can see a text file program.txt created in C drive of your computer. When you open that file, you
can see the integer you entered.
Similarly, fscanf() can be used to read data from file.
Reading from file
#include <stdio.h>
int main()
{
int n;
FILE *fptr;
if ((fptr=fopen("C:\\program.txt","r"))==NULL){
printf("Error! opening file");
exit(1); /* Program exits if file pointer returns NULL. */
}
fscanf(fptr,"%d",&n);
printf("Value of n=%d",n);
fclose(fptr);
return 0;
}
If you have run program above to write in file successfully, you can get the integer back entered in
that program using this program.
Other functions like fgetchar(), fputc() etc. can be used in similar way.
Binary Files
Depending upon the way file is opened for processing, a file is classified into text file and binary
file.
If a large amount of numerical data it to be stored, text mode will be insufficient. In such case binary
file is used.
Working of binary files is similar to text files with few differences in opening modes, reading from
file and writing to file.
fwrite(address_data,size_data,numbers_data,pointer_to_file);
Function fread() also take 4 arguments similar to fwrite() function as above.
C Programming File Examples
#include <stdio.h>
int main(){
char name[50];
int marks,i,n;
printf("Enter number of students: ");
scanf("%d",&n);
FILE *fptr;
fptr=(fopen("C:\\student.txt","w"));
if(fptr==NULL){
printf("Error!");
exit(1);
}
for(i=0;i<n;++i)
{
printf("For student%d\nEnter name: ",i+1);
scanf("%s",name);
printf("Enter marks: ");
scanf("%d",&marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
}
fclose(fptr);
return 0;
}
Write a C program to read name and marks of n number of students from user and store them
in a file. If the file previously exits, add the information of n students.
#include <stdio.h>
int main(){
char name[50];
int marks,i,n;
printf("Enter number of students: ");
scanf("%d",&n);
FILE *fptr;
fptr=(fopen("C:\\student.txt","a"));
if(fptr==NULL){
printf("Error!");
exit(1);
}
for(i=0;i<n;++i)
{
printf("For student%d\nEnter name: ",i+1);
scanf("%s",name);
printf("Enter marks: ");
scanf("%d",&marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
}
fclose(fptr);
return 0;
}
Write a C program to write all the members of an array of strcures to a file using fwrite().
Read the array from the file and display on the screen.
#include <stdio.h>
struct s
{
char name[50];
int height;
};
int main(){
struct s a[5],b[5];
FILE *fptr;
int i;
fptr=fopen("file.txt","wb");
for(i=0;i<5;++i)
{
fflush(stdin);
printf("Enter name: ");
gets(a[i].name);
printf("Enter height: ");
scanf("%d",&a[i].height);
}
fwrite(a,sizeof(a),1,fptr);
fclose(fptr);
fptr=fopen("file.txt","rb");
fread(b,sizeof(b),1,fptr);
for(i=0;i<5;++i)
{
printf("Name: %s\nHeight: %d",b[i].name,b[i].height);
}
fclose(fptr);
C Programming Enumeration
An enumeration is a user-defined data type consists of integral constants and each integral constant
is give a name. Keyword enum is used to defined enumerated data type.
enum suit{
club=0;
diamonds=10;
hearts=20;
spades=3;
};
enum boolean{
false;
true;
};
4 day
You can write any program in C language without the help of enumerations but, enumerations helps
in writing clear codes and simplify programming.
C Programming Preprocessor and Macros
Preprocessor extends the power of C programming language. Line that begin with # are called
preprocessing directives.
Use of #include
Let us consider very common preprocessing directive as below:
#include <stdio.h>
Here, "stdio.h" is a header file and the preprocessor replace the above line with the contents of
header file.
Use of #define
Preprocessing directive #define has two forms. The first form is:
INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 69
AN INTRODUCTION TO C LANGUAGE
Area=28.27
Syntactic Sugar
Syntactic sugar is the alteration of programming syntax according to the will of programmer. For
example:
#define LT <
Every time the program encounters LT, it will be replaced by <.
Second form of preprocessing directive with #define is: