PSWC Unit I Full
PSWC Unit I Full
PSWC Unit I Full
Compiled by
M S Anand
Text Book(s):
1. “How To Solve It By Computer”, R G Dromey, Pearson, 2011.
2. “The C Programming Language”, Brian Kernighan, Dennis
Ritchie, 2nd Edition, Prentice Hall PTR, 1988.
Reference Book(s):
1. “Expert C Programming; Deep C secrets”, Peter van der Linden
2. “ The C puzzle Book”, Alan R Feuer
11/03/2024
Problem Solving With C
Introduction
11/03/2024
Problem Solving With C
Introduction
Why study C?
C is one of the most important programming languages in the
history of computing.
11/03/2024
Problem Solving With C
Introduction
For example, the UNIX kernel itself was rewritten in 1973 on a DEC
PDP-11.
11/03/2024
Problem Solving With C
Introduction
Evolution of C
Over time, C began to be used in personal computers for
developing software applications and other purposes.
It appears that this language will continue to be with us long into the
future as well.
Proof (??)
The TIOBE Programming Community index is an indicator of the
popularity of programming languages. The index is updated once a
month. The ratings are based on the number of skilled engineers
world-wide, courses and third party vendors.
11/03/2024
Problem Solving With C
C Standards
The C programming language has several standard versions, with the most
commonly used ones being C89/C90, C99, C11, and C18.
❑ C89/C90 (ANSI C or ISO C) was the first standardized version of the
language, released in 1989 and 1990, respectively. This standard
introduced many of the features that are still used in modern C
programming, including data types, control structures, and the standard
library.
❑ C99 (ISO/IEC 9899:1999) introduced several new features, including
variable-length arrays, flexible array members, complex numbers, inline
functions, and designated initializers. This standard also includes
several new library functions and updates to existing ones.
❑ C11 (ISO/IEC 9899:2011) introduced several new features, including
_Generic, static_assert, and the atomic type qualifier. This standard also
includes several updates to the library, including new functions for math,
threads, and memory manipulation.
❑ C18 (ISO/IEC 9899:2018) is the most recent standard and includes
updates and clarifications to the language specification and the library.
11/03/2024
Problem Solving With C
Programming language
11/03/2024
Problem Solving With C
Programming language
11/03/2024
Problem Solving With C
Programming language
11/03/2024
Problem Solving With C
Creating and executing a C program
Creating C Programs
There are four fundamental stages, or processes, in the creation of
any C program:
1. Editing
2. Compiling
3. Linking
4. Executing
11/03/2024
Problem Solving With C
Creating and executing a C program
11/03/2024
Problem Solving With C
Creating and executing a C program
Editing
Editing is the process of creating and modifying C source code—
the name given to the program instructions you write. Some C
compilers come with a specific editor program that provides a lot of
assistance in managing your programs.
Compiling
The compiler converts your source code into machine language
and detects and reports errors in the compilation process. The input
to this stage is the file you produce during your editing, which is
usually referred to as a source file.
Linking
The linker combines the object modules generated by the compiler from
source code files, adds required code modules from the standard library
supplied as part of C, and welds everything into an executable whole. The
linker also detects and reports errors; for example, if part of your program
is missing or a nonexistent library component is referenced.
Executing
The execution stage is where you run your program, having completed all
the previous processes successfully. Unfortunately, this stage can also
generate a wide variety of error conditions that can include producing the
wrong output, just sitting there and doing nothing, or perhaps crashing your
computer for good measure. In all cases, it’s back to the editing process to
check your source code.
Debugging
Find the errors and fix them.
11/03/2024
Problem Solving With C
Setting up the development environment
Refer to airport
11/03/2024
Problem Solving With C
The first program
gcc hello.c
1. Documentation
2. Preprocessor Section
3. Definition
4. Global Declaration
5. Main() Function
6. Sub Programs (other functions)
11/03/2024
Problem Solving With C
Compilation – a few options
Compilation
gcc –E source_file
The output after preprocessing is done
gcc –c source_file
Output file is an object file
gcc source_file
Executable file (if there were no errors)
11/03/2024
Problem Solving With C
Constants and variable types
long double
long long –
sizeof operator
11/03/2024
Problem Solving With C
Variables
What is a variable?
A variable in a program is a specific piece of memory that consists
of one or more contiguous bytes, typically 1, 2, 4, 8 or 16 bytes.
Naming Variables
The name you give to a variable, conveniently referred to as a
variable name, can be defined with some flexibility.
A variable name is a sequence of one or more uppercase or
lowercase letters, digits, and underscore characters (_) that begin
with a letter (incidentally, the underscore character counts as a
letter).
11/03/2024
Problem Solving With C
Variables
11/03/2024
Problem Solving With C
Reserved (key) words in C
11/03/2024
Problem Solving With C
Data types and range of values
Variable type Keyword Bytes required Range
11/03/2024
Problem Solving With C
Basic input and output in C
11/03/2024
Problem Solving With C
Operators and Expressions
11/03/2024
Problem Solving With C
Arithmetic Operators
11/03/2024
Problem Solving With C
Relational Operators
The result of a logical operation is either True (1) or False (0) A sample program is
here.
11/03/2024
Problem Solving With C
Logical Operators
The result of a logical operation is either True (1) or False (0) A sample program is
here.
11/03/2024
Problem Solving With C
Assignment Operators
11/03/2024
Problem Solving With C
Increment and Decrement Operators
Decrement operator − (- -)
pre decrement - --a
post decrement – a—
Sample programs:
preincr postincr
predecr postdecr
11/03/2024
Problem Solving With C
Bitwise Operators
11/03/2024
Problem Solving With C
Conditional (Ternary) Operator
if (exp1)
exp2;
else
exp3;
11/03/2024
Problem Solving With C
Special Operators
Special operators
Some of the special operators are comma, ampersand (&), sizeof
operators.
11/03/2024
Problem Solving With C
Control statements
goto statements in C
11/03/2024
Problem Solving With C
Control statements
if Statement
if (test expression)
{
// code
}
if...else Statement
if (test expression) {
// run code if test expression is true
}
else {
// run code if test expression is false
}
if...else Ladder
if (test expression1) {
// statement(s)
}
else if(test expression2) {
// statement(s)
}
else if (test expression3) {
// statement(s)
}
.
.
else {
// statement(s)
}
Nested if...else
It is possible to include an if...else statement inside the body of
another if...else statement.
11/03/2024
Problem Solving With C
Conditional statements
C switch Statement
The switch statement allows us to execute one code block among many
alternatives.
You can do the same thing with the if...else..if ladder. However, the syntax
of the switch statement is much easier to read and write.
switch (expression)
{
case constant1:
// statements
break;
case constant2:
// statements
break;
.
.
.
default:
// default statements
} A sample program is here.
11/03/2024
Problem Solving With C
goto statement
11/03/2024
Problem Solving With C
Loop statements
for loop
while loop
do...while loop
11/03/2024
Problem Solving With C
Loop statements
for loop
for (initializationStatement; testExpression; updateStatement)
{
// statements inside the body of loop
}
How does the for loop work?
✓ The initialization statement is executed only once.
✓ Then, the test expression is evaluated. If the test expression is
evaluated to false, the for loop is terminated.
✓ However, if the test expression is evaluated to true, statements
inside the body of the for loop are executed, and the update
expression is updated.
✓ Again the test expression is evaluated.
This process goes on until the test expression is false. When the
test expression is false, the loop terminates.
Sample program: find_ones1.c
11/03/2024
Problem Solving With C
Loop statements
while loop
while (testExpression) {
// the body of the loop
}
How does the while loop work?
✓ The while loop evaluates the testExpression inside the
parentheses ().
✓ If testExpression is true, statements inside the body of while loop
are executed. Then, testExpression is evaluated again.
✓ The process goes on until testExpression is evaluated to false.
✓ If testExpression is false, the loop terminates (ends).
11/03/2024
Problem Solving With C
Loop statements
do...while 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.
do {
// the body of the loop
}
while (testExpression);
break; find_ones4.c
The continue statement skips the current iteration of the loop and
continues with the next iteration. Its syntax is:
continue;
11/03/2024
Problem Solving With C
Loop statements
find_ones_zeros.c
11/03/2024
Problem Solving With C
Basic Input/Output functions
Input
Output
putchar() printf ()
11/03/2024
Problem Solving With C
Basic Input/Output functions
getchar ()
#include <stdio.h>
int getchar(void);
putchar ()
int putchar(int c)
11/03/2024
Problem Solving With C
Basic Input/Output functions
Write a program that asks the user to enter a fraction, then reduces
the fraction to lowest terms. (Example 6/12 to be reduced to ½)
Hint: To reduce a fraction to lowest terms, we need to divide both
the numerator and the denominator by the GCD of the numerator
and the denominator).
Write a program that prompts the user to enter two dates and then
indicates which date comes earlier in the calendar.
Write a program that prompts the user to enter a 2 digit number and
then prints the English word for the number.
11/03/2024
Problem Solving With C
Language specification and behavior
Language Specification
A programming language specification can take several forms,
including the following:
➢ An explicit definition of the syntax and semantics of the
language.
➢ A description of the behavior of a "translator” for the language
➢ “Model implementation” is a program that implements all
requirements from a corresponding specification
11/03/2024
Problem Solving With C
Language specification and behavior
Categories of programs by behavior
The original goal of the C standard committee in the early 1980s was to
codify the set of rules in existing implementations. This standardization was
possible for features in the original ”Kernighan and Ritchie C
manual” where compilers and runtime libraries all agreed on their
interpretation, but became more difficult when the compilers and libraries
diverged from it. Some diverged because the manual was ambiguous,
others to provide extensions useful for their target environment or CPU.
11/03/2024
Problem Solving With C
Language specification and behavior
To that end, the C standard recognizes several categories of programs.
Each category in turn places progressively weaker requirements on
implementations, and, as a result, weaker guarantees about programs'
behavior and portability.
Terminology:
✓ An implementation consists of a compiler and the standard C library.
The C library rarely stands on its own but is usually incorporated into a
larger library that implements some superset of C such as POSIX, or
some proprietary operating system API.
✓ By behavior, the standard means the observable output of a program:
The data it writes to open streams (such as stdout and stderr), or the
accesses it performs on volatile storage (both reading from it and writing
to it).
✓ Formally, the term behavior is defined as external appearance or action.
✓ Finally, the term portability is defined in the ISO vocabulary as
the capability of a program to be executed on various types of data
processing systems without converting the program to a different
language and with little or no modification.
11/03/2024
Problem Solving With C
Language specification and behavior
Well-defined behavior
Ideally, a program is portable without change, not just to the environments
intended for it, but to all possible environments, whether or not they exist in
the wild, ever did, or might in the future. Given the same input, a portable
program runs with the same output everywhere it's compiled today, and will
continue to do so in the future. Another way we can describe a portable
program like this is to call it well-defined.
11/03/2024
Problem Solving With C
Language specification and behavior
Unspecified behavior
The standard describes a few dozen coding constructs that might result in
more than one kind of behavior. A couple of examples are whether the
same string literals have distinct addresses, or the order in which
subexpressions are evaluated. Uses of these constructs are valid code that
implementations might handle in different ways that can even change from
one instance to another. Because the identified constructs are valid code,
their handling doesn't extend to issuing an error, either during compilation
or at runtime.
An example is here.
11/03/2024
Problem Solving With C
Language specification and behavior
Implementation-defined behavior
Besides constructs with undefined behavior, the standard also describes a
number of others that might result in more than one observable behavior,
but where implementations are required to document how each instance is
handled.
Example.
printf("Size of int: %d\nSize of char:%d\n", sizeof(int), sizeof(char));
11/03/2024
Problem Solving With C
Language specification and behavior
Locale-specific behavior
Locale-specific behavior is behavior that arises when a program
runs in a locale other than the default C locale. An example locale is
fr_CA for Canadian French. This behavior is a special category that
C programs opt into, either by being translated in a specific locale,
or at runtime by calling the setlocale function with a first argument
other than "C".
11/03/2024
Problem Solving With C
Language specification and behavior
Undefined behavior
The C standard describes programs that contain an undefined construct as either
nonportable or erroneous. The practical difference is that nonportable programs run
correctly (don't crash or misbehave), perhaps even with the expected output, in
some environments. In contrast, erroneous programs might (although they don't
need to) behave erratically or crash.
Most real-world programs fall into the undefined category: They contain some code
whose behavior is not defined by the C standard. This isn't necessarily a bad thing.
The behavior may be defined by some other standard or provided as an extension of
the implementation targeted by the program's authors.
11/03/2024
Problem Solving With C
Language specification and behavior
Undefined behavior
Some of the undefined behaviour are :
Division by zero
Ex. : printf("%d\n", 5 / 0);
11/03/2024
Problem Solving With C
Language specification and behavior
Undefined behavior can be broken down into two kinds: compile-time
undefined behavior and runtime undefined behavior.
enum { e, f, g = f / e };
The semantics of the division expression are undefined when the second
operand is zero. Because the compiler evaluates this division expression to
process the definition of the enumeration, the problem occurs at compile
time.
11/03/2024
Problem Solving With C
Language specification and behavior
11/03/2024
THANK YOU
M S Anand
Department of Computer Science Engineering
[email protected]