[go: up one dir, main page]

0% found this document useful (0 votes)
10 views31 pages

Module 1

The document provides an introduction to C programming, covering the basics of computers, data representation, programming languages, algorithms, flowcharts, and the structure of C programs. It details the history and importance of C, its syntax and semantics, and the process of compiling and executing C programs. Additionally, it discusses programming styles, including decision-making and looping statements, along with examples of algorithms and C code for basic operations.

Uploaded by

sachind2006hsn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views31 pages

Module 1

The document provides an introduction to C programming, covering the basics of computers, data representation, programming languages, algorithms, flowcharts, and the structure of C programs. It details the history and importance of C, its syntax and semantics, and the process of compiling and executing C programs. Additionally, it discusses programming styles, including decision-making and looping statements, along with examples of algorithms and C code for basic operations.

Uploaded by

sachind2006hsn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Introduction to C-PROGRAMMING (1BPLC105E)

BASICS:

Computer:
Computer is an electronic programmable device which can accept input from
users, process the input and results the output.
(or)
Computer can be defined as an information processing machine because it can
accept the data from users and solve the problems in terms of series of steps and
produce an output.
Computer can accept instructions and data, process these instructions and data by
applying basic arithmetic and logical operations like addition, multiplication,
division, AND, OR, NOT etc, and produces the required useful results known as
output(information).

Basic structure of a computer system:

Data representation in computers:


Generally we are using computers for communication across the countries on a
computer communication networking system. Coding of all these characters has
been standardised to facilitate easy exchange of data between various computer
systems. The most popular internal standards including symbols, characters is
ASCII – “American Standard Code for Information Interchange”, developed
by ‘ANSI’(American National Standard Institute). This standard uses 7 bits binary
coding to represent each and every character i.e., 2^7=128. The max characters
represented by ASCII binary coding format is upto 128.
Bit:
Bit is used to represent a brimary digit.
(Or)
It is a single digit in a binary numbering scheme and bit can have only 2 values -
0 and 1

• 1 represents something is present or true.

• 0 represent something is absent or false.


Bytes:
Bytes is a collection of bits.
(or)
A string of binary digits is called byte. The length of 1 byte is equal to 8 bits.
1 byte = 8 bits
Words:
Collection of bytes is called words. Usually minimum of 2 bytes form a single
word.
1 word = 2 bytes = 16 bits (min)

Programmes: A finite set of instructions to carry out some specific task or


functions is called programmes.
Set of programmes is called software. (Set of instructions are written by using
various programming languages.)
Programming:
To solve a problem in computer, it involves preparing a set of instructions
(procedural instructions). Programs in computers refer to as set of instructions
written by using various programming languages. A finite set of instructions
expressed in a precised notation is called computer programing.
Programming languages can be divided into 3 types:
1. Machine level language
2. Assembly level language
3. High level language
Machine level language:
Computer is an electronic machine executing instructions in it's own programming
language called as machine language. It consists of a series of binary code patterns
and these bimany codes are also called as operational codes.
Assembly level language:
It contains pnemonic code which is a symbolic code and instruction consisting of
few of the alphabet symbols together to denote binary codes.
Ex: MOV AX, 01H
ADD AX, BX
HLT , STOP etc

High level language:


It is a special language used to communicate with computer for problem solving.
This language is also called as procedure oriented language because it allows the
programmer to enclose one or more statements on certain procedure to solve the
problem.
Example: C, C++, java, pascle,cobal, C-ash/C sharp,python etc.
This language consists of a set of symbols like alphabets, numbers, special
characters and symbols etc. Instructions in a high level language is usually a
english like statement which can be enclosed in a programme as per the procedure
of a particular programming language.

MODULE – 1

Flowcharts and algorithms:


Art of programming through algorithms and flow charts.

Algorithms:
It can be defined as a finite number of well defned procedurel steps used to solve
a given problem.
(or)
It is a step-by-step procedure to solve a given problem. It consists of a limited
umber of procedural steps, each of the step may perform onr or more operations.
Characteristics of algorithms: (Features)
1. Input:
Algorithm starts with procedurel steps to accept an input data and these data
elements are proccessed by subsequence steps.
2. Definite:
Each operational step and operation must be definite, i.e., each and every
instruction must specify clearly that what should be done.
3. Effective:
Each operation and procedural step must be effective to carry out the specific
task.
4. Terminate:
After some minimal number of operations, algorithms must be compiled and
terminated (using ;).
5. Output:
An algorithm is written to solve a problem, i.e., it must produce one or more
computered results as output.
Example Algorithms:
1. Algorithm to compute sum and average of 3 numbers.
Step 01: Read this values of a, b and c.
Step 02: Computo sum  a+b+c;
Step 03: Computer average  sum/3;
Step 04: Display the results of sum and avg.
Step 05: STOP / terminate / exit the process.

2. Develop an algorithm to compute area of a circle.


Step 01: Read of value of radius ‘r’ of the circle.
Step 02: Initialize pi  3.142
Step 03: Computer area  3.142 * r * r
Step on: Display the result of area of the circle.
Step 05: Stop the process.

3. Write an algorithm to find largest of 3 numbers.


Step 01: Read the values of a, b and c.
Step 02: Compare if a > b and a > c
Step 03: If yes, display a is largest.
Step 04: Else, compare if b > c
Step 05: If yes, display b as largest.
Step 06: Else display c is largest.
Stop 07: Terminate the process.

Flow charts:
A flowchart can be defined as a pictorial representation of an algorithm.
(or)
Graphical representation of an algorithm is called a flow chart. When a problem is
solved with computer, 1st we must analyse a given problem and develop a
procedural step in sequencial manner, which is called algorithm.
The advantages of flow charts are:

• It is very easy for an individual to understand the problem clearly.

• It is easy to develop flow of sequence of an operation graphically.

• It can be represented using some shapes and symbols.

Basic symbols used in flow charts are:


010-- used to represent beginning or ending of a flow chart
III - used to represent input on output operations
IT - used to specify processing such as arithematic & logic operations
- used to represent condition and condition is tested based on the values or true
/ false
11- used to represent flow of operations
- looping - used to represent looping (a group of instructions executed many times
repeatedly)
- used to represent connector

Write a flow chart to compute sum and average of 3 numbers

Write an algorithm and flow chart to compute largest of 2 numbers


Step 01: Start the process.
Step 02: Read the values of a and b.
Step 03: Compare if a > b
Stop 04: If yes, display a is largest.
Step 05: Else display b is largest.
Step 06: Terminate the process.

Write an algorithm and flowchart to swap 2 numbers


Step 01: Start the process.
Step 02: Read the values of a and b.
Step 03: Compute temp = a;
a = b;
b = temp;
Step 04: Display the values of a and b.
Step 05: Stop the process.
Overview of C:
History of C, Importance of C, Basic Structure of C programs,
Programming Style, Compiling and Executing of a ‘C’ program.

History of C:

Origin:
C is a structured, high-level, and machine-independent programming language
developed for system and application programming.
Roots:
The foundation of modern languages began with ALGOL (1960s), the first
language to use block structure. It introduced structured programming, later
popularized by Corrado Bohm, Guiseppe Jacopini, and Edsger Dijkstra.
Early Developments:
1967: Martin Richards developed BCPL (Basic Combined Programming
Language) for writing system software.
1970: Ken Thompson created B, derived from BCPL, and used it to develop early
versions of the UNIX operating system at Bell Labs.
Creation of C:
1972: Dennis Ritchie at Bell Laboratories developed C, evolving it from ALGOL,
BCPL, and B.
Added data types and more powerful features.
UNIX was coded almost entirely in C, making C closely associated with UNIX.
Evolution:
Initially used in academic environments, C gained popularity with the release of
commercial compilers and the rise of UNIX.
1978: The book “The C Programming Language” by Brian Kernighan and Dennis
Ritchie standardized “K&R C”.

Different versions led to incompatibilities.


Standardization:
1983: ANSI formed a committee to standardize C.
1989: ANSI approved the standard version — ANSI C (C89).
1990: ISO also approved it, known as ISO C.
Later Developments:
1990s: Introduction of C++, derived from C, adding object-oriented features.
Sun Microsystems developed Java, modeled on C and C++.
1999: Introduction of C99, an updated standard with new features.

Importance of C:
Robust and Efficient:
C offers a rich set of built-in functions and operators, allowing development of
complex programs efficiently.
Programs written in C run faster than those in interpreted languages like BASIC.
Combination of High and Low-Level Features:
C combines the control of assembly language with the simplicity of high-level
languages, making it suitable for system software and business applications.
Portability:
C programs are machine-independent and can run on different systems with little
or no modification.
Structured Programming:
Supports modular programming by dividing a program into functions or blocks,
which simplifies debugging, testing, and maintenance.

Extensibility:
Users can add their own functions to the C library, expanding its functionality.
Simplicity and Power:
With only 32 keywords, C relies on its extensive set of built-in and library
functions, making it simple yet powerful.

Basic Structure of C program:


Structure of a c program:
pre processor directives
global declaration
main()
local declaration
{
statement 1
|
|
statement n
}
user defined function
{
statement 1
|
|
statement n
}

Pre processor directives:


Programmer must enclose the require the process directives called header files. It
contains n-number of functions for specific purpose. These functions has/is a
collection of statements for specific operations.
Ex: # include < stdio.h>
stdio.h is a header file which contains functions/routines to perform read or write
operations on input-output devices.
Ex: printf(), scanf(), putc(), getc(), puts(), gets(), # define pi 3.142
Global declaration section:
In this section we can declare many variables and all variables can be accessed
anywhere in the program i.e., it can accessed in main program or in user defined
functions.
Main:
Always C-program starts with main and main is the starting point of program
execution. The beginning of the main program is indicated
with ‘{’ and end is represented with ‘}’
Local declaration section:
In this section we can declare n no of variables. Variables inside The local
declaration can be accessed only inside the same function and is not accessable
and sharable by any other function inside a program.
Satements: (sub-program functions)
Statements is a thing which represent actual operations. All functions in a program
may have n number of statements to perform specific operations.
User-defined Function:
It is a function which contains n-number of statements to perform specific
operations and it can be declared and defined by the user for specific operation.
All the functions including main function can have open and closing parenthesis
({ }) indicating beginning and ending of functions.

Program to compute addition and subtraction of two numbers.


/* Program to add and sub 2 numbers */
# include <statio.h>
void main( )
{
int a, b, sum, sub;
printf ( “Enter the values of a and b \n” );
scanf ( “%d %d”, &a, &b );
sum = a+b;
sub = а-b;
printf ( “Sum of a and b is %d”, sum );
printf ( “Difference of a and b is %d”, sub );
}
Same program can be written by breaking of tasks or operations into functions,
known as modular programming.
# include <statio.h>
int add ( int, int );
int sub ( int, int );
void main( )
{
int a, b, result;
printf ( “Enter the values of a and b \n” );
scanf ( “%d %d”, &a, &b );
result = add (a,b);
printf ( “Sum of a and b is %d”, result );
result = sub (a,b); // result is a variable here, which can be reused in
modular programming

printf ( “Difference of a and b is %d”, result );


}
// Function to add two numbers

int add ( int x , int y )


{
int sum;
sum = x + y ;
return ( sum );
}
// Function to subtract two numbers

int sub ( int x , int y )


{
int difference;
difference = x - y ;
return ( difference );
}
C is a high-level language consisting of 2 parts such as syntax and semantics.
Syntax of a C-language specify characters, words, operators, rules, sentences, etc.
According to these syntax, programmer has to enclose and declare statements to
perform certain functions. These syntax are checked and evaluated by C-compilers
before going to perform specific task (execution of program). Ex: c = a + b ;
Semantics in a language assign exact meaning and action to be performed in a valid
statement.
Ex: c = a + b ; » a, b and c are variables foe which we assign values.
(a and b can be considered as operands also).
» =, +, ; are operators (‘=’ is assignment operator, ‘+’
is arithematic operator, ‘;’ is terminator operator).
Programming Style:

Rules:

• C knows the difference between the upper case and the lower case (case-
sensitive).

• C supports fundamental data types like integer, real


numbers (float and double) and characters (boolean – true/false).
• C allows to form an arithematic expression including arithematic operators
and opperants (identifiers).
Ex: Sum = a+b ( a and b are operands ; = and + are operators )

• C provides decision making statements such as if, if else, if else if and switch
statements. All decision making statements in C may be one way decision
making, two way decision making and multi way decision making
statements.

• C also provides looping statements such as for loop, while loop and do while
loop. Main objective of looping statement in c is to execute set of statements
repeatedly for specified no of times.

Compiling and Executing a ‘C’ program:


Compiling:
Compilation is done by a ‘C-compiler’ to translate source code into machine
understandable language to check for correctness ( no error ).
Executing of C-program:
Execution indicates that the machine is ready for processing. Execution is the art
of running the compiled code on a computer’s processor to perform the program’s
task.
Process of compiling and executing a C-program:
Executing a C-program involves series of steps such as:
1. Creating the program
2. Compiling the program
3. Linking the program with functions that are needed from the c libraries
4. Executing the program.
1. Creating the program:
Program must be created by enclosing operations statements inside a file. To create
a file and program, a programmer has to use editors. The extention for a file is ".c"
and we have to give a file name using letters, digits and special characters followed
by dot c (filename.c)
2. Compiling and linking:
Once if the source program is ready or the souece program has been created, the
program is ready for compilation. We use ‘Alt+F9’ to compile a c-program in turbo
c++.
The main ppurpose of the compiler is to translate the source program instructions
to machine understandable form for execution by the computer system. The
complete translation is done after examining each instruction for its correctness.
Once if the source program is compiled successfully without any error, then the
compiler generates another file with the name ‘______.o’ .o is a object file that
contains object codes ( object codes are also called as machine codes ).
3. After compilation of source program, next step is linking. Linking is the process
of putting together other program files and functions that are required by the
program.
Ex 01: In a program we may use printf ( ) function.
These printf( ) function is already defined in library such as stdio.h Instructions for
printing messages are imported from stdio.h and copied (linking) to original source
program.
Ex 02: sqrt is a function to find square root of a given number and it is defined in
math.h which contains rootings of all mathematical functions. All these functions
are linked with original main program.
4. Executing the C-program:
Execution of c program is a simple task. In turbo C++, ‘Ctrl + F9’ is used to execute
the source program. It is also called as running of source program. During
execution some errors may be generated and these errors are called linking errors.
Linking error is generated due to unavailability of library functions.
Constants, Variables and Datatypes:
Character set, C Tokens, Keywords and Identifiers, Constants-
Variables, Data Types, Declaration of variables, Assigning values to variables,
Defining symbolic constants, Declaring a variable as Constants and Volatile,
Input and Output Statements in C

Character Set:
Character set is a collection of all valid characters that can be used to write C-
programs. Characters can be used to form words, numbers and expressions
depending on the computer on which the program runs. The main characters used
in C are grouped together into following categories:

• Letters or alphabets [A-Z , a-z]

• Numbers or digits [0-9]

• Special characters [ , (comma) ; (semi-colon) . (dot) : (colon) ? (question-


mark) ‘ ’ (single-quotes) “ ” (double-quotes) ! (not) |
(pipes/connectors/filters) \ (backword slash) / (forward slash) ~ (tilde
operator) _ (underscore) $ (dollar) % (percentage) & (ampacent) ^ (cap) *
(astring) # (ash) + (plus) – (minus) < (lesser than) > (greater than) ( ) [ ] { }
(parentesis or brackets)

• White space

C – Tokens:
An indivisual text, word, punctuation is called token.
Tokens are the fundamental building blocks of a C-program representing smallest
indivisual units that are meaningful to the c-compiler. The compiler breaks down
the source code into these tokens to understand its structure and functionality.
Keywords and Identifiers:
Keywords or Reserved Words:
These are the words whose meaning is already defined (pre-defined), declared and
explained to the C-compiler. We cannot use reserved words as identifiers / variable
names because these can be used to carry pre defined meaning of a language
syntax.
Ex: main( ), int, float, char, void, sqrt, abs, if, for, continue, switch, else, while,
exit, break, default, do-while, case, getch( ), clrscr( ), unsigned, go-to, double,
return, sizeof, struct, union, enum, typedef, exter, static, const, volatile, auto etc.
Identifiers:
In the C programming language, identifiers are names used to uniquely identify
various program elements such as variables, functions, arrays, structures, unions,
and other user-defined items. They are essential for referring to these elements
within the code, making it readable and maintainable.

Constants and Variables:


Constants:
Constants are also called as literals. It can be defined as a value or quantity which
doesn’t change during execution of a program. Constants can be integers, real no.s,
or can be characters or strings.
Ex: int a = 10;
float pi = 3.142;
char gender = ‘M’;
char[10] city = “HASSAN”;
1. Integer Constant:
An integer constant refers to a sequence of digits and has 3 types:

• Decimal integers: Decimal integers consist of a set of digits, 0 through 9,


preceded by an optional – or + sign. Valid examples of decimal integer
constants are: 123, -123, 0, 687 etc
Note: Embedded spaces, commas, and non-digit characters are not permitted
between digits. For example: 15 750, 20,000 $1000

• Octa decimal integers: An octal integer constant consists of any combination


of digits from the set 0 through 7, with a leading 0. Some examples of octal
integer are: 037, 0, 0435, 0551

• Hexa decimal integers: A sequence of digits preceded by 0x or 0X is


considered as hexadecimal integer. They may also include alphabets A
through F or a through f. The letter A through F represent the numbers 10
through 15. Following are the examples of valid hex integers: 0X2, 0x9F,
0Xbcd, 0 .We rarely use octal and hexadecimal numbers in programming.
2. Real constant: (float)
Integer numbers are inadequate to represent quantities that varies continuously.
Ex: Temperature, Distance
3. String constant:
These are enclosed with double quotes(“ ”). String constant is a constant and is
a sequence collection of characters.
Ex: char[10] city = "Hassan";
4. Single character constants:
These are enclosed with single quote(‘ ’) and exactly has a single character.
Ex: char gender = ‘F’;
Special ( back slash ) single character constants:
‘ \a ’ - audible bell / alert
‘ \b ’- back space
‘ \f ’ - form feed (keep curzor in next page)
‘ \n ’ - new line
‘ \h ’ - horizontal tab (8-character space)
‘ \v ’ - vertical tab (8-line space)
‘ \“ ’ – to print double quotes(“ / ”)
‘ \\ ’ – to print back slash ( \ )
‘ \o ’ - null character
Variables:
Variable is a data name used to store data values. Values in variables may vary
during execution time.
Ex: int a,b,c = 0;
c=a+b;
Values or quantitities which may vary during program execution is called
variables. Each variable has a specific memory location and can store numeric or
character value. A symbolic name given to a memory location is called variable.
Variables are also known as identifies.
int a, b, sum = 0;
Variable names are a, b, sum. These variables pointes to a memory location that
holds different data values.
Rules to construct variables:
Rule 01: A variable is an identifier consisting of single word as a sequence of
characters or characters with digits or with some special characters.
Ex: int a , int a1, int a1_ , int _a1.....
Rule 02: The 1st character in any variable may be letter of the alphabet including
underscore.
Ex: int _a, int a, int a1, (int 1a is not allowed).
Rule 03: In C, upper and lower case alphabets are recognised as seperate variables
i.e., case sensitive.
Rule 04: Variable name should not contain any blank space, question mark, comma
and some other special symbols.
Real 05: Variable name should not to reserved words.
Ex: int main, int void, int int - cannot be declared but voids, void1 can be.

Data Types:
The storage representations and machine instructions to handle constants differ
from machine to machine. Variety of data values are processed and mentioned by
the programmer.
Representation of varieties of data values are called data types. Basically ANSII
supports 3 classes of data types such as:

• primary data types (Basis / fundamental / primary) → int, float, char, double,
etc.

• derived data Types → Formed using the basic types.- Arrays, Pointers,
Functions

• user defined data types → typedef, enum, struct, union.


1. Primary data types:
C supports 5 fundamental data types such as: int- integers, float - real nos, double-
real nos, char- single character or string, void – null or empty.
❖ int data type:
An integer constant / number in C language simply consists of a sequence of
1 or more decimal numbers.
Ex; 1, 153, 180 etc.
It can be divided into:
▪ signed ( both +ve and –ve )
▪ unsigned ( only +ve integers )
▪ short
▪ long
❖ float data type:
Floating point in C language consists of a sequence of one or more digits of
decimal number system along with decimal point and fractional values.
Ех: 4.0, 4.199, 80.085, -197.35
❖ double data type:
It is similar to float data type and can be used whenever the accuracy is
required
❖ void data type:
Void is a data type and has no value. This can be used to represent functions.
❖ char data type:
In C, character constants are formed by enclosing the characters within a pair
or single or double quotes.
2. Derived data types:
Derived data types are created from the fundamental (basic) types. They include:
❖ Arrays - Collection of elements of the same type stored in contiguous
memory.
▪ Ex: int arr[5] = {1, 2, 3, 4, 5};
❖ Pointers - Variables that store the memory address of another variable.
▪ Ex: int x = 10;
int *ptr = &x; // ptr stores address of x
❖ Functions - In C, functions are considered derived types because they return
values of basic types or derived types.
▪ Ex: int sum(int a, int b) {
return a + b;
}
❖ Structures & Unions (sometimes considered user-defined, but also treated as
derived)
➢ Structure groups variables of different types.
struct Student {
int roll;
char name[2];
float marks;
};
➢ Union shares the same memory for all members.
union Data {
int i;
float f;
char str[20];
};
3. User-defined data types:
In C programming, User-defined data types are those that are created by the
programmer using basic or derived data types to suit their needs..
❖ typedef (Type Definition) - Used to create a new name (alias) for an existing
data type.
Ex: typedef unsigned int uint;
uint age = 25; // same as unsigned int age = 25;
❖ enum (Enumeration) - Defines a set of named integer constants (makes code
more readable).
Ex: enum Weekday { MON, TUE, WED, THU, FRI, SAT, SUN };
enum Weekday today = WED; // internally WED = 2
❖ struct (Structure) - Groups variables of different types under a single name.
Ex: struct Student {
int roll;
char name[20];
float marks;
};
struct Student s1 = {101, "Ravi", 88.5};
❖ union (Union) - Similar to struct, but members share the same memory
location. Saves memory but only one member holds a valid value at a time.
Ex: union Data {
int i;
float f;
char str[20];
};
union Data d;
d.i = 10; // d.f and d.str overwrite same memory
Declaration of Variables:
Each variable used in a c program must be declared in local declaration section
before using. To declare a variable in C we must specify the type of variables to
use and also need to specify number of memory locations required to hold different
constants and values.
Syntax: “ datatype variable_name; ”
“ datatype variablename1, variable name2, ..... ”
Ex: int a;
int b, sum;
float avg o.o;

Assigning values to variables:


Values can be assigned to variables in two ways :
1. At the time of declaring:

• Declaring and then assigning value to variable:


Ex: int a, b, sum; // declaring of variables
int a= 10; // assigning value 10 to variable a
int b = 20; // assigning value 20 to variable b
sum = a+b; // 10 + 20 = 30
printf(“Sum = %d”, sum); // 30 is assigned to variable sum

• Declaration with initialization:


Ex: int sum = 0;
float avg = 0.00;
char initial = ‘j’;
char name[20] = “aabbbccc”;
2. At the time of executing the program: (accepting user input)
Variables can be assigned value that is given by users at the time of executing any
program. It is done with the help of scanf( ) function.
Ex: int a, b, sum; // declaring of variables
printf (“ Enter the values of a, b and c\n ”);
scanf (“ %d %d ”, &a, &b);// to accept user input value to variables a and b
sum = a + b;
printf ( “ Sum = %d ”, sum );

Defining symbolic Constants:

Constants can be defined using 2 methods:


1. using # define pre-processor directive:
Syntax: # define CONSTANT_NAME value
where, ‘# define’ is pre-processor directive,
‘CONSTANT_NAME’ is a name assigned to the constant
(should be in upper case with underscore for seperating words)
‘value’ is the assigning value to constant
2. using “ const ” keyword:
Syntax: const type CONSTANT_NAME value
where, ‘const’ is a keyword indicating constant variable,
‘type’ indicating datatype to specify the datatype
‘CONSTANT_NAME’ is a name assigned to the constant
‘value’ value that cannot be changed

Declaring variables as constants and volatile:


Variables can be declared with type qualifiers – “const” and “volatile” to provide
specific instructions to compiler regarding behaviour.
1. const :
If a variable is declared as const, its value cannot be modified after initialization.
It leads to compilation error if value is tried to change.
Ex: const float PI = 3.14159;
2. volatile:
If variables are declared using volatile keyword, variable’s value may change at
any time. (shared memory in multi-thread)
Ex: volatile int sensor_reading;
3. combining const and volatile:
It is possible and sometimes necessary to declare variables as both const and
volatile. This indicates that value shouldn’t be changed by program itself(const),
but may be altered by external entities(volatile).
Ex: const volatile abc_3;

Input / Output Statements in C:


C language supports many input functions to read data values for processing from
various sources. The main sources to read data values is input devices. To read the
data values from input devices, C provides set of standard built-in functions called
library functions. These functions are declared and defined in a file called stdio.h
Input functions can be classified into two types such as,
• Formatted input functions.

• Unformatted input functions.


1. Unformatted Input Funcions:
They are functions which read any single charcater and strings or any other
symbols or digits or characters. Whether the characters read by input functions
including digits all are treated as chracters only.
Some of the unformatted input functions supported in C are,

• getchar( );

• getch( );

• getc( );

• fgetchar( );
variable name = getc( ); reads only single character
Ex: gender = getc( );
Name = getchar();
Getchar(); to read single character or even string
2. Formatted Input Function:
To read data values of different data types, format input function is used. It is a
function used to read data values of specific data type. Formatted input function is
‘scanf( )’
Syntax of scanf( ) :
scanf (“control string”, arg1, arg2, ......, arg n); where control string
specify field format in which the data is to be entered, arg1, arg2,..., arg n are
arguments which specifies the address of a specific / particular memory location
where data value is stored.
Control string is also known as format string containing field specification. Field
specification contains conversion character i.e., % and data type character i.e.,
d(for integers), f(for floating point no.s) etc.
Ex: scanf (“%d %f %c %s”, &age, &marks, &gender, &name);
Here in the above example, & is known as address-of operator (specifies
where input values should be stored)
3. Formatted output functions:
Formatted output functions are used to display results on display units.
Syntax of formatted output function printf ( ) is:
printf (“control string”, arg1, arg2,...., arg n);
Control string or format string in a printf( ) function is a string literal enclosed in
double quotes. It consists of:

• Plain Text: characters that is not part of format specifiers will be printed on
the screen as they appear (literal text)

• Format specifiers: to specify data values to be printed on screen, begins with


%
o %d : for integers
o %f : for floating-point numbers
o %c : for characters
o %s : for strings
o %lf : for double-precision floating-point numbers
o %x : for hexadecimal representation of integers

• Escape sequence: special character combinations like \n (newline), \t (tab), \\


(backslash), etc to controlthe output’s appearance.
Ex: printf(“sum = %d\n”, 100);
4. Unformatted output function:
These are functions used to display characters or string values on display unit.
Some of the unformatted output functions supported by C are put c( ); putchar( );
putch( ); fputchar( );
Program to read USN, name, age, gender, percentage and address of a student and
display the same on display unit.
#include<stdio.h>
#include<conio.h>
void main( )
{
cham name [20], USN[10], address[30];
int age;
float percentage;
char gender;
clrscr( );
printf("Please enter name, USN, address, age, percentage and gender of a
student \n");
scanf("%s %s %s %d %f %c", name, USN, address, &age, &percentage,
&gender);
printf("Details of the student is as follows \n");
printf("Name = %s \n", name);
printf("USN = %s \n", USN);
printf("Address = %s \n", address);
printf("Age = %d \n", age);
printf("Percentage = %f \n", percentage);
printf("Gender = %c \n", gender);
getch( );
}
Output:
Please enter name, USN, address, age, percentage and gender of a student
Name =
USN =
Address =
Age =
Percentage =
Gender =

Unformated:
putc("Please enter name, USN, address, age, percentage and gender of a student");
name = getchar( );
USN = getchar( );
putchar(name);
putchar(USN);

You might also like