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

C Programming - Notes-1

The document discusses the basic components and functions of a computer system. It explains that a computer takes input from the user, processes data, produces output, and stores information. The main components are the hardware, software, and user. The hardware includes input, output, storage, and other physical devices. The software allows the user to interact with the hardware. When a user provides input, the application processes the data using the operating system and hardware, and then displays the output.

Uploaded by

Sumit Nirmal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views

C Programming - Notes-1

The document discusses the basic components and functions of a computer system. It explains that a computer takes input from the user, processes data, produces output, and stores information. The main components are the hardware, software, and user. The hardware includes input, output, storage, and other physical devices. The software allows the user to interact with the hardware. When a user provides input, the application processes the data using the operating system and hardware, and then displays the output.

Uploaded by

Sumit Nirmal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Computer Systemst is Cmputer?

Computer is an electronic device which operates under the control of instructions


stored in its own memory. A computer can take data from the user through input
devices (Input), process the user given data (Processing), produces the result to the
user through output devices (Output)and stores data (Information) for future use.
Computer can be defined as follows...

Computer is an electronic device which operates under the control of instructions


stored in its own memory and it takes the data from the user, process that data,
gives the result and stores the result for future use.

Every computer mainly consists of three things and those are...

1. Hardware
2. Software
3. User

Here the user interacts with the software, and the software makes the computer
hardware parts to work for the user.
What isputer Hardware?
All physical components of the computer are called as computer hardware. A user can
see, touch and feel every hardware of the computer. All hardware components perform
any task based on the instructions given by the computer software.

The computer hardware is the physical part of a computer.

The computer hardware components are as follows...

1. Input Devices - These are the parts through which a user can give the data to the
computer.
2. Output Devices - These are the physical components of a computer through which
the computer gives the result to the user.
3. Storage Devices - These are the physical components of a computer in which the
data can be stored.
4. Devices Drives - Using drives, user can read and write data on to the strorage
devices like CD, floppy, etc.,
5. Cables - Various cables (Wires) are used to make connections in a computer
6. Other Devices - Other than the above hardware components, a computer also
contains components like Mother board, CPU (Processor), SMPS, Fans, etc.,

Input Devices
Computer input devices are the physical components of the computer which are used to
give the data given by the user to the computer. Using input devices the user can give
the data to the computer.

Example

Output Devices
Computer output devices are the physical components of the computer which are used
to give the computer result to the User. Using output devices, the user can see the
computer generated result.

Example
Storage Devices
Computer storage devices are the physical components of the computer which are used
to store data internally or externally.
Example

Device Drives
Computer Device drives are the physical components of the computer which are used to
read and write data of the storage devices.
Example
Computer Cables
In a Computer, various cables are used to make connections among the various
hardware components of the computer.

Example

Other Devices
Other devices of the computer are shown below...

CPU (Processor)

SMPS
CPU Fan (Heat Sinck)

Mother Board

When a user wants to communicate with the computer, the user interacts with an
application. The application interacts with the operating system, and the operating
system makes hardware components to work according to the user given instructions.
The hardware components sends the result back to the operating system, then the
operating system forwards the same to the application and the application shows the
result to the user.By using input devices, the user interacts with the application and the
application uses output devices to show the result. All input and output devices work
according to the instructions given by the operating system. The working process of a
computer is shown in the following figure...
Computer Languages
Generally, we use languages like english, hindi, telugu etc., to make communication
between two persons. That means, when we want to make communication between two
persons we need a language through which persons can express their feelings. Similarly,
when we want to make communication between user and computer or between two or
more computers we need a language through which user can give information to
computer and vice versa. When user wants to give any instruction to the computer the
user needs a specific language and that language is known as computer language.

User interacts with the computer using programs and that programs are created using
computer programming languages like C, C++, Java etc.,

Computer languages are the languages through which user can communicate with
the computer by writing program instructions.

Every computer programming language contains a set of predefined words and a set of
rules (syntax) that are used to create instructions of a program.

Computer Languages Classification

Over the years, computer languages have been evolved from Low Level to High Level
Languages. In the earliest days of computers, only Binary Language was used to write
programs. The computer languages are classified as follows...
Low Level Language (Machine Language)
Low Level language is the only language which can be understood by the
computer. Binary Language is an example of low level language. Low level language is
also known as Machine Language. The binary language contains only two symbols 1 & 0.
All the instructions of binary language are written in the form of binary numbers 1's &
0's. A computer can directly understand the binary language. Machine language is also
known as Machine Code.

As the CPU directly understands the binary language instructions, it does not
requires any translate. CPU directly starts executing the binary language instructions,
and takes very less time to execute the instructions as it does not requires any
translation. Low level language is considered as the First Generation Language (1GL).

Middle Level Language (Assembly Language)

Middle level language is a computer language in which the instructions are created
using symbols such as letters, digits and special characters. Assembly language is an
example of middle level language. In assembly language, we use predefined words
called mnemonics. Binary code instructions in low level language are replaced with
mnemonics and operands in middle level language. But computer can not understand
mnemonics, so we use a translator called Assembler to translate mnemonics into binary
language. Assembler is a translator which takes assembly code as input and produces
machine code as output. That means, computer can not understand middle level
language, so it needs to be translated into low level language to make it understandable
by the computer. Assembler is used to translate middle level language to low level
language.

High Level Language


High level language is a computer language which can be understood by the users.
High level language is very similar to the human languages and have a set of grammar
rules that are used to make instructions more easily. Every high level language have a
set of predefined words known as Keywords and a set of rules known as Syntax to create
instructions. High level language is more easier to understand for the users but the
computer can not understand it. High level language needs to be converted into low
level language to make it understandable by the computer. We
useCompiler or interpretor to convert high level language to low level language.

Languages like COBOL, FORTRAN, BASIC, C ,C++, JAVA etc., are the examples
of high level languages. All these programming languages use human understandable
language like english to write program instructions. These instructions are converted to
low level language by the compiler so that it can be understood by the computer.

Basic Structure of a C Program:


To write a C program, we first create functions and then put them together. A C program may contain one or
more sections. They are illustrated below.

 Documentation section : The documentation section consists of a set of


comment lines giving the name of the program, the author and other details,
which the programmer would like to use later.
 Link section : The link section provides instructions to the compiler to link
functions from the system library.
 Definition section : The definition section defines all symbolic constants.
 Global declaration section : There are some variables that are used in more
than one function. Such variables are called global variables and are declared in
the global declaration section that is outside of all the functions. This section
also declares all the user-defined functions.
 main () function section : Every C program must have one main function
section. This section contains two parts; declaration part and executable
partDeclaration part : The declaration part declares all the variables used in
the executable part.Executable part : There is at least one statement in the
executable part. These two parts must appear between the opening and closing
braces. The program execution begins at the opening brace and ends at the
closing brace. The closing brace of the main function is the logical end of the
program. All statements in the declaration and executable part end with a
semicolon.
 Subprogram section : The subprogram section contains all the user-defined
functions that are called in the main () function. User-defined functions are
generally placed immediately after the main () function, although they may
appear in any order. Note:All section, except the main () function section may
be absent when they are not required.

Sample C Program:

#include<stdio.h> <———————-Preprocessing Directive

void main()

{ <——————–Start of a Program

/*………….Printing Starts………….*/

Printf(“Learn at every moment”);

/*………….Printing starts……..*/

} <———————-End of a Program

 In C many library functions are grouped category-wise and stored in different


files known as header files. Ex. stdio.h–>standard input output header file
 To use the functions defined in the header file that need to be included in the
program
 This can be achieved by the preprocessing directive “#include”
 “#include” includes the content of header file(stdio.h) at the beginning of
program.
 Explanation of void main in detail is present later.

C- Character Set
As every language contains a set of characters used to construct words, statements etc.,
C language also has a set of characters which include alphabets, digits and special
symbols. C language supports a total of 256 characters.

Every C program contains statements. These statements are constructed using words
and these words are constructed using characters from C character set. C language
character set contains the following set of characters...

1. Alphabets
2. Digits
3. Special Symbols

Alphabets

C language supports all the alphabets from english language. Lower and upper case
letters together supports 52 alphabets.

 lower case letters - a to z


 UPPER CASE LETTERS - A to Z

Digits

C language supports 10 digits which are used to construct numerical values in C


language.

 Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Special Symbols

C language supports rich set of special symbols that include symbols to perform
mathematical operations, to check conditions, white spaces, back spaces and other
special symbols.

Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < \ | tab newline space
NULL bell backspace verticaltab etc.

Variables
Variables in c programming language are the named memory locations where user can
store different values of same datatype during the program execution. That means,
variable is a name given to a memory location in which we can store different values of
sasme datatype. In other words a variable can be defined as a storage container to hold
values of same datatype during the program execution. The formal definition of
datatype is as follows...

Variable is a name given to a memory location where we can store defferent values
of same datatype during the program execution.
Every variable in c programming language must be declared in the declaration section
before it is used. Every variable must have a datatype that determines the range and
type of values to be stored and size of the memory to be allocated.

A variable name may contain letters, digits and underscore symbol. The following are
the rules to specify a variable name...

Variable name should not start with digit.

Keywords should not be used as variable names.

Variable name should not contain any special symbols except underscore(_).

Variable name can be of any length but compiler considers only the first 31 characters
of the variable name.

Declaration of Variable

Declaration of a variable tells to the compiler to allocate required amount of memory


with specified variable name and allows only specified datatype values into that
memory location. In C programming language, the declaration can be performed either
before the function as global variables or inside any block or function. But it must be at
the begining of block or function.

Declaration Syntax:

datatype variableName;

Example

int number;

The above declaration tells to the compiler that allocate 2 bytes of memory with the
name numberand allows only integer values into that memory location.

Constants
A constant is a entity that does not change but not change but the variable is the entity
that may change. Constant is usually referred as a value and variable is a name which
stores a value at a time . In program we do many calculations. During the calculations or
after that we need to store some values for the retrieval purpose. i.e. we may require
stored values for the further calculation or just as a final result. To store these values
we need memory. Memor is set of millions of cells. One cell stores one value at a time .
for recognizing these memory location user can give name to that location. The memory
location cell name is called as variable.

Types of constants

C constants are divided into two types :

1. Primary constants
2. Secondary constants

In this initial stage we are going to know more about primary constants. Primary
constants are the basic data types in which user enter the values. Basically data is
collection of facts, figures and numbers. i.e real (float) , integer or characters.

C constants

Primary constants secondary constants

Integer constants Array


Real (float) constants Pointer
Character constants Union
Enum

Integer constants :-
a. An integer constant should be at east one digit and can not have decimal points.
b. It can be positive or negative. If sign is not given, then integer constant is
considered a positive
c. No commas or bank spaces are allowed within integer constant.
d. The rage of integer constant is form -32767 to 32767
Example +426
-945
9000

Real (float) constants :-


a. A real constants should be at least one digit and must have decimal points.
b. It can be positive or negative. If sign is not given, then real constant is considered
as positive.
c. No commas of blank spaces are allowed within real constant
The exponential representation is used when value is too small or too large. In this types
of number representation there are two parts called mantissa and exponent. The part
which comes before ‘e ‘ is called as exponents.
a. The mantissa and exponents part should be separated by letter ’e’
b. The mantissa and exponents both can be positive or negative.
c. Range of real constant is -3.4e38 to 3.4e38
Example -3.2e-2
0.2e+3

Character constants :-

A single character enclosed in apostrophes is known as a character constants. Character


constants can be single alphabet, or digit or a special symbol. The character constant Is
specified using.
Example ’G’, ‘6’, ‘+’

Datatypes
Data used in c program is classified into different types based on its properties. In c programming
langauge, datatype can be defined as a set of values with similar characteristics. All the values in a
datatype have the same properties.

Datatypes in c programming language are used to specify what kind of value can be stored in a
variable. The memory size and type of value of a variable are determined by varible datatype. In a
c program, each variable or constant or array must have a datatype and this datatype specifies how
much memory is to be allocated and what type of values are to be stored in that variable or
constant or array. The formal definition of data type is as follows...

Datatype is a set of value with predefined characteristics. Datatypes are used to declare
variable, constants, arrays, pointers and functions.

In c programming language, datatypes are classified as follows...

1. Primary Datatypes (Basic Datatypes OR Predefined Datatypes)


2. Derived Datatypes (Secondary Datatypes OR Userdefined Datatypes)

Primary Datatypes

The primary datatypes in C programming language are the basic datatypes. All the primary
datatypes are already defined in the system. Primary datatypes are also called as Built-In
datatypes. The following are the primary datatypes in c programming lanuage...
1. Integer Datatype
2. Floating Point Datatype
3. Double Datatype
4. Character Datatype

Integer Datatype

Integer datatype is a set of whole numbers. Every integer value does not have the decimal value.
We use the keyword "int" to represent integer datatype in c. We use the keyword int to declare the
variables and to specify return type of a function. The integer datatype is used with different type
modifiers like short, long, signed and unsigned. The following table provides complete details
about integer datatype.

Floating Point Datatypes

Floating point datatypes are set of numbers with decimal value. Every floating point value must
contain the decimal value. The floating point datatype has two variants...

 float
 double

We use the keyword "float" to represent floating point datatype and "double" to represent double
datatype in c. Both float and double are similar but they differ in number of decimal places. The
float value contains 6 decimal places whereas double value contains 15 or 19 decimal places. The
following table provides complete details about floating point datatypes.
z

Character Datatype

Character datatype is a set of characters enclosed in single quotations. The following table
provides complete details about character datatype.

The following table provides complete information about all the datatypes in c programming
language...

Derived Datatypes
Derived datatypes are user-defined data types. The derived datatypes are also called as user
defined datatypes or secondary datatypes. In c programming language, the derived datatypes are
created using the following concepts...

 Arrays
 Structures
 Unions
 Enumeration

Type Casting
Type casting is also called as explicit type conversion. Compiler converts data from one
datatype to another datatype implicitly. When compiler converts implicitly, there may
be a data loss.In such case, we convert the data from one datatype to another datatype
using explicit type conversion. To perform this we use the unary cast operator. To
convert data from one type to another type we specify the target datatype in
paranthesis as a prefix to the data value that has to be converted. The general syntax of
type casting is as follows...

(TargetDatatype) DataValue

Example
int total Marks = 450, max Marks = 600 ;
float average ;

average = (float) totalMarks / maxMarks * 100 ;

In the above example code, both totalMarks and maxMarks are integer data values.
When we perform totalMarks / maxMarks the result is a float value, but the destination
(average) datatype is float. So we use type casting to convert totalMarks and maxMarks
into float datatype.

Example Program
#include <stdio.h>

void main()

int a, b, c ;

float avg ;

printf("Enter any three integer values : ") ;

scanf("%d%d%d", &a, &b, &c) ;

avg = (a + b + c) / 3 ;

printf("avg before casting = %f\n",avg);

avg = (float)(a + b + c) / 3 ;

printf("avg after casting = %f\n",avg);

}
Output:

Enter any three integer values : 5 3 2


avg before casting = 3
avg after casting = 3.333333

Operators
Operators are the symbols used to indicate the operations on the operands i.e. values.
e.g. 10+20 in this example 10 and 20 are called as operands and + is called as arithmetic
operator which will add two values 10 and 20

A=5

A=7

A*b

Here a and b are called as variables, 5 and 7 are called as values and * is operator which
is used for the multiplication. An expression is consist of operators, operands or
variables.

There are different types of operators which are used as per users need. The different
types of operators available in c are as follows:

1. Arithmetical
2. Relational
3. Logical
4. Assignment
5. Conditional
6. Bitwise

Arithmetical operators :-
Arithmetical operators are used to do basic operations like addition, subtraction,
multiplication and division. % is operator called as modulus operator. This is used to
find out the remainder from division.

SR. NO OPERATOR MEANING


1 + Addition
2 - Subtraction
3 * Multiplication
4 / Division
5 % modules
Relational operators :-
Relational operators are popularly known as comparison operators. These operators
check the relation between two values or variables.

Sr.no Operator Meaning


1 < Less than
2 > Grater than
3 <= Less than or equal to
4 >= Greater than or equal to
5 = Equal to
6 != Not equal to

e.g consider the following statement used with the if statement. If statement is
used to check the different conditions. Imagine we have two number stored in two
variables called as a and b. if we want to compare these two number then the following
statement con be written.

If (a>b) this statements checks whether the value stored in variable is grater than
variable b.

Logical operators :-
Logical operators are used to evaluate the conditions or expressions. The logical
operators are AND, OR and NOT. The AND operators checks for all the conditions to be
true then only it returns true else false. OR operators conditions checks for any one or
all conditions from the given conditions to be true then it evaluates true otherwise if
all conditions are false then it returns false. Another operator is NOT. This is calles as
negation operator. It checks for the negative condition.

Expression is set of operators and operands. Consider the following expression c=a+b

Sr. no Operator Meaning


1 && AND- True if all conditions are true
2 || OR- True if any one or all conditions are true
3 ! NOT- Negation
Assignment operators :-

The assignment operators used regularly is ‘=’ This is used to assign some value to the
variable

E.g. b=10

Here we are assigning the value 10 to the variable b. C uses some shorthand operators
to assign the values. It is very interesting to learn them.

e.g. a*=b+5 means a=a*(b+5)

a/=b is a=a/b

a%=5 is a=a%b

Conditional Operator
Conditional operator is in combination of ‘ ? : ‘ This is called as ternary operator.
The general for is

Syntax :- expression1 ? expression2 : expression3

It checks for the condition and evaluates the result depending on the status of
condition

i.e. true or false.

e.g. max=a>b ? a:b

In the above statement if a>b then the condition becomes true then max variable
will store value of a. Otherwise if a>b is false then max will store value of b So
conditional operator evaluates true of false and returns the result.

Bitwise operators
Bitwise operators are used to manipulate the data at bit level. Basically computer
does not understand any language.

It understands machine code which is in the form of 0’s and 1’s or it understands
language like assembly which is hardware oriented. But the language in which user
writes the program is high level language. There are some special programs which
converts the high level language into the low level language. These programs are
called as compilers.

Compiler compiles the data and program in the machinery code i.e. low level
language in the form of 0 and 1. ‘0’ and ‘1’ are called as bits . so to do multiple
operations on these bits we require bitwise operators.

Sr no Operator Meaning
1 & Bitwise AND
2 | Bitwise OR
3 ^ Bitwise exclusive OR
4 << Shift Left
5 >> Shift Right

C – STANDARD LIBRARY FUNCTIONS


 Library functions in C language are inbuilt functions which are grouped
together and placed in a common place called library.

 Each library function in C performs specific operation.

 We can make use of these library functions to get the pre-defined output
instead of writing our own code to get those outputs.

 These library functions are created by the persons who designed and created C
compilers.

 All C standard library functions are declared in many header files which are
saved as file_name.h.

 Actually, function declaration, definition for macros are given in all header
files.

 We are including these header files in our C program using


“#include<file_name.h>” command to make use of the functions those are
declared in the header files.

 When we include header files in our C program using “#include<filename.h>”


command, all C code of the header files are included in C program. Then, this
C program is compiled by compiler and executed.
Header
file Description

This is standard input/output header file


in which Input/Output
stdio.h
functions are declared

conio.h This is console input/output header file

All string related functions are defined in


string.h this header file

This header file contains general


stdlib.h functions used in C programs

All maths related functions are defined in


math.h this header file

This header file contains time and clock


time.h related functions

Managing Input And Output

C – printf and scanf

 printf() and scanf() functions are inbuilt library functions in C programming language
which are available in C library by default. These functions are declared and related macros
are defined in “stdio.h” which is a header file in C language.
 We have to include “stdio.h” file as shown in below C program to make use of these printf()
and scanf() library functions in C language.

1. PRINTF() FUNCTION IN C LANGUAGE:

 In C programming language, printf() function is used to print the “character, string, float,
integer, octal and hexadecimal values” onto the output screen.
 We use printf() function with %d format specifier to display the value of an integer
variable.
 Similarly %c is used to display character, %f for float variable, %s for string
variable, %lf for double and %x for hexadecimal variable.
 To generate a newline,we use “\n” in C printf() statement.

Note:
 C language is case sensitive. For example, printf() and scanf() are different from Printf()
and Scanf(). All characters in printf() and scanf() functions must be in lower case.

EXAMPLE PROGRAM FOR C PRINTF() FUNCTION:

#include <stdio.h>

Void main()

Char ch='A';

Char str[20]="fresh2refresh.com";

Float flt=10.234;

Int no=150;

Double dbl=20.123456;

Printf ("Character is %c \n",ch);

Printf ("String is %s \n",str);

Printf ("Float value is %f \n",flt);

Printf ("Integer value is %d\n",no);

Printf ("Double value is %lf \n",dbl);

Printf ("Octal value is %o \n",no);

Printf ("Hexadecimal value is %x \n",no);

Return 0;

}
OUTPUT:

Character is A
String is fresh2refresh.com
Float value is 10.234000
Integer value is 150
Double value is 20.123456
Octal value is 226
Hexadecimal value is 96

%d got replaced by value of an integer variable

%c got replaced by value of a character variable

%f got replaced by value of a float variable

%s got replaced by value of a string variable

\n got replaced by a newline.

2. SCANF() FUNCTION IN C LANGUAGE:

In C programming language, scanf() function is used to read character, string, numeric


data from keyboard

Consider below example program where user enters a character. This value is assigned
to the variable “ch” and then displayed.

Then, user enters a string and this value is assigned to the variable “str” and then
displayed.

EXAMPLE PROGRAM FOR PRINTF() AND SCANF() FUNCTIONS IN C PROGRAMMING LANGUAGE:

#include <stdio.h>
intmain()
{
Char ch;
Char str[100];
Printf ("Enter any character \n");
Scanf ("%c",&ch);
Printf ("Entered character is %c \n",ch);
Printf ("Enter any string ( upto 100 character ) \n");
Scanf ("%s",&str);
Printf ("Entered string is %s \n",str);
}
OUTPUT :
Enter any character
a
Entered character is a
Enter any string ( upto 100 character )
hai
Entered string is hai

The format specifier %d is used in scanf() statement. So that, the value entered is received as
an integer and %s for string.

Ampersand is used before variable name “ch” in scanf() statement as &ch.

It is just like in a pointer which is used to point to the variable. For more information about
how pointer works, please click here.

KEY POINTS TO REMEMBER IN C PRINTF() AND SCANF():


 printf() is used to display the output and scanf() is used to read the inputs.
 printf() and scanf() functions are declared in “stdio.h” header file in C library.
 All syntax in C language including printf() and scanf() functions are case sensitive.

Input Functions in C
C programming language provides built-in functions to perform input operations. The
input opearations are used to read user values (input) from keyboard. C programming
language provides the following built-in input functions...

 scanf()
 getchar()
 getch()
 gets()
scanf() function

The scanf() function is used to read multiple data values of different data types from
the keyboard. The scanf() function is built-in function defined in a header file called
"stdio.h". When we want to use scanf() function in our program, we need to include the
respective header file (stdio.h) using#include statement. The scanf() function has the
following syntax...

Syntax:

scanf("format strings",&variableNames);

Example Program

#include <stdio.h>

void main()

int i;

printf("\nEnter any integer value: ");

scanf("%d",&i);

printf("\nYou have entered %d number",i);

Output:

Enter any integer value: 55


You have entered 55 number

In the above example program, we used the scanf() function to read an integer value
from the keyboard and store it into variable 'i'.

The scanf function also used to read multiple data values of different or same data
types. Consider the following example program...
#include <stdio.h>

void main()

int i;

float x;

printf("\nEnter one integer followed by one float value : ");

scanf("%d%f",&i, &x);

printf("\ninteger = %d, float = %f",i, x);

Output:

Enter one integer followed by one float value : 20 30.5


integer = 20, float = 30.5

In the above example program, we used the scanf() function to read one integer value
and one float value from the keyboard. Here 'i' is an integer variable so we have used
format string %d, and 'x' is a float variable so we have used format string %f.

The scanf() function returns an integer value equal to the total number of input values
read using scanf function.

Example Program

#include <stdio.h>

void main()

int i,a,b;

float x;

printf("\nEnter two integers and one float : ");

i = scanf("%d%d%f",&a, &b, &x);

printf("\nTotal inputs read : %d",i);


}

Output:

Enter two integers and one float : 10 20 55.5


Total inputs read : 3

getchar() function
The getchar() function is used to read a character from the keyboard and return it to
the program. This function is used to read only single character. To read multiple
characters we need to write multiple times or use a looping statement. Consider the
following example program...

#include <stdio.h>

void main()

char ch;

printf("\nEnter any character : ");

ch = getchar();

printf("\nYou have entered : %c",ch);

Output:

Enter any character : A


You have entered : A

getch() function
The getch() function is similar to getchar function. The getch() function is used to read
a character from the keyboard and return it to the program. This function is used to read
only single character. To read multiple characters we need to write multiple times or use a
looping statement. Consider the following example program...

#include <stdio.h>

void main()

{
char ch;

printf("\nEnter any character : ");

ch = getch();

printf("\nYou have entered : %c",ch);

Output:

Enter any character :


You have entered : A

gets() function
The gets() function is used to read a line of string and stores it into character array. The
gets() function reads a line of string or sequence of characters till a newline symbol enters.
Consider the following example program...

#include <stdio.h>

void main()

char name[30];

printf("\nEnter your favourite website: ");

gets(name);

printf("%s",name);

Output:

Enter your favourite website: www.btechsmartclass.com


www.btechsmartclass.com

putchar() function
The putchar() function is used to display single character on the output screen. The
putchar() functions prints the character which is passed as parameter to it and returns the
same character as return value. This function is used to print only single charater. To print
multiple characters we need to write multiple times or use a looping statement. Consiider
the following example program...
#include <stdio.h>

void main()

char ch = 'A';

putchar(ch);

Output:

if statement in C
What is Decision Making Statement?

In c programming language, the program execution flow is, line by line from top to
bottom. That means the c program is executed line by line from the main method. But this
type of execution flow may not be suitable for all the program solutions. Sometimes, we
make some decisions or we may skip the execution of one or more lines of code. Consider a
situation, where we write a program to check whether a student has passed or failed in a
particular subject. Here, we need to check whether the marks are greater than the pass
marks or not. If marks are greater, then we take the decision that the student has passed
otherwise failed. To solve such kind of problems in c we use the statements called decision
making statements.

Decision making statements are the statements that are used to verify a given
condition and decides whether a block of statements gets executed or not based on
the condition result.

In c, if statement is used to make decisions based on a condition. The if statement verifies


the given condition and decides whether a block of statements are executed or not based
on the condition result. In c, if statement is classified into four types as follows...

 Simple if statement
 if - else statement
 Nested if statement
 if-else-if statement (if-else ladder)
Simple if statement
Simple if statement is used to verify the given condition and executes the block of
statements based on the condition result. The simple if statement evaluates specified
condition. If it is TRUE, it executes the next statement or block of statements. If the
condition is FALSE, it skips the execution of the next statement or block of statements. The
general syntax and execution flow of the simple if statement is as follows...

Simple if statement is used when we have only one option that is executed or skipped
based on a condition.

Example Program | Test whether given number is divisible by 5.

#include <stdio.h>

#include<conio.h>

void main()

int n ;

clrscr() ;

printf("Enter any integer number: ") ;

scanf("%d", &n) ;

if ( n%5 == 0 )

printf("Given number is divisible by 5\n") ;

printf("statement does not belong to if!!!") ;

}
Output 1:

Enter any integer number: 100


Given number is divisible by 5
statement does not belong to if!!!

Output 2:

Enter any integer number: 99


statement does not belong to if!!!

if - else statement
The if - else statement is used to verify the given condition and executes only one out
of the two blocks of statements based on the condition result. The if-else statement
evaluates the specified condition. If it is TRUE, it executes a block of statements (True
block). If the condition is FALSE, it executes another block of statements (False block). The
general syntax and execution flow of the if-else statement is as follows...

The if-else statement is used when we have two options and only one option has to
be executed based on a condition result (TRUE or FALSE).

Example Program | Test whether given number is even or odd.


#include <stdio.h>

#include<conio.h>

void main()

int n ;

clrscr() ;

printf("Enter any integer number: ") ;

scanf("%d", &n) ;

if ( n%2 == 0 )

printf("Given number is EVEN\n") ;

else

printf("Given number is ODD\n") ;

Output 1:

Enter any integer number: 100


Given number is EVEN

Output 2:

Enter any integer number: 99


Given number is ODD

Nested if statement
Writing a if statement inside another if statement is called nested if statement. The
general syntax of the nested if statement is as follows...
The nested if statement can be defined using any combination of simple if & if-else
statements.

Example Program | Test whether given number is even or odd if it is below 100.

#include <stdio.h>

#include<conio.h>

void main()

int n ;

clrscr() ;

printf("Enter any integer number: ") ;

scanf("%d", &n) ;

if ( n < 100 )

printf("Given number is below 100\n") ;

if( n%2 == 0)

printf("And it is EVEN") ;

else

printf("And it is ODD") ;
}

else

printf("Given number is not below 100") ;

Output 1:
Enter any integer number: 55
Given number is below 100
And it is ODD

Output 2:

Enter any integer number: 999


Given number is not below 100

if - else - if statement (if-else ladder)


Writing a if statement inside else of a if statement is called if - else - if
statement. The general syntax of the if-else-if statement is as follows...
The if-else-if statement can be defined using any combination of simple if & if-else
statements.

Example Program | Find the largest of three numbers.

#include <stdio.h>

#include<conio.h>

void main()

int a, b, c ;

clrscr() ;

printf("Enter any three integer numbers: ") ;

scanf("%d%d%d", &a, &b, &c) ;

if( a>=b && a>=c)

printf("%d is the largest number", a) ;

else if (b>=a && b>=c)

printf("%d is the largest number", b) ;

else

printf("%d is the largest number", c) ;

Output 1:

Enter any three integer numbers: 55 60 20


60 is the largest number

while Statement in C
Consider a situation in which we execute a single statement or block of statements
repeatedly for required number of times. Such kind of problems can be solved
using looping statements in C. For example, assume a situation where we print a message
for 100 times. If we want to perform that task without using looping statements, we have
to either write 100 printf statements or we have to write the same message for 100 times
in a single printf statement. Both are complex methods. The same task can be performed
very easily using looping statements.

The looping statements are used to execute a single statement or block of


statements repeatedly until the given condition is FALSE.

C language provides three looping statements...

 while statement
 do-while statement
 for statement

while Statement
The while statement is used to execute a single statement or block of statements
repeatedly as long as the given condition is TRUE. The while statement is also known
as Entry control looping statement. The while statement has the following syntax...

At first, the given condition is evaluated. If the condition is TRUE, the single
statement or block of statements gets executed. Once the execution gets completed the
condition is evaluated again. If it is TRUE, again the same statements gets executed. The
same process is repeated until the condition is evaluated to FALSE. Whenever the condition
is evaluated to FALSE, the execution control moves out of the while block.

Example Program | Program to display even numbers upto 10.

#include <stdio.h>
#include<conio.h>

void main()

int n = 0;

clrscr() ;

printf("Even numbers upto 10\n");

while( n <= 10 )

if( n%2 == 0)

printf("%d\t", n) ;

n++ ;

getch() ;

Output 1:

Even numbers upto 10


0 2 4 6 8 10

do-while Statement in C
The do-while statement is used to execute a single statement or block of statements
repeatedly as long as given the condition is TRUE. The do-while statement is also known
as Exit control looping statement. The do-while statement has the following syntax...
At first, the single statement or block of statements which are defined in do block are
executed. After execution of do block, the given condition gets evaluated. If the condition
is evaluated to TRUE, the single statement or block of statements of do block are executed
again. Once the execution gets completed again the condition is evaluated. If it is TRUE,
again the same statements are executed. The same process is repeated until the condition
is evaluated to FALSE. Whenever the condition is evaluated to FALSE, the execution control
moves out of the while block.

Example Program | Program to display even numbers upto 10.

#include <stdio.h>

#include<conio.h>

void main()

int n = 0;

clrscr() ;

printf("Even numbers upto 10\n");

do

if( n%2 == 0)

printf("%d\t", n) ;

n++ ;
}

while( n <= 10 ) ;

getch() ;

Output 1:

Even numbers upto 10


0 2 4 6 8 10

for Statement in C
The for statement is used to execute a single statement or a block of statements
repeatedly as long as the given condition is TRUE. The for statement has the following
syntax and execution flow diagram...

SYNTAX

For (initialization; condition; increment/decrement(modifications))

Block of statement;

... ... ...

At first, the for statement executes initialization followed by condition evaluation. If


the condition is evaluated to TRUE, the single statement or block of statements of for
statement are executed. Once the execution gets completed, the modification statement is
executed and again the condition is evaluated. If it is TRUE, again the same statements are
executed. The same process is repeated until the condition is evaluated to FALSE.
Whenever the condition is evaluated to FALSE, the execution control moves out of the for
block.

Example Program | Program to display even numbers upto 10.

#include <stdio.h>

#include<conio.h>

void main()

{
int n ;

clrscr() ;

printf("Even numbers upto 10\n");

for( n = 0 ; n <= 10 ; n++ )

if( n%2 == 0)

printf("%d\t", n) ;

getch() ;

Output 1:

Even numbers upto 10


0 2 4 6 8 10

You might also like