Presentation is about Traditional Two Pass Compiler architecture done by 4th year Computer Science and Technology(special) undergraduates at Uva Wellassa University, Sri Lanka
Presentation is about Traditional Two Pass Compiler architecture done by 4th year Computer Science and Technology(special) undergraduates at Uva Wellassa University, Sri Lanka
In order to communicate with the computer user also needs to have a language that should be understood by the computer. for this purpose, different languages are developed for performing different types of work on the computer. C is a general-purpose high level language that was originally developed by Dennis Ritchie for the Unix operating system.
Introduction to Computer.
Program and Programming.
Languages.
Types of Programming Languages.
Low-Level Languages.
Assembly languages.
High-Level Languages.
History of Programming.
Languages.
Translators.
Compiler.
Interpreter.
Typical C Program Development.
Environment
The C Programming Language
Characteristics of C language
durk computer,computer clan,jim's computer,chama computer,computer gk for,tiktok computer,gaming computer,kvs computer science full syllabus,chama computers,lil durk computer,trucchi computer,bhuture computer,computer science,patwari computer,computer security,computer for uppcl,
computer business basic computer
Characteristics of C language
Basic Program Structure in C
Language
Full description about the c programming language . It will helpful to learn the c language easily with this notes and it will helpful in the building of coding and to get jobs in required companies
Saudi Arabia stands as a titan in the global energy landscape, renowned for its abundant oil and gas resources. It's the largest exporter of petroleum and holds some of the world's most significant reserves. Let's delve into the top 10 oil and gas projects shaping Saudi Arabia's energy future in 2024.
Immunizing Image Classifiers Against Localized Adversary Attacksgerogepatton
This paper addresses the vulnerability of deep learning models, particularly convolutional neural networks
(CNN)s, to adversarial attacks and presents a proactive training technique designed to counter them. We
introduce a novel volumization algorithm, which transforms 2D images into 3D volumetric representations.
When combined with 3D convolution and deep curriculum learning optimization (CLO), itsignificantly improves
the immunity of models against localized universal attacks by up to 40%. We evaluate our proposed approach
using contemporary CNN architectures and the modified Canadian Institute for Advanced Research (CIFAR-10
and CIFAR-100) and ImageNet Large Scale Visual Recognition Challenge (ILSVRC12) datasets, showcasing
accuracy improvements over previous techniques. The results indicate that the combination of the volumetric
input and curriculum learning holds significant promise for mitigating adversarial attacks without necessitating
adversary training.
Final project report on grocery store management system..pdfKamal Acharya
In today’s fast-changing business environment, it’s extremely important to be able to respond to client needs in the most effective and timely manner. If your customers wish to see your business online and have instant access to your products or services.
Online Grocery Store is an e-commerce website, which retails various grocery products. This project allows viewing various products available enables registered users to purchase desired products instantly using Paytm, UPI payment processor (Instant Pay) and also can place order by using Cash on Delivery (Pay Later) option. This project provides an easy access to Administrators and Managers to view orders placed using Pay Later and Instant Pay options.
In order to develop an e-commerce website, a number of Technologies must be studied and understood. These include multi-tiered architecture, server and client-side scripting techniques, implementation technologies, programming language (such as PHP, HTML, CSS, JavaScript) and MySQL relational databases. This is a project with the objective to develop a basic website where a consumer is provided with a shopping cart website and also to know about the technologies used to develop such a website.
This document will discuss each of the underlying technologies to create and implement an e- commerce website.
Cosmetic shop management system project report.pdfKamal Acharya
Buying new cosmetic products is difficult. It can even be scary for those who have sensitive skin and are prone to skin trouble. The information needed to alleviate this problem is on the back of each product, but it's thought to interpret those ingredient lists unless you have a background in chemistry.
Instead of buying and hoping for the best, we can use data science to help us predict which products may be good fits for us. It includes various function programs to do the above mentioned tasks.
Data file handling has been effectively used in the program.
The automated cosmetic shop management system should deal with the automation of general workflow and administration process of the shop. The main processes of the system focus on customer's request where the system is able to search the most appropriate products and deliver it to the customers. It should help the employees to quickly identify the list of cosmetic product that have reached the minimum quantity and also keep a track of expired date for each cosmetic product. It should help the employees to find the rack number in which the product is placed.It is also Faster and more efficient way.
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)MdTanvirMahtab2
This presentation is about the working procedure of Shahjalal Fertilizer Company Limited (SFCL). A Govt. owned Company of Bangladesh Chemical Industries Corporation under Ministry of Industries.
Water scarcity is the lack of fresh water resources to meet the standard water demand. There are two type of water scarcity. One is physical. The other is economic water scarcity.
Welcome to WIPAC Monthly the magazine brought to you by the LinkedIn Group Water Industry Process Automation & Control.
In this month's edition, along with this month's industry news to celebrate the 13 years since the group was created we have articles including
A case study of the used of Advanced Process Control at the Wastewater Treatment works at Lleida in Spain
A look back on an article on smart wastewater networks in order to see how the industry has measured up in the interim around the adoption of Digital Transformation in the Water Industry.
2. Overview of C language
Developed at Bell Laboratories in the early seventies by Dennis Ritchie.
Born out of two other languages – BCPL (Basic Control Programming
Language) and B.
C introduced such things as character types, floating point arithmetic, structures,
unions and the preprocessor.
The principal objective was to devise a language that was easy enough to
understand to be "high-level" – i.e. understood by general programmers, but low-
level enough to be applicable to the writing of systems-level software.
3. Cont…
The language should abstract the details of how the computer achieves its tasks in such a way as
to ensure that C could be portable across different types of computers, thus allowing the UNIX
operating system to be compiled on other computers with a minimum of re-writing.
C as a language was in use by 1973, although extra functionality, such as new types, was
introduced up until 1980.
In 1978, Brian Kernighan and Dennis M. Ritchie wrote the seminal work The C Programming
Language, which is now the standard reference book for C.
A formal ANSI standard for C was produced in 1989.
4. Cont…
In 1986, a descendant of C, called C++ was developed by Bjarne Stroustrup, which is in wide
use today. Many modern languages such as C#, Java and Perl are based on C and C++.
Using C language scientific, business and system-level applications can be developed easily.
5. Program
There is a close analogy between learning English language and learning C language.
The classical method of learning English is to first learn the alphabets used in the language, then
learn to combine these alphabets to form words, which in turn are combined to form sentences
and sentences are combined to form paragraphs.
Learning C is similar and easier.
Instead of straight-away learning how to write programs, we must first know what alphabets,
numbers and special symbols are used in C, then how using them constants, variables and
keywords are constructed, and finally how are these combined to form an instruction.
7. Types of
Languages
Low level languages are machine level and assembly level language.
In machine level language computer only understand digital numbers
i.e. in the form of 0 and 1. So, instruction given to the computer is in
the form binary digit, which is difficult to implement instruction in
binary code. This type of program is not portable, difficult to maintain
and also error prone.
The assembly language is on other hand modified version of machine
level language. Where instructions are given in English like word as
ADD, SUM, MOV etc.
It is easy to write and understand but not understand by the machine.
So the translator used here is assembler to translate into machine level.
Although language is bit easier, programmer has to know low level
details related to low level language.
In the assembly level language the data are stored in the computer
register, which varies for different computer. Hence it is not portable.
Low level language
8. Types of
Languages
These languages are machine independent, means it is
portable.
The language in this category is Pascal, COBOL, Fortran etc.
High level languages are understood by the machine.
So it needs to translate by the translator into machine level.
A translator is software which is used to translate high level
language as well as low level language in to machine level
language.
High level language
10. Compiler
A compiler is a translator used to convert high level language to low level language.
It converts the whole program in one session and reports errors detected after the conversion.
The compiler takes time to do its work as it translates high-level code to lower-level code all at once
and then saves it to memory.
A compiler is processor-dependent and platform-dependent.
It has been addressed by alternate names as the following: special compiler, cross-compiler and,
source-to-source compiler.
11. Interpreter
The interpreter is similar to a compiler, it is a translator used to convert high-level programming
language to low-level programming language.
The difference is that it converts the program one line of code at a time and reports errors when
detected, while also doing the conversion.
An interpreter is faster than a compiler as it immediately executes the code upon reading the code.
It is often used as a debugging tool for software development as it can execute a single line of code at
a time.
An interpreter is also more portable than a compiler as it is processor-independent, you can work
between different hardware architectures.
12. Assembler
An assembler is a translator used to translate assembly language into machine language.
It has the same function as a compiler for the assembly language but works like an interpreter.
Assembly language is difficult to understand as it is a low-level programming language.
An assembler translates a low-level language, such as an assembly language to an even lower-level
language, such as the machine code.
13. Characteristics of C
We briefly list some of C's characteristics that define the language and also have lead to its popularity as a
programming language. Naturally we will be studying many of these aspects throughout the course.
• Small size
• Extensive use of function calls
• Loose typing
• Structured language
• Low level (Bitwise) programming readily available
• Pointer implementation - extensive use of pointers for memory, array, structures and functions.
14. Cont…
C has now become a widely used professional language for various reasons.
• It has high-level constructs.
• It can handle low-level activities.
• It produces efficient programs.
• It can be compiled on a wide variety of computers.
15. Compiling &
Executing C
Program
Step 1: The program that is to be compiled is first typed
into a file on the computer system.
There are various conventions that are used for naming
files, typically be any name provided the last two characters
are “.c” or file with extension .c.
Step 2: After the source program has been entered into a
file, then proceed to have it compiled.
The compilation process is initiated by typing a special
command on the system.
When this command is entered, the name of the file that
contains the source program must also be specified.
For example, under Unix, the command to initiate program
compilation is called cc. If we are using the popular GNU C
compiler, the command we use is gcc.
A compiler is a software
program that analyzes a
program developed in a
particular computer language
and then translates it into a
form that is suitable for
execution on a particular
computer system.
16. Cont…
Step 3: When all the syntactic and semantic errors have
been removed from the program, the compiler then
proceeds to take each statement of the program and translate
it into a “lower” form that is equivalent to assembly
language program needed to perform the identical task.
Step 4: After the program has been translated the next step
in the compilation process is to translate the assembly
language statements into actual machine instructions.
The assembler takes each assembly language statement and
converts it into a binary format known as object code,
which is then written into another file on the system.
This file has the same name as the source file under Unix,
with the last letter an “o” (for object) instead of a “c”.
17. Cont…
Step 5: After the program has been translated into object
code, it is ready to be linked.
This process is once again performed automatically
whenever the cc or gcc command is issued under Unix.
The purpose of the linking phase is to get the program into a
final form for execution on the computer.
Step 6: To subsequently execute the program, the command
a.out has the effect of loading the program called a.out into
the computer‟s memory and initiating its execution.
19. C character
Set
Letters
Uppercase characters (A-Z)
Lowercase characters (a-z)
Numbers
All the digits from 0 to 9
White spaces
Blank space
New line
Carriage return
Horizontal tab
A character denotes any
alphabet, digit or special
symbol used to represent
information.
Valid alphabets, numbers
and special symbols allowed in
C are
Letters
Numbers
White spaces
Special Characters
21. C Tokens
TOKEN is the smallest unit in a 'C'
program. It is each and every word and
punctuation that you come across in
your C program. The compiler breaks a
program into the smallest possible units
(tokens) and proceeds to the various
stages of the compilation. A token is
divided into six different types, such as
Keywords, Operators, Strings,
Constants, Special Characters, and
Identifiers.
22. 32 Keywords
Flow control (6) – if, else, return, switch, case, default
Loops (5) – for, do, while, break, continue
Common types (5) – int, float, double, char, void
For dealing with structures (3) – struct, typedef, union
Counting and sizing things (2) – enum, sizeof
Rare but still useful types (7) – extern, signed, unsigned, long, short, static, const
Keywords that is undiscouraged and which we NEVER use (1) – goto
We don't use unless we're doing something strange (3) – auto, register, volatile
23. Identifiers
Rules for naming identifiers are:
1) name should only consists of alphabets (both upper and
lower case), digits and underscore (_) sign.
2) first characters should be alphabet or underscore
3) name should not be a keyword
4) since C is a case sensitive, the upper case and lower case
considered differently, for example code, Code, CODE etc.
are different identifiers.
5) identifiers are generally given in some meaningful name
such as value, net_salary, age, data etc.
6) It should not contain any whitespace character.
Identifiers are user defined word
used to name of entities like
variables, arrays, functions,
structures etc.
24. Constants
Constant is a any value that
cannot be changed during program
execution.
In C, any number, single
character, or character string is
known as a constant.
A constant is an entity that
doesn‟t change whereas a variable
is an entity that may change.
25. Operators
This is a symbol use to perform some operation on variables, operands or with the constant.
Some operator required 2 operand to perform operation or some required single operation.
Several operators are there those are, arithmetic operator, assignment, increment, decrement, logical,
conditional, comma, size of , bitwise and others.
27. Strings
In C programming, a string is a sequence of characters terminated with a null character 0. For
example:
char c[] = "c string";
When the compiler encounters a sequence of characters enclosed in the double quotation marks, it
appends a null character 0 at the end by default.
28. Simple C
program
structure
1 ) Comment line
2) Preprocessor directive
3 ) Global variable declaration
4) main function( )
{
Local variables;
Statements;
}
User defined function
}
}
29. Comments
It indicates the purpose of the program. It is represented as
/*……………………………..*/
Comment line is used for increasing the readability of the
program.
It is useful in explaining the program and generally used for
documentation.
It is enclosed within the decimeters.
Comment line can be single or multiple line but should not
be nested.
It can be anywhere in the program except inside string
constant & character constant.
30. Preprocessor
directive
#include tells the compiler to include information about the
standard input/output library.
It is also used in symbolic constant such as #define PI
3.14(value).
The stdio.h (standard input output header file) contains
definition &declaration of system defined function such as
printf( ), scanf( ), pow( ) etc.
Generally printf() function used to display and scanf()
function used to read value
31. Global
declaration
This is the section where variable are declared globally so
that it can be access by all the functions used in the
program.
And it is generally declared outside the function
32. main()
Syntax
main()
{
……..
……..
……..
}
It is the user defined function and
every function has one main()
function from where actually
program is started and it is encloses
within the pair of curly braces.
The main( ) function can be
anywhere in the program but in
general practice it is placed in the
first position.
33. /*First c program
with return
statement*/
#include <stdio.h>
int main (void)
{
printf ("welcome to c Programming language.n");
return 0;
}
Output: welcome to c programming language
34. Constants
C Constants is the most fundamental and essential part of the C programming language. Constants in C
are the fixed values that are used in a program, and its value remains the same during the entire
execution of the program.
Constants are also called literals.
Constants can be any of the data types. const keyword defines a constant in C.
It is considered best practice to define constants using only upper-case names.
Syntax
const type constant_name;
35. Example
#include<stdio.h>
main()
{
const int SIDE = 10;
int area;
area = SIDE*SIDE;
printf("The area of the square with side: %d is: %d sq. units", SIDE, area);
}
Output: The area of the square with side: 10 is: 100 sq. units
36. Types of Constants
Constants are categorized into two basic types, and each of these types has its subtypes/categories. These are:
Primary Constants
1. Numeric Constants
Integer Constants
Real Constants
2. Character Constants
Single Character Constants
String Constants
Backslash Character Constants
37. Integer
Constants
An integer constant must have at least one digit.
It must not have a decimal point.
It can either be positive or negative.
No commas or blanks are allowed within an integer
constant.
If no sign precedes an integer constant, it is assumed to be
positive.
The allowable range for integer constants is -32768 to
32767.
Example: 0 , -33, 32767
There are three types of integer
constants namely,
a) Decimal integer
b) Octal integer constant
c) Hexadecimal integer
38. Decimal Integer constant (base
10)
•It consists of any combinations of digits taken from the set 0 through 9, preceded by an optional – or +
sign.
•The first digit must be other than 0.
Embedded spaces, commas, and non-digit characters are not permitted between digits.
Valid: 0 32767 -9999 -23
Invalid:
12,245 - Illegal character (,)
10 20 30 - Illegal character (blank space)
39. Octal Integer Constant (base 8)
It consists of any combinations of digits taken from the set 0 through 7.
If a constant contains two or more digits, the first digit must be 0.
In programming, octal numbers are used.
Valid: 037 0 0435
Invalid:
0786 - Illegal digit 8
123 - Does not begin with zero
01.2 - Illegal character (.)
40. Hexadecimal Integer Constant
(base 16)
It consists of any combinations of digits taken from the set 0 through 7 andalso a through f
(either uppercase or lowercase).
The letters a through f (or A through F) represent the decimal quantities 10 through 15 respectively.
This constant must begin with either 0x or 0X.
In programming, hexadecimal numbers are used.
Valid Hexadecimal Integer Constant: 0x 0X1 0x7F Invalid Hexadecimal
Integer Constant: 0xefg - Illegal character g
123 - Does not begin with 0x
41. Real Constants
(Fractional
form)
The numbers containing fractional parts like 99.25 are
called real or floating points constant.
Here are the rules for creating floating point constants in
Fractional form:
1. Must have one at least one digit
2. Must have a decimal point
3. Can be positive or negative, the default is positive
4. No comma, blanks, or any other symbols are allowed
Here are some examples: 3.14, 899.0, -0.999
42. Real Constants
(Exponential
form)
Exponential form is used in cases when a number is too small or too
large. For example, 0.00000941 can be represented as 9.41e-6. The part
of the number before e is called mantissa i.e 9.41, whereas, the part
following e is called the exponent i.e -6.
Here are the rules for creating floating point constants in Exponential
form:
1. Mantissa and exponent must be separated by e or E.
2. Mantissa can be positive or negative, default is positive.
3. Exponent must have at least one digit.
4. The exponent can be positive or negative default is positive
Some examples of floating point numbers in exponential form are:
100.34e4, -56E10, 0.233E10, -0.94e15
By default, floating constants are of type double. We can explicitly
mention the type of a floating-point constant as a float by
appending f or F at the end of the constant.
For example: 12f, -0.87f
43. Character Constant
1. A character constant is a single alphabet, a single digit or a single special symbol enclosed within
single quotes.
2. The maximum length of a character constant is 1 character.
3. String constants are enclosed within double quotes.
44. Single character constant
It simply contains a single character enclosed within ' and ' (a pair of single quote). It is to be noted that
the character '8' is not the same as 8. Character constants have a specific set of integer values known as
ASCII values (American Standard Code for Information Interchange).
Example:
'X', '5', ';'
The maximum length of a character constant is 1 character long. That means you cannot put more than
one character inside single quotation marks like this
'ab' // Wrong
'12' // Wrong
45. String constant
String constants consist of zero or more characters enclosed in double quotes (""). At the end of the
string, the null character i.e '0' is automatically placed by the compiler. Here are some examples of
string constants:
"hello"
"123"
"" // This is empty string
Although not officially part of Primary constants, string constants are given here for the sake of
completeness. C has no data type for string, they are stored as an array of characters. We will learn
more about strings in a great deal in its own chapter
46. Backslash
character
constant
There are some characters which
have special meaning in C
language.
They should be preceded by
backslash symbol to make use of
special function of them.
Given below is the list of special
characters and their purpose.
47. Symbolic
Constant
It is generally defined at the beginning of the program. Here is
the syntax of creating a Symbolic constant.
#define NAME VALUE
#define is a preprocessor directive just like #include, that's why
it doesn't end with the semicolon (;).
NAME indicates the name we want to give to our constant and
is generally written in uppercase.
VALUE can be numeric, character or string constant. Let's
create a symbolic constant called PI.
#define PI 3.141592
If we want to use constant several
times in a program, then we can
provide it a name. For example: If
there is a need to use constant Π =
3.141592 at several places in the
program, then we can give it a name
and use that name instead of writing
this long number. This constant is
called Symbolic constant.
48. Example 1
#include <stdio.h>
void main()
{
const int height = 100; /*int constant*/
const float number = 3.14; /*Real constant*/
const char letter = 'A'; /*char constant*/
const char letter_sequence[10] = "ABC"; /*string constant*/
const char backslash_char = '?'; /*special char cnst*/
printf("value of height :%d n", height );
printf("value of number : %f n", number );
printf("value of letter : %c n", letter );
printf("value of letter_sequence : %s n", letter_sequence);
printf("value of backslash_char : %c n", backslash_char);
}
49. Example 2
#include<stdio.h>
main()
{
const int SIDE = 10;
int area;
area = SIDE*SIDE;
printf("The area of the square with side: %d is: %d sq.
units" , SIDE, area);
}
Output: The area of the square
with side: 10 is: 100 sq. units
50. Variables
A variable is a value that can change.
A symbol or name that stands for a value.
Variables provide temporary storage for information that will
be needed during the lifespan of the computer program (or
application).
Variables store everything in your program.
• The purpose of any useful program is to modify variables.
• In a program every, variable has:
– Name (Identifier)
– Data Type
– Size
– Value
A variable is nothing but a name
given to a storage area that our
programs can manipulate.
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.
51. 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.
Based on the basic types explained
in the previous chapter, there will
be the following basic variable
types –
52. Variables
definition
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.
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;
53. Variable
initialization
Some examples are −
extern int d = 3, f = 5; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
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.
Variables can be initialized
(assigned an initial value) in their
declaration. The initializer consists
of an equal sign followed by a
constant expression as follows −
type variable_name = value;
54. Example
#include <stdio.h>
extern int a, b;
extern int c;
extern float f;
int main () {
int a, b;
int c;
float f;
a = 10;
b = 20;
c = a + b;
printf("value of c : %d n", c);
f = 70.0/3.0;
printf("value of f : %f n", f);
return 0;
}
Output
value of c : 30
value of f : 23.333334
56. Local variable
Advantages of using Local Variables
• The use of local variables offer a guarantee that the values of variables will
remain intact while the task is running
• If several tasks change a single variable that is running simultaneously, then the
result may be unpredictable. But declaring it as local variable solves this issue as
each task will create its own instance of the local variable.
• You can give local variables the same name in different functions because they
are only recognized by the function they are declared in.
• Local variables are deleted as soon as any function is over and release the
memory space which it occupies.
Disadvantages of using Local Variables
• The debugging process of a local variable is quite tricky.
• Common data required to pass repeatedly as data sharing is not possible between
modules.
• They have a very limited scope.
Local variables are those that are in
scope within a specific part of the
program (function, procedure,
method, or subroutine, depending on
the programming language
employed).
The scope of local variables will be
within the function only.
These variables are declared within
the function and can‟t be accessed
outside the function.
57. Example 1
#include<stdio.h>
void test();
int main()
{
int m = 22, n = 44;
printf("nvalues : m = %d and n = %d", m, n);
test();
}
void test()
{
int a = 50, b = 80;
printf("nvalues : a = %d and b = %d", a, b);
}
58. Example 2
#include<stdio.h>
int main()
{
int a = 100;
{
int a = 10;
printf("Inner a = %dn", a);
}
printf("Outer a = %dn", a);
// signal to operating system everything works fine
return 0;
}
59. Global variable
Advantages of using Global variables
You can access the global variable from all the functions or modules in a program
You only require to declare global variable single time outside the modules.
It is ideally used for storing "constants" as it helps you keep the consistency.
A Global variable is useful when multiple functions are accessing the same data.
Disadvantages of using Global Variables
Too many variables declared as global, then they remain in the memory till
program execution is completed. This can cause of Out of Memory issue.
Data can be modified by any function. Any statement written in the program can
change the value of the global variable. This may give unpredictable results in
multi-tasking environments.
If global variables are discontinued due to code refactoring, you will need to
change all the modules where they are called.
Global variables are those that are in scope
for the duration of the programs execution.
They can be accessed by any part of the
program, and are readwrite for all
statements that access them.
The scope of global variables will be
throughout the program. These variables
can be accessed from anywhere in the
program.
This variable is defined outside the main
function. So that, this variable is visible to
main function and all other sub functions.
60. Example 1
#include<stdio.h>
void test();
int m = 22, n = 44;
int a = 50, b = 80;
int main()
{
printf("All variables are accessed from main function");
printf("nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b);
test();
}
void test()
{
printf("nnAll variables are accessed from" " test function");
printf("nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b);
}
63. Datatypes
Data types in c refer to an extensive system used for declaring variables or functions of different types.
The type of a variable determines how much space it occupies in storage and how the bit pattern stored
is interpreted.
A programming language is proposed to help programmer to process certain kinds of data and to
provide useful output.
The task of data processing is accomplished by executing series of commands called program.
A program usually contains different types of data types (integer, float, character etc.) and need to store
the values being used in the program. C language is rich of data types.
65. Integer types
Integer Data Types: Integers are whole numbers with a
range of values, range of values are machine dependent.
Generally an integer occupies 2 bytes memory space and its
value range limited to -32768 to +32767 (that is, -2 15 to
+215 -1).
A signed integer use one bit for storing sign and rest 15 bits
for number.
Syntax:
int <variable name>;
Example
int num1;
short int num2;
long int num3;
Example: 5, 6, 100, 2500.
68. Floating point
types
The float data type is used to store fractional numbers (real
numbers) with 6 digits of precision.
Floating point numbers are denoted by the keyword float.
When the accuracy of the floating point number is
insufficient, we can use the double to define the number.
The double is same as float but with longer precision and
takes double space (8 bytes) than float.
To extend the precision further we can use long double
which occupies 10 bytes of memory space.
Syntax:
float <variable name>;
Examples
float num1;
double num2;
long double num3;
Example: 9.125, 3.1254.
71. Void data type
The void type specifies that no
value is available.
It is used in three kinds of situations
72. Operators
C language is rich in built-in operators and provides the
following types of operators:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Sizeof() operators
7. Ternary operators
8. Special operators
9. Unary operators
An operator is a symbol that tells
the compiler to perform specific
mathematical or logical
manipulations.
73. Arithmetic
operators
The following table shows all the
arithmetic operators supported by
the C language. Assume
variable A holds 10 and
variable B holds 20 then
83. Sizeof()
It is a much used operator in the C. It is a compile time
unary operator which can be used to compute the size of its
operand.
The result of sizeof is of unsigned integral type which is
usually denoted by size_t.
sizeof can be applied to any data-type, including primitive
types such as integer and floating-point types, pointer types,
or compound datatypes such as Structure, union etc.
Usage
sizeof() operator is used in different way according to the
operand type.
86. Ternary operator
If any operator is used on three operands or variable is known as Ternary Operator. It can be represented with ? : . It is
also called as conditional operator
The ternary operator is an operator that takes three arguments. The first argument is a comparison argument, the second is
the result upon a true comparison, and the third is the result upon a false comparison. Ternary operator is shortened way
of writing an if-else statement.
Ternary operator is a?b:c it say that the condition a is true b will be executed else c will be executed.
Advantage of Ternary Operator
Using ?: reduce the number of line codes and improve the performance of application.
Syntax
expression-1 ? expression-2 : expression-3
89. Unary operator
◦ unary minus
The minus operator changes the sign of its argument. A
positive number becomes negative, and a negative number
becomes positive.
int a = 10;
int b = -a; // b = -10
unary minus is different from subtraction operator, as
subtraction requires two operands.
Unary operator: are operators that act upon a
single operand to produce a new value.
Types of unary operators:
unary minus(-)
increment(++)
decrement(- -)
NOT(!)
Addressof operator(&)
sizeof()
90. Increment
operator
prefix increment
In this method, the operator preceeds the operand (e.g.,
++a). The value of operand will be altered before it is
used.
int a = 1;
int b = ++a; // b = 2
postfix increment
In this method, the operator follows the operand (e.g.,
a++). The value operand will be altered after it is used.
int a = 1;
int b = a++; // b = 1
int c = a; // c = 2
It is used to increment the value of
the variable by 1. The increment
can be done in two ways:
91. Decrement
operator
prefix decrement
In this method, the operator preceeds the operand (e.g., – -
a). The value of operand will be altered before it is used.
int a = 1;
int b = --a; // b = 0
posfix decrement
In this method, the operator follows the operand (e.g., a- -).
The value of operand will be altered after it is used.
int a = 1;
int b = a--; // b = 1
int c = a; // c = 0
It is used to decrement the value of the
variable by 1. The decrement can be done in
two ways:
92. NOT and
address
operators
◦ NOT(!):
It is used to reverse the logical state of its operand. If a condition is true, then
Logical NOT operator will make it false.
If x is true, then !x is false
If x is false, then !x is true
◦ Addressof operator(&):
It gives an address of a variable. It is used to return the memory address of a
variable. These addresses returned by the address-of operator are known as
pointers because they “point” to the variable in memory.
& gives an address on variable n
int a;
int *ptr;
ptr = &a; // address of a is copied to the location ptr.
93. Expressions
Expressions are the fundamental means of specifying
computations in a programming language
–To understand the expression evaluation, it is necessary to
be familiar with the orders of operator and operand
evaluation
– The essence of the imperative programming languages is
the dominant role of assignment statements
An expression is a combination of variables constants and
operators written according to the syntax of C language. In
C every expression evaluates to a value i.e., every
expression results in some value of a certain type that can be
assigned to a variable.
Evaluation of Expressions
Precedence in Arithmetic Operators
Type conversions in expressions
Order
Category
Operator
Associativity
94. Evaluation of
expressions
Expressions are evaluated using an assignment statement of
the form
Variable = expression;
Variable is any valid C variable name. When the statement
is encountered, the expression is evaluated first and then
replaces the previous value of the variable on the left hand
side. All variables used in the expression must be assigned
values before evaluation is attempted.
Example of evaluation statements are
x = a * b – c
y = b / c * a
z = a – b / c + d;
96. Precedence in
arithmetic
operators
Rules for evaluation of expression
• First parenthesized sub expression left to right are
evaluated.
• If parenthesis are nested, the evaluation begins with the
innermost sub expression.
• The precedence rule is applied in determining the order of
application of operators in evaluating sub expressions.
• The associability rule is applied when two or more
operators of the same precedence level appear in the sub
expression.
• Arithmetic expressions are evaluated from left to right
using the rules of precedence.
• When Parenthesis are used, the expressions within
parenthesis assume highest priority.
An arithmetic expression without
parenthesis will be evaluated from
left to right using the rules of
precedence of operators.
There are two distinct priority levels
of arithmetic operators in C.
High priority * / %
Low priority + -
97. Type
conversion in
expression
The following rules apply during evaluating expressions
All short and char are automatically converted to int then
1. If one operand is long double, the other will be converted to long double and
result will be long double.
2. If one operand is double, the other will be converted to double and result will
be double.
3. If one operand is float, the other will be converted to float and result will be
float.
4. If one of the operand is unsigned long int, the other will be converted into
unsigned long int and result will be unsigned long int.
5. If one operand is long int and other is unsigned int then a. If unsigned int can
be converted to long int, then unsigned int operand will be converted as such and
the result will be long int.
…..b. Else Both operands will be converted to unsigned long int and the result
will be unsigned long int.
6. If one of the operand is long int, the other will be converted to long int and the
result will be long int.
7. If one operand is unsigned int the other will be converted to unsigned int and
the result will be unsigned int.
Implicit type conversion
C permits mixing of constants and variables of different
types in an expression. C automatically converts any
intermediate values to the proper type so that the
expression can be evaluated without loosing any
significance.
This automatic type conversion is know as implicit type
conversion
During evaluation it adheres to very strict rules and type
conversion.
If the operands are of different types the lower type is
automatically converted to the higher type before the
operation proceeds. The result is of higher type.
100. Managing I/O operations
1. Standard Input (stdin)
Standard input or stdin is used for taking input from devices
such as the keyboard as a data stream.
1. Standard Output (stdout)
Standard output or stdout is used for giving output to a device
such as a monitor.
I/O operations are useful for a
program to interact with
users. stdlib is the standard C
library for input-output operations.
While dealing with input-output
operations in C, two important
streams play their role. These are:
101. Reading character in C
The easiest and simplest of all I/O
operations are taking a character as
input by reading that character from
standard input (keyboard).
getchar() function can be used to read
a single character.
This function is alternate
to scanf() function.
Syntax
var_name = getchar();
102. Writing character in C
Similar to getchar() there is another
function which is used to write
characters, but one at a time.
Syntax
putchar(var_name);
103. Reading and
Writing Strings
in C
The gets() function reads a string of
characters entered at the keyboard and
places them at the address pointed to by its
argument. We can type characters at the
keyboard until we strike a carriage return.
The carriage return does not become part of
the string; instead a null terminator is
placed at the end and gets() returns.
Typing mistakes can be corrected prior to
striking ENTER. The prototype for gets() is:
char* gets (char *str);
107. Example
#include<stdio.h>
int main()
{
char str1[100], str2[100];
printf("Enter two string: ");
gets(str1);
fgets(str2, sizeof(str2), stdin);
//Notice displaying order
printf("String 1: %s ",str1);
printf("String 2: %s",str2);
return 0;
}
Output:-
Enter two string: Know Program
C language
String 1: Know Program String 2: C
language
108. C - Formatted I/O Functions
C language provide us console
input/output functions. As the name
says, the console input/output functions
allow us to -
• Read the input from the
keyboard by the user accessing the
console.
• Display the output to the user
at the console.
Note : These input and output values
could be of any primitive data type.
110. Scanf()
It refers to an input data which has been arranged in a specific format. This is possible in C using
scanf().
Syntax:
scanf("control string", arg1, arg2, ..., argn);
111. Example
OUTPUT :
Enter any character
a
Entered character is a
Enter any string ( upto 100
character )
hai
Entered string is hai
112. Printf()
• 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.
• All output starts in the leftmost box, although some output might be "padded" with blank spaces to align it to the right edge of
the field. "X"'s indicated unused positions.
115. Decision Making
This deals with the various methods that C can control the flow of logic in a program. Control statements can be classified as un-
conditional and conditional branch statements and loop or iterative statements. The Branch type includes:
1. Un-conditional: goto, break, return, continue, exit
2. Conditional: if, if-else, nested if, switch case statement
3. Loop or iterative: for loop, while loop, do-while loop
116. Conditional Statement
Sometimes we want a program to select an action from two or more alternatives. This requires a
deviation from the basic sequential order of statement execution.
Such programs must contain two or more statements that might be executed, but have some way to
select only one of the listed options each time the program is run.
This is known as conditional execution.
117. if statement
Statement or set of statements can be
conditionally executed using if statement.
Here, logical condition is tested which, may
either true or false.
If the logical test is true (non zero value) the
statement that immediately follows if is
executed.
If the logical condition is false the control
transfers to the next executable statement.
119. if – else
statement
The general syntax of simple if - else statement is:
The if statement is used to execute
only one action.
If there are two statements to be
executed alternatively, then if-else
statement is used.
The if-else statement is a two way
branching.
120. Example
#include <stdio.h>
int main()
{
int age;
printf("Enter your age:");
scanf("%d",&age);
if(age >=18)
{
/* This statement will only execute if the
* above condition (age>=18) returns true
*/
printf("You are eligible for voting");
}
else
{
/* This statement will only execute if the
* condition specified in the "if" returns false.
*/
printf("You are not eligible for voting");
}
return 0;
}
Output
Enter your age:14
You are not eligible for voting
121. Nested if
statement
The ANSI standard specifies that
15 levels of nesting must be
supported.
In C, an else statement always
refers to the nearest if statement
in the same block and not already
associated with if.
122. Example
#include <stdio.h>
int main () {
/* local variable definition */
int a = 100;
int b = 200;
/* check the boolean condition */
if( a == 100 ) {
/* if condition is true then check the following */
if( b == 200 ) {
/* if condition is true then print the following */
printf("Value of a is 100 and b is 200n" );
}
}
Output
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
printf("Exact value of a is : %dn", a );
printf("Exact value of b is : %dn", b );
return 0;
}
123. if –else – if
ladder
When faced with a situation in which a
program must select from many processing
alternatives based on the value of a single
variable,
an analyst must expand his or her use of the
basic selection structure beyond the
standard two processing branches offered
by the if statement to allow for multiple
branches.
One solution to this is to use an approach
called nesting in which one (or both)
branch(es) of a selection contain another
selection.
124. Example
Output
Enter a Number: -5
Given Number is Negative
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
printf("Enter a Number: ");
scanf("%d",&a);
if(a > 0)
{
printf("Given Number is Positive");
}
else if(a == 0)
{
printf("Given Number is Zero");
}
else if(a < 0)
{
printf("Given Number is Negative");
}
getch();
}
125. The switch
case statement
The general
form of switch case statement is:
switch (expression)
{
case constant1:
statement;
break;
case constant2:
statement;
break;
default:
statement;
break;
}
The switch-case statement is used
when an expression’s value is to
be checked against several
values. If a match takes place, the
appropriate action is taken.
126. Three important
things to know
about switch
statement
1. The switch differs from the if in that
switch can only test for equality whereas
if can evaluate any type of relational or
logical expression.
2. No two case constants in the same
switch can have identical values. But, a
switch statement enclosed by an outer
switch may have case constants and
either same.
3. If character constants are used in the
switch statement, they are automatically
converted to integers.
127. Example
#include <stdio.h>
int main()
{
int num=2;
switch(num+2)
{
case 1:
printf("Case1: Value is: %d", num);
case 2:
printf("Case1: Value is: %d", num);
case 3:
printf("Case1: Value is: %d", num);
default:
printf("Default: Value is: %d", num);
}
return 0;
}
Output:
Default: value is: 2
128. Looping statement
Looping is a powerful programming technique through which a group of statements is
executed repeatedly, until certain specified condition is satisfied. Looping is also called
a repetition or iterative control mechanism.
Types of Loops in C
Depending upon the position of a control statement in a program, looping in C is
classified into two types:
1. Entry controlled loop
2. Exit controlled loop
In an entry controlled loop, a condition is checked before executing the body of a loop.
It is also called as a pre-checking loop. Eg. do-while loop
In an exit controlled loop, a condition is checked after executing the body of a loop. It
is also called as a post-checking loop. Eg. for and while loop
C provides three types of loop control structures. They are:
• for statement
• while statement
• do-while statement
129. for statement
The for loop statement is useful to repeat a
statement/s a known number of times. The
general syntax is as follows:
for (initialization; condition; operation)
{
statement;
}
The initialization is generally an assignment
statement that is used to set the loop control
variable.
The condition is an
expression(relational/logical/arithmetic/bitwise
….) that determines when the loop exists.
The Operation defines how the loop control
variable changes each time the loop is repeated.
132. Nested for loop
Nested loops consist of one loop placed
inside another loop. An example of a
nested for loop is:
for (initialization; condition; operation)
{
for (initialization; condition; operation)
{
statement;
}
statement;
}
134. while
statement
The second loop available in ‘C’ is while
loop.
The general format of while loop is:
while (expression)
{
statement
}
A while statement is useful to repeat a
statement execution as long as a condition
remains true or an error is detected. The
while statement tests the condition before
executing the statement.
135. Example
#include <stdio.h >
void main()
{
int i, j, k, temp;
printf("ItI^2tI^3tI^4 n");
printf("--------------------------------n");
i = 1;
while (i < 10) /* Outer loop */
{
j = 1;
while (j < 5) /* 1st level of nesting */
{
temp = 1;
k = 1;
while (k < j)
{
temp = temp * i;
k++;
}
printf ("%dt", temp);
j++;
}
printf ("n");
i++;
}
136. do-while
statement
The third loop available in C is do
– while loop.
The general format of do-while is:
do
{
statement;
} while (expression);
140. Unconditional statement
C has four jump statements to perform an unconditional branch:
• return
• goto
• break and
• continue
141. Return statement
A return statement is used to return from a function. A function can use this statement
as a mechanism to return a value to its calling function. If now value is specified,
assume that a garbage value is returned (some compilers will return 0).
The general form of return statement is:
return expression;
Where expression is any valid rvalue expression.
Example:
return x; or return(x);
return x + y or return(x + y);
return rand(x); or return(rand(x));
return 10 * rand(x); or return (10 * rand(x));
142. goto statement Void main()
{
int x = 6, y = 12;
if( x == y)
x++;
else
goto error;
error:
printf (“Fatal error; Exiting”);
}
The compiler doesn‟t require any formal declaration of the label identifiers.
goto statement provides a method of
unconditional transfer control to a labeled
point in the program. The goto statement
requires a destination label declared as:
label:
The label is a word (permissible length is
machine dependent) followed by a colon. The
goto statement is formally defined as:
goto label;
„
„
„
label:
143. break statement
void main()
{
int value;
while (scanf(“%d'', &value ) == 1 && value != 0)
{
if(value < 0)
{
printf (“Illegal valuen'');
break; /* Terminate the loop */
}
if(value > 100)
{
printf(“Invalid valuen'');
continue; /* Skip to start loop again */
}
} /* end while value != 0 */
}
We can use it to terminate a case in a
switch statement and to terminate a
loop.
Consider the following example where we
read an integer values and process them
according to the following conditions.
If the value we have read is negative, we
wish to print an error message and
abandon the loop. If the value read is
greater than 100, we wish to ignore it
and continue to the next value in the
data.
If the value is zero, we wish to terminate
the loop.
144. Continue
statement
/* Program to print the even numbers below 100 */
#include<stdio.h>
void main()
{
int x;
for(x = 1; x < 10; x++)
{
if (x % 2)
continue;
printf (“%dt”, x)
}
}
The continue statement forces the
next iteration of the loop to take
place, skipping any code in
between.
But the break statement forces for
termination.
An odd number causes continue to execute and the next iteration to occur, by
passing the printf () statement. A continue statement is used within a loop ( i.e for,
while, do – while) to end an iteration in while and do-while loops, a continue
statement will cause control to go directly to the conditional test and then continue
the looping process.
In the case of for, first the increment part of the loop is performed, next the
conditional test is executed and finally the loop continues.
146. Exit statement
Void menu(void)
{
char ch;
printf(“B: Breakfast“);
printf(“L: Lunch“);
printf(“D: Dinner”);
printf(“E: Exit”);
printf(“Enter your choice: “);
do
{
ch = getchar();
switch (ch)
{
case „B‟ :
printf (“time for breakfast”);
break;
case „L‟ :
printf (“time for lunch”);
break;
case „D‟ :
printf (“time for dinner”);
break;
case „E‟ :
Just as we can break out of a loop, we can
break out of a program by using the
standard library function exit(). This
function causes immediate termination of
the entire program, forcing a return to the
operation system.
The general form of the exit() function is:
void exit (int return_code);
The value of the return_code is returned to
the calling process, which is usually the
operation system. Zero is generally used as
a return code to indicate normal program
termination.
exit (0); /* return to operating system */
}
} while (ch != „B‟ && ch != „L‟ && ch != „D‟);
}