0% found this document useful (0 votes)
117 views

Unit-2 Fundamentals of C

This document discusses the key features of the C programming language. It describes C as a simple, machine-independent, mid-level structured programming language that provides features like pointers, recursion, and extensibility. It also covers C program structure, data types, comments, header files, variables, and common functions like printf() and scanf().

Uploaded by

Nishil Pathak
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)
117 views

Unit-2 Fundamentals of C

This document discusses the key features of the C programming language. It describes C as a simple, machine-independent, mid-level structured programming language that provides features like pointers, recursion, and extensibility. It also covers C program structure, data types, comments, header files, variables, and common functions like printf() and scanf().

Uploaded by

Nishil Pathak
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/ 62

UNIT-2 FUNDAMENTALS OF C

1
Features of C Language
Features of C Language
▪ Simple
C is a simple language in the sense that it provides a structured approach (to break the
problem into parts), the rich set of library functions, data types, etc.
▪ Machine Independent or Portable
Unlike assembly language, c programs can be executed on different
machines with some machine specific changes. Therefore, C is a machine
independent language.
▪ Mid-level programming language
Although, C is intended to do low-level programming. It is used to develop
system applications such as kernel, driver, etc.
It also supports the features of a high-level language. That is why it is known
as mid-level language.
▪ Structured programming 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. Functions also provide code reusability.
Features of C Language
▪ Rich Library
C provides a lot of inbuilt functions that make the development fast.
▪ 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.
▪ Speed
The compilation and execution time of C language is fast since there are lesser
inbuilt functions and hence the lesser overhead..
▪ Pointer
C provides the feature of pointers. We can directly interact with the memory by
using the pointers.
▪ Recursion
In C, we can call the function within the function. It provides code reusability for
every function. Recursion enables us to use the approach of backtracking.
▪ Extensible
C language is extensible because it can easily adopt new features.
Structure of C Program
n section // Program for addition of 2 nos
▪(Used for comments)
#include<stdio.h>

#define PI 3

void fun();

int a=10;

void main( )
{
printf("Value of a inside main
function: %d", a);

fun();
}

void fun()
Comments
▪ A comment is an explanation or description of the source code of the
program.
▪ It helps a programmer to explain logic of the code and improves program
readability.
▪ At run-time, a comment is ignored by the compiler.
▪ There are two types of comments in C:
▪ Single line comment
▪ Represented as // double forward slash
▪ It is used to denote a single line comment only.
▪ Example: // Single line comment
▪ Multi-line comment
▪ Represented as /* any_text */ start with forward slash and asterisk (/*) and end with
asterisk and forward slash (*/).
▪ It is used to denote single as well as multi-line comment.
▪ Example: /* multi line comment line -1
▪ multi line comment line -2 */
Header files
▪ In C language, header files contain the set of predefined standard
library functions.
▪ The “#include” preprocessing directive is used to include the
header files with “.h” extension in the program.
Header file Description
stdio.h Input/Output functions (printf and scanf)
conio.h Console Input/Output functions (getch and
clrscr)

math.h Mathematics functions (pow, exp, sqrt etc…)

string.h String functions (strlen, strcmp, strcat etc…)


Data Types
▪ Data types are defined as the data storage format that a variable
can store a data.
▪ It determines the type and size of data associated with variables.

Data types in C

Primary Data type Secondary Data


(int, float, char) type

Derived Data type User definer Data type


(array, pointer) (structure, union, enum)
)
Type Storage size Value range Format
Specifier
char 1 byte -128 to 127 or 0 to 255 %c
unsigned char 1 byte 0 to 255 %c

signed char 1 byte -128 to 127 %c

-32,768 to 32,767 or -2,147,483,648 to %d


int 2 or 4 bytes
2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295 %u

short 2 bytes -32,768 to 32,767 %hd


unsigned short 2 bytes 0 to 65,535 %hu

long 8 bytes or (4bytes -9223372036854775808 to %ld


for 32 bit OS) 9223372036854775807
unsigned long 8 bytes 0 to 18446744073709551615 %lu

float 4 byte 1.2E-38 to 3.4E+38(6 decimal places) %f

double 8 byte 2.3E-308 to 1.7E+308(15 decimal places) %lf

long double 10 byte 3.4E-4932 to 1.1E+4932(19 decimal places) %Lf


Secondary Data Type
▪ Secondary data types are not directly supported by the machine.
▪ It is combination of primary data types to handle real life data in
more convenient way.
▪ It can be further divided in two categories,
▪ Derived data types
▪ User defined data types:
Secondary Data Type
▪ Derived data types: Derived data type is extension of primary data
type. It is built-in system and its structure cannot be changed.
Examples: Array and Pointer.
• Array: An array is a fixed-size sequenced collection of elements of the same data
type.
• Pointer: Pointer is a special variable which contains memory address of another
variable.
• User defined data types: User defined data type can be created by
programmer using combination of primary data type and/or
derived data type. Examples: Structure, Union, Enum.
• Structure: Structure is a collection of logically related data items of different data
types grouped together under a single name.
• Union: Union is like a structure, except that each element shares the common
memory.
• Enum: Enum is used to assign names to integral constants, the names make a
program easy to read and maintain.
Tokens in C
▪ Tokens in C is the most important element to be used in creating a
program in C.
▪ We can define the token as the smallest individual element in C.
▪ For `example, we cannot create a sentence without using words;
similarly, we cannot create a program in C without using tokens in
C.
▪ we can say that tokens in C is the building block or the basic
component for creating a program in C language.
Classification of tokens in C
Keywords in C
▪ Keywords in C can be defined as the pre-defined or the reserved
words having its own importance, and each keyword has its own
functionality
▪ You cannot use it as a variable name, constant name, etc
▪ There are only 32 reserved words (keywords) in the C language.
auto break case char const continue default do

double else enum extern float for goto if

int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while


Identifiers in C
▪ Identifiers in C are used for naming variables, functions, arrays,
structures, etc. Identifiers in C are the user-defined words.
▪ Rules For defining Identifiers.
• The first character of an identifier should be either an alphabet or an
underscore, and then it can be followed by any of the character, digit, or
underscore.
• It should not begin with any numerical digit.
• In identifiers, both uppercase and lowercase letters are distinct.
Therefore, we can say that identifiers are case sensitive.
• Commas or blank spaces cannot be specified within an identifier.
• Keywords cannot be represented as an identifier.
• The length of the identifiers should not be more than 31 characters.
• Identifiers should be written in such a way that it is meaningful, short,
and easy to read.
Variables
▪ A variable is nothing but a name given to a storage area that our
programs can manipulate.
▪ A variable is a name of the memory location. It is used to store
data. Its value can be changed, and it can be reused many times.
▪ It is a way to represent memory location through symbol so that it
can be easily identified.
▪ Syntax ::
type variable_list;
▪ Example:: int a;
float b;
char c;
▪ Here, a, b, c are variables. The int, float, char are the data types.
printf()
▪ printf() is a function defined in stdio.h file
▪ It displays output on standard output, mostly monitor
▪ Message and value of variable can be printed
▪ Let’s see few examples of printf
• printf(“ ”);
• printf(“Hello World”); // Hello World
• printf(“%d”, c); // 15
• printf(“Sum = %d”, c); // Sum = 15
• printf(“%d+%d=%d”, a, b, c); // 10+5=15
scanf() function
▪ scanf() is a function defined in stdio.h file
▪ scanf() function is used to read character, string, numeric data
from keyboard
▪ Syntax of scanf
• scanf("%X", &variable);
• where %X is the format specifier which tells the compiler what type of data is in
a variable.
• & refers to address of “variable” which is directing the input value to a address
returned by &variable.
Example of datatype used
#include<stdio.h>

int main()
{
int a=10; Example:: Example_data.c
float b=20.123456789; Example:: Example_data1.c
char c='a';
double d=45.12345678911225;

printf("integer value:: %d",a);


printf("\nfloating value :: %f",b);
printf("\ncharcter value :: %c",c);
printf("\ndouble value :: %lf",d);

return 0;
}
ASCII value in C
▪ The full form of ASCII is the American Standard Code for
information interchange.
▪ It is a character encoding scheme used for electronics
communication. Each character or a special character is
represented by some ASCII code.
▪ In C programming language, a character variable does not contain
a character value itself rather the ascii value of the character
variable.
▪ The ascii value represents the character variable in numbers, and
each character variable is assigned with some number range from
0 to 127. For example, the ascii value of 'A' is 65.
▪ https://en.cppreference.com/w/cpp/language/ascii
Example of Ascii code and Charcter
#include <stdio.h>
int main()
{
char ch; // variable declaration
printf("Enter a character");
scanf("%c",&ch); // user input
printf("\n The ascii value of the ch variable %c is : %d",ch, ch);
return 0;
}

Example::Example_data2.c

Example::Example_data3.c
Constants in C
▪ A constant is a value assigned to the variable which will remain
the same throughout the program, i.e., the constant value cannot
be changed.
▪ There are two ways of declaring constant:
• Using const keyword
• Using #define pre-processor
Constant Example
Integer constant 10, 11, 34, etc.
Floating-point constant 45.6, 67.8, 11.2, etc.
Octal constant 011, 088, 022, etc.
Hexadecimal constant 0x1a, 0x4b, 0x6b, etc.
Character constant 'a', 'b', 'c', etc.
String constant "java", "c++", ".net", etc.
Example (Constant_var.c)
/* Program illustarting use of declartion, assignment of value to variables. Also explains how to use
symbolic constants.
Program to calculate area and circumference of a circle */

#include <stdio.h>
#define PI 3.1415 /* no semicolon here */
int main()
{
float rad = 5; /* declaration and assignment */
float area, circum; /* declaration of variable */

const float pi=3.14;


area = PI * rad *rad;
//PI=500.4;
circum = 2 * pi *rad;

// pi=500.4;
printf("Area of circle = %f\n",area);
printf("Circumference of circle =%f\n",circum);
return 0;
}
Strings in C
▪ Strings in C are always represented as an array of characters having null
character '\0' at the end of the string.
▪ This null character denotes the end of the string.
▪ Strings in C are enclosed within double quotes, while characters are
enclosed within single characters.
▪ The size of a string is a number of characters that the string contains.
▪ Example:
• char a[10] = "javatpoint"; // The compiler allocates the 10 bytes to the 'a'
array.
• char a[] = "javatpoint"; // The compiler allocates the memory at the run time.
• char a[10] = {'j','a','v','a','t','p','o','i','n','t','\0'}; // String is represented in the
form of characters.
Special characters in C
▪ Some special characters are used in C, and they have a special meaning which
cannot be used for another purpose.
▪ Square brackets [ ]: The opening and closing brackets represent the single and
multidimensional subscripts.
▪ Simple brackets ( ): It is used in function declaration and function calling. For
example, printf() is a pre-defined function.
▪ Curly braces { }: It is used in the opening and closing of the code. It is used in
the opening and closing of the loops.
▪ Comma (,): It is used for separating for more than one statement and for
example, separating function parameters in a function call, separating the
variable when printing the value of more than one variable using a single printf
statement.
▪ Hash/pre-processor (#): It is used for pre-processor directive. It basically
denotes that we are using the header file.
▪ Asterisk (*): This symbol is used to represent pointers and also used as an
operator for multiplication.
▪ Tilde (~): It is used as a destructor to free memory.
▪ Period (.): It is used to access a member of a structure or a union.
Operators
▪ Arithmetic operators (+, - , *, /, %)
▪ Relational operators (<, <=, >, >=, ==, !=)
▪ Logical operators (&&, ||, !)
▪ Assignment operators (+=, -=, *=, /=)
▪ Increment and decrement operators (++, --)
▪ Conditional operators (?:)
▪ Bitwise operators (&, |, ^, <<, >>)
▪ Special operators ()
Arithmetic Operators
▪ Arithmetic operators are used for mathematical calculation.
Program explaining Arithmetic operators
/* Program illustrating use of arithmetic operators. The numbers x and y are initialized in the program
itself with x = 25 and y =4 */
#include <stdio.h>
main()
{
int x=25;
int y=4;

printf("%d + %d = %d\n",x,y,x+y);
printf("%d - %d = %d\n",x,y,x-y);
printf("%d * %d = %d\n",x,y,x*y);
printf("%d / %d = %d\n",x,y,x/y);
printf("%d %% %d = %d\n",x,y,x%y);
}

Output
---------------------------------------------------------------------------------------------------------
25 + 4 = 29
25 - 4 = 21
25 * 4 = 100
25 / 4 = 6
25 % 4 = 1
---------------------------------------------------------------------------------------------------------
Relational Operators
▪ Relational operators are used to compare two numbers and taking
decisions based on their relation.
▪ Relational expressions are used in decision statements such as if, for,
while, etc…

▪ A relational operator checks the relationship between two operands. If


the relation is true, it returns 1; if the relation is false, it returns value 0.
Example Relational Operator
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10;
Example:: Operator.c
printf("%d == %d is %d \n", a, b, a == b);
printf("%d == %d is %d \n", a, c, a == c);
printf("%d > %d is %d \n", a, b, a > b);
printf("%d > %d is %d \n", a, c, a > c);
printf("%d < %d is %d \n", a, b, a < b);
printf("%d < %d is %d \n", a, c, a < c);
printf("%d != %d is %d \n", a, b, a != b);
printf("%d != %d is %d \n", a, c, a != c);
printf("%d >= %d is %d \n", a, b, a >= b);
printf("%d >= %d is %d \n", a, c, a >= c);
printf("%d <= %d is %d \n", a, b, a <= b);
printf("%d <= %d is %d \n", a, c, a <= c);

return 0;
}
Logical Operators
▪ Logical operators are used to test more than one condition and
make decisions.

a b a&&b a||b
0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1
Assignment Operators
▪ Assignment operators (=) is used to assign the result of an
expression to a variable.
▪ Assignment operator stores a value in memory.
▪ C also supports shorthand assignment operators which simplify
operation with assignment.
Example Assignment operator
#include <stdio.h>
int main()
{
int a;
Example::
printf("Give the value of a\n");
scanf("%d",&a); assignment_op.c
a += 5; /* a= a +5 */
printf("a= %d\n",a);
a -= 5; /* a = a-5 */
printf("a= %d\n",a);
a *=5; /* a = a* 5 */
printf("a= %d\n",a);
a /=5; /* a= a /5 */
printf("a= %d\n",a);
a %= 5; /* a= a %5 */
printf("a= %d\n",a);

return 0;
}
Increment/Decrement operators
▪ Increment (++) operator used to increase the value of the variable
by one.
▪ Decrement (--) operator used to decrease the value of the variable
by one.
Example
▪ If a is a variable, then x=100;
x++;
++a is called prefix increment
Explanation
a++ is called postfix increment.
After the execution the
▪ Similarly, value of x will be 101.

--a is called prefix decrement Example

a-- is called postfix decrement. x=100;


x--;
Explanation
After the execution the
value of x will be 99.
Increment and Decrement Operators (cont…)
Operator Description
Pre increment operator (++x) value of x is incremented before assigning it to
the variable on the left

Example Explanation Output

x=10; First increment value of x will be 11


p=++x; x by one then assign. p will be 11

Operator Description
Post increment operator (x++) value of x is incremented after assigning it to the
variable on the left

Example Explanation Output

x=10; First assign value of x x will be 11


p=x++; then increment value. p will be 10
Increment and Decrement Operators (cont…)
#include <stdio.h>
main()
Example:: incre_decrement.java
{
int x=10;
int y; Example:: incre_decrement1.java
int z=0;
clrscr();
x++; /* x incremented using postfix notation x=11*/
++x; /* x incremented using prefix notation x=12*/
y = ++x; /* x incremented first and then assigned to y. y=13 x=13 */
printf("Value of x=%d y=%d and z=%d\n",x,y,z);
z= y--; /* y assigned to z first and then decremented z=13 y =12*/
printf("Value of x=%d y=%d and z=%d\n",x,y,z);
}
Output
---------------------------------------------------------------------------------------------------------
Value of x=13 y=13 and z=0
Value of x=13 y=12 and z=13
Conditional Operator (Ternary operator)
▪ ‘C’ language provides ? operator as a conditional operator. It is
also known as a ternary operator. It is used as shown below.
▪ Syntax:
exp1 ? exp2 : exp3
Working of the ? : Operator
exp1 is evaluated first
if exp1 is true(nonzero) then
- exp2 is evaluated and its value becomes the value of the
expression
If exp1 is false(zero) then
- exp3 is evaluated and its value becomes the value of the
expression
Example Example
Example::ternary.c
m=2, n=3; m=2, n=3;
r=(m>n) ? m : n; r=(m<n) ? m : n;
Explanation Explanation
Value of r will be 3 Value of r will be 2
Bit-wise operators
▪ C’ language supports some operators which can perform at the bit
level.
▪ These type of operations are normally done in assembly or
machine level programming.
▪ But, ‘C’ language supports bit level manipulation also, that is why
‘C’ language is also known as middle-level programming language.
▪ Bitwise operators may not be applied to float or double.
Bitwise Operators (Example:: bitwise_op.c)
8 = 1000 (In Binary) and 6 = 0110 (In Binary)

Example: Bitwise & (AND) Example: Bitwise | (OR)


int a=8, b=6, c; int a=8, b=6, c;
c = a & b; c = a | b;
printf("Output = %d", c); printf("Output = %d", c);
Output Output
0 14

Example: Bitwise << (Shift Left) Example: Bitwise >> (Shift Right)
int a=8, b; int a=8, b;
b = a << 1; b = a >> 1;
printf("Output = %d", b); printf("Output = %d", b);
Output Output
16 (multiplying a by a power of 4 (dividing a by a power of
two) two)
Special Operators
Precedence and associativity of operators
▪ When arithmetic expressions are evaluated, the answer of that
expression depends on the value of operands, the operators used
and also on the precedence and associativity of the operators
used.
▪ Precedence of an operator is its priority in an expression for
evaluation.
▪ The operator with higher precedence is evaluated first and the
operator with the least precedence is evaluated last.
▪ Operator precedence is why the expression 5 + 3 * 2 is calculated
as 5 + (3 * 2), giving 11, and not as (5 + 3) * 2, giving 16.
▪ We say that the multiplication operator (*) has higher
"precedence" or "priority" than the addition operator (+), so the
multiplication must be performed first.
Operator associativity
▪ Associativity is the left-to-right or right-to-left order for grouping
operands to operators that have the same precedence.
▪ Operator associativity is why the expression 8 - 3 - 2 is calculated
as (8 - 3) - 2, giving 3, and not as 8 - (3 - 2), giving 7.
▪ We say that the subtraction operator (-) is "left associative", so
the left subtraction must be performed first.
▪ When we can't decide by operator precedence alone in which
order to calculate an expression, we must use associativity.
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right


Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right


Precedence and associativity of operators (Example)
▪ The expression, 5 -3 * 4 +6 /4 will be evaluated as 3 *4 first, then
6/4,then – operation and at last + operation as shown below.

5-3 * 4 + 6 /4

5 - 12 + 6/4

5 - 12 + 1

-7 +1

-6
Type conversion
▪ Whenever an expression involves two different types of operands,
‘C’ language applies the type conversion rules to evaluate an
expression.
▪ Type conversion is converting one type of data to another type.
• Implicit Type Conversion
• This type of conversion is usually performed by the compiler when
necessary without any commands by the user.
• It is also called Automatic Type Conversion.
• Explicit Type Conversion
• These conversions are done explicitly by users using the pre-defined
functions.
Implicit Type conversion
▪ If the operands are of different type, then the operand with a
lower type is upgraded to the higher type and then the operation
is performed.
▪ In the case of assignment,
• If float is assigned to integer, then fractional part is truncated as shown in
above program.
• If double is assigned to float, then rounding takes place.
• If long int is assigned to integer, then additional bits are dropped,
remember that long int requires 4 bytes while int requires only 2 bytes.
Program – Type Conversion (Example::typecast.c)
#include <stdio.h>
In the statement b = a *c +d /10,
main()
{
◻ a*c will be done first, here a will be upgraded
int a,b;
to float because other operand c is float.
float c; So, a*c will evaluate to 27.5.
double d;
a=5; ◻ Then, d/10 will be evaluated, 10 will be
c= 5.5; converted into 10.0 (double) because d is
d = 4.0; double. So, d/10 will evaluate to 0.4.
clrscr();
b = a *c +d /10; ◻ Then 27.5 + 0.4 evaluates to 27.9. This value is
printf("value of b = %d\n",b);
assigned to variable b, which is integer, so
truncated value of 27.9 will be the value of b
}
i.e 27 will be assigned to b.
Output
Type casting
▪ When user needs the type conversion explicitly, then type casting
is used.
▪ Type conversion is automatic while type casting is explicitly
specified by the programmer in the program.
▪ The type casting can be specified in following form
(typename) expression;
Program - Type casting
#include <stdio.h>
main()
{
int sum =47;
Example:: typecast1.c
int n = 10;
float avg;

clrscr();
avg = sum/n; /*avg without type cast */
printf("avg=sum/n = %f\n",avg);
avg = (float)sum/n; /*avg with type cast on sum */
printf("avg=(float)sum/n = %f\n", avg);
avg = (float)(sum/n); /*avg without type cast on (sum/n) */
printf("avg=(float)(sum/n) = %f\n", avg);
}
Output
---------------------------------------------------------------------------------------------------------
avg=sum/n = 4.000000
avg=(float)sum/n = 4.700000
avg=(float)(sum/n) = 4.000000
Preprocessor directives
▪ Preprocessors are programs that process our source code before
compilation.
▪ There are a number of steps involved between writing a program
and executing a program in C.
▪ Let us have a look at these steps before we actually start learning
about Preprocessors.
C Program

Object Executable
Are there
No Code Code
preprocessor Compiler Linker
directive

Preprocessor perform
action
Preprocessor directives
▪ Preprocessor is a program that processes the source program
before the control is given to the compiler.
▪ Preprocessor understands some commands known as
preprocessor directives.
▪ The directive begins with symbol #. There are many directives
which the preprocessor understands.
For example,
#include <stdio.h>
# define PI 3.1415
include directive includes the file mentioned after it, while define
directive defines a symbolic constant.
Macro
▪ A macro is a fragment of code which has been given a name.
Whenever the name is used in program, it is replaced by the
contents of the macro.
▪ Macro definitions are not variables and cannot be changed by
your program code like variables.
▪ The ‘#define’ directive is used to define a macro.
▪ Do not put a semicolon ( ; ) at the end of #define statements.
▪ There are two types of macros:
• Object-like Macros
• Function-like Macros
Macro

Definition The object-like macro is an The function-like macro looks like


identifier that is replaced by value. function call.
Use It is used to represent numeric It is used to represent function.
constants.
Syntax #define CNAME value #define CNAME (expression)

Example #define PI 3.14 #define MIN(a,b) ((a)<(b)?(a):(b))

Program #include <stdio.h> #include <stdio.h>


#define PI 3.14 #define MIN(a,b) ((a)<(b)?
void main() (a):(b))
{ int r=2; void main()
float a; {
a=PI*r*r; printf("%d", MIN(2, 5)
printf("%f", a); );
} }
Program - Preprocessor directives
/* Write a program that demonstrates symbolic constants
*/

#include <stdio.h> Example:: macro.c


#define cube(x) (x*x*x)
void main()
{
int ans,a;
clrscr();
a=3;
ans = cube(a);
printf("Answer = %d\n",ans);
}
Output
---------------------------------------------------------------------------------------------------------
Answer = 27
Character Input
▪ ‘C language provides getchar() function for getting character input
from keyboard.
▪ As we know input/output is buffered, so getchar() function reads
the next character from the input buffer and returns the ASCII
value of the character.
• The syntax of getchar() is
character_variable = getchar();
• The statements
char c;
c = getchar();
will store the ASCII value of the character pressed from the
keyboard.
Program- ASCII code
/* Write a program which accepts a character from keyboard and
display it’s ASCII code */
#include <stdio.h>
#include <conio.h> Example:: char_input.c
main()
{
char c;
printf(“Enter one character\n”);
c=getchar();
printf(“ASCII code of input character %c is = %d\n”,c,c);
}
getch(), getche() and getchar() functions
▪ getchar() function requires ENTER key to be pressed to terminate
the input.
▪ Some times we want to simply read the characters (particularly)
for reading the strings without terminating each character with
ENTER key.
▪ In that case we can use getch() or getche() functions.
▪ getch() function does not echo the input character,
▪ while getche() function echoes the input character on the screen.
▪ The conio.h header file supports the above two functions.
▪ Example:: char_input2.c
Character Output(Example:: char_input2.c)
▪ ‘C language provides putchar() function for displaying one
character on the screen. It prints the character whose ASCII value
is provided to it.
▪ The syntax of putchar() is
putchar(character_variable);
▪ where, character_variable will be char type variable holding the
ASCII value.
▪ The statement sequence,
char c = ‘a’;
putchar(c);
will display the character ‘a’ on output screen.
Formatted Input(Example::formatted_in.c)
▪ scanf() function can be used to read various types of data in different
formats.
▪ The format specification for integer data is %wd
Where, w stands for width (number of digits), while d stands for integer number.
▪ For example,
scanf(“ %3d %4d”, &num1,&num2);
statement is used and if the input is given like
234 4563
then, 234 will be assigned to num1 and 4563 will be assigned to num2.
But, if the input is 2344 563
Then, num1=234 and num2=4
▪ For floating point numbers or double numbers, width is not necessary.
To read float number, use %f, while for double number use %lf.
Formatted Output
▪ We can format the output with printf() function. The format
specification for integer data is %wd
Where, w stands for width (number of digits) to be used for printing, while d
stands for integer number.
▪ By default integer is printed right justified, we can change the
justification by using hyphen (-) flag. Following table lists output flags.
Flag Meaning
– Left justified print, remaining spaces left blank
+ Print + or – before the number (signed number)
0 Leading zeros are printed
#o 0 before octal number
#x 0x before hex number
e Scientific notation
Formatted Output (Example::formatted_out.c)
▪ Some examples
Format Output
printf(“%d”,456); 4 5 6
printf(“%5d”,456); 4 5 6

printf(“%2d”,456); 4 5 6

printf(“%05d”,456); 0 0 4 5 6
printf(“%-5d”,456); 4 5 6
printf(“%+5d”,456); + 4 5 6
printf(“%#5o”,456); 0 7 1 0
printf(“%#5x”,456); 0x1c8 0 X 1 c 8
Formatted Output(Example::formatted_out1.c)
▪ The format specification for floating data is %w.pf
Where, w denotes width, p denotes number of digits after decimal point,
and f denotes float number. If e is used in place of f, then the number is
displayed in scientific notation.
▪ If width is not specified, then the floating point number is
displayed with six decimal point digits.
Format Output
printf(“%f”,45.678); 4 5 . 6 7 8 0 0 0
printf(“%7.2f”,45.678); 4 5 . 6 8
printf(“%-7.2f”,45.678);
4 5 . 6 8
printf(“%7.2e”,45.678);
4 . 5 7 e + 0 1
printf(“%e”,45.678);
4 . 5 6 7 8 0 0 e 0 1

You might also like