C Programming - Notes-1
C Programming - Notes-1
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.
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.
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 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.
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.
Sample C Program:
void main()
{ <——————–Start of a Program
/*………….Printing Starts………….*/
/*………….Printing starts……..*/
} <———————-End of a Program
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.
Digits
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 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 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
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
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
Character constants :-
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.
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 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 ;
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 ;
avg = (a + b + c) / 3 ;
avg = (float)(a + b + c) / 3 ;
}
Output:
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.
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
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.
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
It checks for the condition and evaluates the result depending on the status of
condition
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
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.
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.
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.
#include <stdio.h>
Void main()
Char ch='A';
Char str[20]="fresh2refresh.com";
Float flt=10.234;
Int no=150;
Double dbl=20.123456;
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
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.
#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.
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.
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;
scanf("%d",&i);
Output:
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;
scanf("%d%f",&i, &x);
Output:
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;
Output:
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;
ch = getchar();
Output:
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;
ch = getch();
Output:
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];
gets(name);
printf("%s",name);
Output:
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.
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.
#include <stdio.h>
#include<conio.h>
void main()
int n ;
clrscr() ;
scanf("%d", &n) ;
if ( n%5 == 0 )
}
Output 1:
Output 2:
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).
#include<conio.h>
void main()
int n ;
clrscr() ;
scanf("%d", &n) ;
if ( n%2 == 0 )
else
Output 1:
Output 2:
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() ;
scanf("%d", &n) ;
if ( n < 100 )
if( n%2 == 0)
printf("And it is EVEN") ;
else
printf("And it is ODD") ;
}
else
Output 1:
Enter any integer number: 55
Given number is below 100
And it is ODD
Output 2:
#include <stdio.h>
#include<conio.h>
void main()
int a, b, c ;
clrscr() ;
else
Output 1:
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.
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.
#include <stdio.h>
#include<conio.h>
void main()
int n = 0;
clrscr() ;
while( n <= 10 )
if( n%2 == 0)
printf("%d\t", n) ;
n++ ;
getch() ;
Output 1:
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.
#include <stdio.h>
#include<conio.h>
void main()
int n = 0;
clrscr() ;
do
if( n%2 == 0)
printf("%d\t", n) ;
n++ ;
}
while( n <= 10 ) ;
getch() ;
Output 1:
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
Block of statement;
#include <stdio.h>
#include<conio.h>
void main()
{
int n ;
clrscr() ;
if( n%2 == 0)
printf("%d\t", n) ;
getch() ;
Output 1: