Overview of Computer Systems and Software
Overview of Computer Systems and Software
Introduction
System:system is a collection of components working together to perform a
specific task.
Commonly
Opearting
Machine
particularly
Used for
Trade
Education
Reasearch
Computer
System
Hardware Software
Computer Hardware
The hardware component of the computer system consists of five parts: input
devices, central processing unit (CPU) ,primary storage, output devices, and
auxiliary storage devices.
ALU,CU,memory
Auxiliary storage, also known as secondary storage, is used for both input
and output. It is the place where the programs and data are stored permanently.
When we turn off the computer, or programs and data remain in the secondary
storage, ready for the next time we need them.
Computer Software
System software:It manages the computer resources .It provides the interface
between the hardware and the users.
Application software, on the other hand is directly responsible for helping users
to solve their problems.
System software:It manages the computer resources .It provides the interface between the
hardware and the users.
Application software, on the other hand is directly responsible for helping users to solve
their problems.
Application –specific software can be used only for its intended purpose.
[Link]-used for accounting
The relationship between system and application software is shown in [Link] this
figure, each circle represents an interface point .
The inner core is hard ware. The user is represented by the outer layer. To work
with the system user uses some form of application software. The application
software in turn interacts with the operating system ,which is apart of the system
software layer. The system software provides the direct interaction with the hard
ware
A motherboard is the main circuit board inside a computer that connects the
different parts of a computer together.
[Link] Environments
The different types of computing environments are
1. Personal Computing Environment
2. Time-Sharing Environment
3. Client/Server Environment
4. Distributed Computing
1. Personal Computing Environment
In the personal computing environment,there is a single computer system.
In a personal computer, all the hardware components are tied together, so that it can be
used for general purpose.
The ENIAC (Electronic Numerical Integrator and Computer) was the first electronic
programmable computer .
[Link]-Sharing Environment
The time sharing computing environment allows multiple users to share the system
simultaneously. Each user is provided a time slice and the processor switches rapidly among
the users according to it. Because of this, each user believes that they are the only ones using
the system.
In the time-sharing environment, all computing must be done by the central computer. The
central computer has many duties: It must control the shared resources
[Link]/Server Environment
In client server computing, the client requests a resource and the server provides that
resource.
Both the client and server usually communicate via a computer network but sometimes
they may reside in the same system.
[Link] Computing
It is the technique of linking together multiple computer servers over a network into a
cluster, to share data and to coordinate processing power. Such a cluster is referred to as a
“distributed system.”
[Link] Languages:
software Evolution:
1940’s Machine level Languages- uses 0s and 1s-binary
1950’s Assembly language- uses Symbolic or mnemonic codes ex. Add a,b
.
,Subtract a from b,div a,b etc. mul a,b,push a.
Machine Languages
Each computer has its own machine language, which is made of streams of 0’s
and 1’s.
Symbolic Languages:
Computer uses symbolic codes to write a program.
Computer does not understand symbolic language or mnemonic codes - it must be
translated to the machine language. A special program called assembler translates
symbolic code into machine language.
Symbolic program is developed by in early In early 1950’s Admiral Grace
Hopper, A mathematician.
Advantages: 1) Easy to understand and use
2) Easy to modify and isolate error
3) High efficiency
4) More control on hardware
Disadvantages:
1) Machine Dependent Language
2) Requires translator
3) Difficult to learn and write programs
4) Slow development time
High Level Languages: are is easy to read, write, and maintain as it is written in English
like words.
Advantages:
1) Easy to write and understand
2) Easy to isolate an error .
3) Machine independent language.
4) Easy to maintain .
5) Better readability .
6) Low Development cost.
7) Easier to document.
8) Portable
Disadvantages: 1) Needs translator
2) Requires high execution time .
4) Less efficient
Example:
C program for addition of two numbers.
#include<stdio.h>
void main()
{
int a,b,c;
scanf("%d%d%",&a,&b);
c=a+b;
printf("%d",c);
}
Language Translators
These are the programs which are used for converting the programs in one language into
machine language instructions, so that they can be excuted by the computer.
1) Compiler:
-It is a program which is used to convert the high level language programs into
machine language .
Ex.c,c++.
2) Assembler: It is a program which is used to convert the assembly level language
programs into machine language .
3) Interpreter: It is a program, it takes one statement of a high level language program,
translates it into machine language instruction and then immediately executes the resulting
machine language instruction and so on.
[Link].
COMPILER INTERPRETER
A Compiler is used to compile an entire An interpreter is used to translate each line of
program and an executable program is the program code immediately as it is entered
generated through the object program
The executable program is stored in a The executable program is generated in
disk for future use or to run it in RAM
another computer and the interpreter is required for each run of
the program
The compiled programs run faster The Interpreted programs run slower.
Most of the Languages use compiler A very few languages use interpreters.
[Link] AND RUNNING
PROGRAMS OR PROCESS OF
COMPILING AND RUNNING THE
PROGRAM
The procedure for turning a program written in C into machine Language.
The following are the four steps in this process.
1) Writing and Editing the program
2) Compiling the program
3) Linking the program with the required modules.
4) Executing the program
Sl. No. Phase Name of Code Tools File Extension
1 TextEditor Source Code C Compilers .C
Edit,
Notepad Etc..,
2 Compiler Object Code C Compiler .OBJ
3 Linker Executable C Compiler .EXE
Code
4 Runner Executable C Compiler .EXE
Code
The Translator
The Preprocessor reads the source code and prepares it for the translator. Preprocessors are the
programs that process our source code before compilation.
Ex.#include<math.h>
#incude<stdio.h>
Translator Translator is a program who convert the Source code into object code.
Linking Programs
a linker is a computer program that takes one or more object files generated by a compiler and
combines them into one, executable program.
Loader: Loader is the program of the operating system which loads the executable program from
the disk into the primary memory(RAM) for execution.
Executing Programs
When everything is loaded the program takes control and it begin execution.
[Link]
An algorithm is a procedure or step-by-step instructions for solving a problem.
The characteristics of a good algorithm are:
• Precision – the steps are precisely stated (defined).
• Uniqueness – results of each step are uniquely defined and only depend
on the input and the result of the preceding steps.
• Finiteness – the algorithm stops after a finite number of instructions are executed.
• Input – the algorithm receives input.
• Output – the algorithm produces output.
• Generality – the algorithm applies to a set of inputs.
Algorithm 1: Add two numbers entered by the user
Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop
Ans.
step 1 : start
step2:declare the vaiable number,rem
step 2 : read value for number
step 3 : remnumber mod 2
step4 : if rem=0 then
print "number
even"else
print "number odd"
end if
step 5 : stop
number 7
Rem=7 mod 2= 2)7(3-coefficient
6
____
1 remainder
Find the largest number among three numbers
Step 1: Start
Step 2: Declare variables a,b and c.
Step 3: Read variables a,b and c. a=3 b=4 c=5
Step 4: If a > b
If a > c
Display a is the largest number.
Else
If b > c
Display b is the largest number.
Else
Display c is the greatest number. Step5:stop
[Link]
Draw flowchart to find the largest among three different numbers entered by user.
wwww
[Link] TO C LANGUAGE
• C
Program File
• All the C programs are writen into text files with extension ".c" for example hello.c. You
can use"vi" editor to write your C program into a file.
BASIC STRUCTURE OF C PROGRAMMING LANGUAGE #include<stdio.h>
#define pi 3.145
1. 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./* program name */
2. Link section: The link section provides instructions to the compiler to link
functions from the system library such as using the #include directive.
3. Definition section: The definition section defines all symbolic constants such
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.
5. main () function section: Every C program must have one main function
section. This section contains two parts; declaration part and executable part
1. Declaration part: The declaration part declares all the variables used in
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.
6. Subprogram section: If the program is a multi-function program then 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.
C TOKENS
C tokens are the basic buildings blocks in C language which are constructed
together to write a C program.
Each and every smallest individual unit in a C program is known
as C tokens. C tokens are of six types. They are
Keywords (eg: int, while),
Identifiers (eg: main, total),
Constants (eg: 10, 20),
Strings (eg: “total”
C KEYWORDS
C keywords are the words that convey a special meaning to the c compiler. The
keywords cannot be used as variable names.
The list of C keywords is given below:
85 /* decimal */
0213 /* octal */
0x4B /* hexadecimal */
30 /* int */
Here the mantissa must be multiplied by 10^exponent for example 345.25E-4 is equal to
345.25*10-4 and 4.56E4 is equal to 4.56*104.
Single character constant:
A single alphabet, digit or any special symbol placed in single inverted commas is called a
single character constant.
1) ‘X’
2) `v`
3) “c”
4) ‘hello’
5) ‘5’
6) ‘=’
7) ‘\n’
Hide Answers
1) Valid
2) Invalid (Single inverted commas are directed towards right)
3) Invalid (Must not be placed in double inverted commas)
4) Invalid (Should have single character only)
5) Valid
6) Valid
7) Valid (\n is considered as single character )
2) It should be noted that character constants have numerical values known as
ASCII values, for example, the value of ‗A‘ is 65 which is its ASCII value.
ESCAPE CHARACTERS
3) C allows us to have certain non graphic characters in character constants. Non
graphic characters are those characters that cannot be typed directly from
keyboard, for example, tabs, carriage return, etc.
4) These non graphic characters can be represented by using escape sequences
represented by a backslash() followed by one or more characters.
5) NOTE: An escape sequence consumes only one byte of space as it represents a
single character.
6)
Escape Sequence Description
a Audible alert(bell)
b Backspace
f Form feed
n New line
r Carriage return
t Horizontal tab
v Vertical tab
\ Backslash
“ Double quotation mark
‘ Single quotation mark
? Question mark
Null
STRING CONSTANTS
7)
SPECIAL SYMBOLS
VARIABLES
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.
. Each variable in C has a specific type, which determines the size and layout of the
variable's memory;
the range of values that can be stored within that memory and the set of operations that
can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character
It must begin with either a letter or an underscore.
Upper and lowercase letters are distinct because C is case-sensitive.
Variable Definition in C
A variable definition tells the compiler where and how much storage to create for
the variable. A variable definition specifies a data type and contains a list of one or
more variables of that type as follows −
type variable_list;
Here, type must be a valid C data type including char, w_char, int, float, double,
bool, or any user-defined object; and variable_list may consist of one or more
identifier names separated by commas. Some valid declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; declares and defines the variables i, j, and k; which instruct
the compiler to create variables named i, j and k of type int.
For definition without an initializer: variables with static storage duration are implicitly
initialized with NULL (all bytes have the value 0); the initial value of all other variables are
undefined.
4 Logical operators
These operators are used to perform logical
operations on the given two variables.&&,||,not,!
( ?: )
ARITHMETIC OPERATORS IN C
C Arithmetic operators are used to perform mathematical calculations like addition,
subtraction, multiplication, division and modulus in C programs.
Arithmetic
[Link] Operators Operation Example
1 + Addition A+B
2 – Subtraction A-B
3 * multiplication A*B
4 / Division A/B
5 % Modulus A%B
int main()
add = a+b;
sub = a-b;
mul = a*b;
div = a/b;
mod = a%b;
printf("Addi
tion of a, b
is : %d\n",
add);
return 0;
}
Addition of a, b is : 60
Subtraction of a, b is : 20
Multiplication of a, b is : 800
Division of a, b is : 2
Modulus of a, b is : 0
ASSIGNMENT OPERATORS IN C
In C programs, values for the variables are assigned using assignment operators.
For example, if the value 10 is to be assigned for the variable sum, it can be assigned as
sum = 10;
Simple
assignment 10 is assigned
operator = sum = 10 to variable sum
This is same as
-= sum -= 10 sum = sum – 10
This is same as
/+ sum /= 10 sum = sum / 10
This is same as
sum %= sum = sum %
%= 10 10
This is same as
sum = sum &
&= sum&=10 10
Compound
assignment sum ^= This is same as
operators ^= 10 sum = sum ^ 10
/*Sum of first 10
natural numbers
*/
# include <stdio.h>
int main()
{
int total=0,i;
for(i=0;i<10;i++)
{
Total = 45
x is greater than
1 > x>y y
x is greater than
3 >= x >= y or equal to y
x is less than or
4 <= x <= y equal to y
5 == x == y x is equal to y
x is not equal to
6 != x != y y
In this program, relational operator (==) is used to compare 2 values whether they are
equalor not.
If both values are equal, output is displayed as values are equal. Else, output is displayed
as values are not equal.
Note: double equal sign (==) should be used to compare 2 values. We should not single
equal sign (=).
EXAMPLE PROGRAM FOR RELATIONAL OPERATORS IN C
/*Example of Relational operators */
#include<stdio.h>
int main()
{
int m=40,n=20;
if (m == n)
{
else
return 0;
}
Output:
m and n are not equal
LOGICAL OPERATORS IN C
These operators are used to perform logical operations on the given expressions.
There are 3 logical operators in C language. They are, logical AND (&&), logical OR (||) andlogical
NOT (!).
It returns true
when both
logical conditions
1 && AND (x>5)&&(y<5) are true
It returns true
when at-least
one of the
logical condition is
2 || OR (x>=10)||(y>=10) true
It reverses the
state of the
operand
((x>5) &&
(y<5))‖
If ((x>5)
&& (y<5))‖
is true,
logical NOT
logical operator
3 ! NOT !((x>5)&&(y<5)) makes it false
OUTPUT:
x x
& ^
x y x|y y y
0 0 0 0 0
0 1 1 0 1
1 0 1 0 1
1 1 1 1 0
Operator_symbol
Operator_name
& Bitwise_AND
| Bitwise OR
~ Bitwise_NOT
^ XOR
<< Left Shift
#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a&b);
printf("Output = %d", a|b);
return 0;
}
Output:8
Bitwise OR operator |
The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1. In
C Programming, bitwise OR operator is denoted by |.
Example 1
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Output = 29
Bitwise XOR (exclusive OR) operator ^
The result of bitwise XOR operator is 1 if the corresponding bits of two operands are
opposite. It is denoted by ^.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Output
Output = 21
Bitwise complement operator ~
Bitwise compliment operator is an unary operator (works on only one operand). It
changes 1 to 0 and 0 to 1. It is denoted by ~.
35 = 00100011 (In Binary)
2 's Complement
Two's complement is an operation on binary numbers. The 2's complement of a
number is equal to the 1’s complement of that number plus 1.
Output
Output = -36
Shift Operators in C programming
There are two shift operators in C programming:
Right shift operator shifts all bits towards right by certain number of specified bits. It is
denoted by >>.
212 = 11010100 (In binary)
212>>2 = 00110101 (In binary) [Right shift by two bits]
212>>7 = 00000001 (In binary)
212>>8 = 00000000
212>>0 = 11010100 (No Shift)
AND_opr value = 0
OR_opr value = 120
NOT_opr value = -41
XOR_opr value = 120
left_shift value = 80
right_shift value = 20
A=10;
A > 100 ? 0 : 1
In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if else
conditional statements.
int x=1, y ;
y = ( x ==3 ? 100 : 0 ) ;
EXAMPLE 2
#include <stdio.h>
int main()
{
int age; // variable declaration
printf("Enter your age");
scanf("%d",&age); // taking user input for age variable
(age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting")); // conditi
onal operator
return 0;
}
C – Increment/decrement Operator
Increment operators are used to increase the value of the variable by one and decrement
operators are used to decrease the value of the variable by one in C programs.
Syntax:
Increment operator: pre increment ++var_name ;
( or) post increment operator var_name++;
Decrement operator: – -var_name; (or) var_name – -;
Example:
Increment operator : ++ i ; i ++ ;
Decrement operator : – – i ; i – – ;
#include<stdio.h>
int main()
{
int i=1;
while(i<10)
{
printf("%d ",i);
i++;
}
}
Output:1 2 3 4 5 6 7 8 9
EXAMPLE PROGRAM FOR DECREMENT OPERATORS IN C
In this program, value of ―I is decremented one by one from 20 up to 11 using ―-i operator and output is
displayed as 20 19 18 17 16 15 14 13 12 11.
//Example for decrement operators
#include <stdio.h>
int main()
{
int i=20;
while(i>10)
{
printf("%d ",i); -20-19-18-17-16-15-14-13-12-11
i--;
}
Examples
a=5
b=++a; // b becomes 6
a=5
b=a++;
a=8;
b=a++; // b becomes 8
a=6;
b=--a; // b becomes 5
a=6;
b=a--; // b becomes 6
a=10;
b=a--;
//b value 10
A=30;
B=--A;
//B value is 29
1 Pre increment
++i Value of i is
incremented before
assigning it to variable
i.
Value of i is
incremented after
i++ assigning it to variable
2 Post–increment i.
Value of i is
decremented before
— –i assigning it to variable
3 Pre decrement i.
Value of i is
decremented after
i– — assigning it to variable
4 Post_decrement i.
SPECIAL OPERATORS
Below are some of special operators that C language offers.
Example : * a where, * is
2 * pointer to the variable a.
This gives the size of the
variable.
#include <stdio.h>
int main()
{
int *ptr , q;
q = 50;
/* address of q is assigned to ptr */
ptr = &q;
/* display q's value using ptr variable */
printf("%d", *ptr);
return 0;
}
OUTPUT:
50
#include <limits.h>
int main()
int a;
char b;
float c;
double d;
type:%d\n",sizeof(d));
return 0;
OUTPUT:
EXPRESSIONS
Expression:It is a combination of operands and operators.
Arithmetic expression in C is a combination of variables, constants and operators written in a proper
syntax.
Operator Associativity is used when two operators of same precedence appear in an
expression. Associativity can be either Left to Right or Right to Left.
100/10*10
=10*10=100
Operators precedence:
A=10
Operators precedence: The precedence of operators determines which operator is executed first if
there is more than one operator in an expression.
The highest precedence of operator is evaluated first than the lower precedence operator.
Note: C does not have any operator for exponentiation
Step 1: x = 9-4 + 3 * 2 – 1
Step 2: x = 9 – 4 + 6 – 1
Second Pass
Step 1: x = 5 + 6 – 1
Step 2: x = 11 – 1
Step 3: x = 10
In the first pass, the high priority operators are applied as they are encountered and in the
second pass, low priority operations are applied as they are [Link], we have an
arithmetic expression as:
For example : x = 9 – 12 / 3 + 3 *2 - 1
This expression is evaluated in two left to right passes as:
First Pass
For example,
x = 9 – 12 / (3 + 3) * (2 – 1)
When parentheses are present then the expression inside the parenthesis are evaluated first
fromleft to right. The expression is now evaluated in three passes as:
First Pass
Step 1: x = 9 – 12 / 6 * (2 – 1)
Step 2: x= 9 – 12 / 6 * 1
Second Pass
Step 1: x= 9 – 2 * 1
Step 2: x = 9 – 2
Third Pass
Step 3: x= 7
1. 5+2*4=13
2. (3+4)*2=14
3. 100+200/10-3*10=90
100+20-3*10
100+20-30
90
4.(10+20)*30
=30*30=900
4.A=5,b=6,c=4;
Res=--A*b- ++c;
4*6-5
24-5
19
5.--A*b-c++
=4*6-4
24-4=20
STORAGE CLASSES IN C
Every variable in C programming has two properties: type and storage class.
Type refers to the data type of a variable. And, storage class determines the
scope, visibility and lifetime of a variable.
• The variable scope.
• The location where the variable will be stored.
• The initialized value of a variable.
• A lifetime of a variable.
#include <stdio.h>
int main()
{
auto int a;
a=10;
printf("%d", a);
return 0;
}
Output: 10
Storage Memory
Variables that are declared outside of all functions are known as external or global
variables.
void display()
{
++n;
printf("n = %d", n);
}
Output
n=7
Storage Memory
static int i;
The value of a static variable persists until the end of the program.
The static storage class instructs the compiler to keep a local variable in existence during the
life-time of the program instead of creating and destroying it each time it comes into and goes
out of scope.
int main()
{
int num1,num2; //local
register int sum;
return(0);
}
Explanation of
program
Refer below animation which depicts the register storage classes –
In the above program we have declared two variables num1,num2. These two variables are
stored in RAM.
Another variable is declared which is stored in register variable. The only difference is that
the variables declared using register storage class are stored inside CPU registers
instead of a memory. Register has faster access than that of the main memory.
Here, the value of a has been promoted from int to double and we have not had to
specify any type-casting operator. This is known as a standard conversion.
int main()
{
double x = 1.2;
int sum;
// Explicit conversion from double to int
sum = (int)x + 1;
return 0;
}
Output:
sum = 2
C Input Output (I/O) or formatting i/o or introduction to stdin,stdout,stderror
C Output function
In C programming, printf() is one of the main output function.
It is used to display output on the [Link] function sends formatted output to the screen
based on format specification.
The format specification string, along with the data to be output, are the parameters to the
printf() function.
Syntax:printf (format, var1, var2,… );
printf(“%d”,x);
output :10
int x=10,y=20;
printf(“%d%d”,x,y);//10,20
printf(“x,y”);x,y
x=10.00;
//x value is= 10
printf(“x value is=%f”,x);
x value is =10.000000.
Conversion Meaning
Character
d The data is converted to decimal (integer)
c The data is taken as a character.
s The data is a string and character from the string , are printed until a NULL,
character is reached.
f The data is output as float or double with a default Precision 6.
Symbols Meaning
\n For new line (linefeed return)
\t For tab space (equivalent of 8 spaces)
#include <stdio.h>
int main()
{
char chr = 'a';
// Displays the string inside quotations
printf("C Programming");
int testInteger = 5;
float number1 = 13.5;
double number2 = 12.4;
To left-justify integer output with printf, just add a minus sign (-) after
the % symbol, like this:
printf("%-3d", 0); 0
printf("%-3d", 123456789); 123456789
scanf() function to take input from the user and printf() function to display
output to the user.
Syntax:scanf(“format”,&var1,&var2……);
Int x;
scanf(“%d”,&x);
Int x,y;
Scanf(“%d%d”,&x,&y);
float z;
scanf(“%d%f”,&x,&z);
Int main()
{
Int x;
Printf(“enter x value”);
Scanf(“%d”,&x);
Printf(“enter y value”);
Scanf(“%d”,&y);
Printf(“total=%d”,(x+y));
}
Enter x value
10
Enter y value
20
Total=30
X 2001
y 3001
#include <stdio.h>
int main() {
int c;
return 0;
}
The getchar() and putchar() Functions
The int getchar(void) function reads the next available character from the standard
input and returns it as an integer. This function reads only single character at a time.
the int putchar(int c) function :is used to write a character to standard output
device.
the passed character on the screen and returns the same character. This
function puts only single character at a time.
getch():
getch() is a nonstandard function and is present in conio.h header
file which is mostly used by MS-DOS compilers like Turbo C.
not part of the C standard library or ISO C-Like above functions, it
reads also a single character from keyboard. But it does not use
any buffer, so the entered character is immediately returned
without waiting for the enter key.
#include <stdio.h>
int main( ) {
int c;
printf( "Enter a value :");
c = getchar( );
return 0;
}
Enter a value : hello
You entered: h
The Standard Files in c
C programming treats all the devices as files.
C standard files can be categorised as
1. Standard input
2. Standard output
3. Standard error
The file pointers are the means to access the file for reading and writing purpose.
#include <stdio.h>
int main( ) {
char str[100];
return 0;
}
When the above code is compiled and executed, it waits for you to input some text.
When you enter a text and press enter, then the program proceeds and reads the
complete line till end, and displays it as follows −
Enter a value : this is test
You entered: this is test
statement that is used to control the flow of execution in a program is called control structure
[Link] STATEMENTS:
A selection statement selects among a set of statements depending on the value of a
controlling expression.
The if-else statement in C is used to perform the operations based on some
specific condition. The operations specified in if block are executed if and only if
the given condition is true.
o If statement
o If-else statement
o If else-if ladder
o Nested if
Syntax :
if
(
e
x
p
r
e
s
s
i
o
n
)
s
t
a
t
e
m
e
n
t
1
;
E
x
p
l
a
n
a
ti
o
n
:
• Expression is Boolean Expression
• It may have true or false value
Output
if(expression)
{
//code to be executed if condition is true
}
Else
{
//code to be executed if condition is false
}
/* program to check whether the given number is odd or even */
#include<stdio.h>
int main(){
int number=0;
printf("enter a number:");
scanf("%d",&number);
if(number%2==0)
{
printf("%d is even number",number);
}
else{ 5/2=1
printf("%d is odd number",number);
}
return 0;
}
Output
enter a number:4
4 is even number
enter a number:5
5 is odd number
//Program to check whether a person is eligible to vote or not.
#include <stdio.h>
int main()
{
int age;
printf("Enter your age?");
scanf("%d",&age);
if(age>=18)
{
printf("You are eligible to vote...");
}
else
{
printf("Sorry ... you can't vote");
}
}
Output
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
...
else{
//code to be executed if all the conditions are false
}
Output
#include<stdio.h>
int main()
{
int num=1;
if(num<10)
{
if(num==1)
{
printf("The value is:%d\n",num);
}
else
{
printf("The value is greater than 1");
}
}
else
{
printf("The value is greater than 10");
}
return 0;
}
Output:
The value is:1
The switch statement is a multiway branch [Link] is an alternative to if
statement.
The switch statement allows us to execute one code block among many
alternatives.
A switch statement allows a variable to be tested for equality against a list of values.
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
default: If switch expression does not match with any case, default statements are
executed by the program.
/* uses the weekday number to calculate the weekday name:*/
simple Calculator
/* Program to create a simple calculator*/
#include <stdio.h>
int main() {
char operator;
double n1, n2;
switch(operator)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);
break;
return 0;
}
Output
Enter an operator (+, -, *,): -
Enter two operands: 32.5
12.4
32.5 - 12.4 = 20.1
LOOP CONTROL STATEMENTS
In programming, loops are used to repeat a block of code until a specified
condition is met.
C programming has three types of loops.
[Link] loop
[Link] loop
[Link]...while loop
While statement:
The syntax of the while loop is:
while (testExpression)
{
// the body of the loop
}
If the test expression is true, statements inside the body of while loop are
executed. Then, the test expression is evaluated again.
The process goes on until the test expression is evaluated to false.
If the test expression is false, the loop terminates (ends).
While loop is also called as entry controlled loop.
#include <stdio.h>
int main()
{
int i = 1;
while (i <= 5)
{
printf("%d\n", i);
++i;
}
return 0;
}
Output
1
2
3
4
5
Do...while loop
It is also called as exit controlled loop.
The do..while loop is similar to the while loop with one important difference.
The body of do...while loop is executed at least once. Only then, the test
expression is evaluated.
The syntax of the do...while loop is:
do
{
// the body of the loop
}
while (testExpression);
• If the test expression is true, the body of the loop is executed again
and the test expression is evaluated.
1. #include<stdio.h>
2. int main(){
3. int i=1;
4. do
5. {
6. printf("%d \n",i);
7. i++;
8. }while(i<=10);
9.
10. return 0;
11. }
Output
1
2
3
4
5
6
7
8
9
10
for Loop
The syntax of the for loop is:
for (initializationStatement; testExpression; updateStatement)
{
// statements inside the body of loop
}
int main() {
int i;
return 0;
}
Output
1 2 3 4 5 6 7 8 9 10
the goto statement is a jump statement which jumps from one point to another point
within a function.
goto label;
----------
----------
label:
----------
----------
In the above syntax, label is an identifier. When, the control of program reaches to goto statement,
the control of the program will jump to the label: and executes the code after it.
The goto statement allows us to transfer control of the program to the specified label.
void main()
{
printf("\nStatement 1.");
printf("\nStatement 2.");
printf("\nStatement 3.");
goto last;
// printf("\nStatement 4.");
printf("\nStatement 5.");
last:
printf("\nStatement 5");
//printf("\nEnd of Program.");
}
Output :
Statement 1.
Statement 2.
Statement 3.
End of Program.
Break Statement
The break statement is used inside loop or switch statement.
#include<stdio.h>
void main()
{
int a=1;
while(a<=10)
{
if(a==5)
break;
printf("\nStatement %d.",a);
a++;
}
printf("\nEnd of Program.");
}
Output :
Statement 1.
Statement 2.
Statement 3.
Statement 4.
End of Program.
CONTINUE STATEMENT :The continue statement skips the current
iteration of the loop and continues with the next iteration.
Example of continue statement
Continue statement:
loop
{
continue;
//code
}
/*continue statement */
#include<stdio.h>
void main()
{
int a=0;
while(a<=10)
{
a++;
if(a==5)
continue;
printf("\nStatement %d.",a);
}
printf("\nEnd of Program.");
}
Output :
Statement 1.
Statement 2.
Statemnent 3.
Statement 4.
Statement 6.
Statement 7.
Statement 8.
Statement 9.
Statement 10.
End of Program.
#include <stdio.h>
int main()
{
int n, i;
getch();
}
Output:enter a number 5 5*1=5 --5*2=10----5*3=15------5*10=50
Output:
Fact=1;number=5
for(i=1;i<=number;i++){ 1<=5
fact=fact*i;
fact=1*1
Fact=fact* i
1*1=1
Fact=1
1*2=2
Fact=2
2*3=6
Fact=6
6*4=24
Fact=24
24*5=120
#include <stdio.h>
int main()
{
int var1, var2, temp;
printf("Enter two integersn");
scanf("%d%d", &var1, &var2);
printf("Before SwappingnFirst variable = %dnSecond variable = %dn", var1, var2);
temp = var1;
var1 = var2;
var2 = temp;
printf("After SwappingnFirst variable = %dnSecond variable = %dn", var1, var2);
return 0;
}
Output:
/*simple c example to print "hello world" using if statement and without using semicolon.*/
#include<stdio.h>
int main()
{
if(printf("hello world")) { }
return 0;
}
Output:
hello world
the program find the sum of odd numbers from 1 to N numbers using for loop.
#include<stdio.h>
int main()
{
int n, sum=0;
return 0;
}
Enter n value: 10
Sum of odd numbers from 1 to 10 is: 25
Enter n value: 20
Sum of odd numbers from 1 to 20 is: 100