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

Ilovepdf Merged

The document provides an overview of problem solving using the C programming language, covering topics such as the definition and importance of computer programming languages, programming paradigms, the history of programming languages, and the features and applications of C. It also includes information on setting up a C programming environment, the program development life cycle, and input/output functions in C. Additionally, it discusses common errors encountered during C program execution.

Uploaded by

Pratheek
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Ilovepdf Merged

The document provides an overview of problem solving using the C programming language, covering topics such as the definition and importance of computer programming languages, programming paradigms, the history of programming languages, and the features and applications of C. It also includes information on setting up a C programming environment, the program development life cycle, and input/output functions in C. Additionally, it discusses common errors encountered during C program execution.

Uploaded by

Pratheek
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 109

PROBLEM SOLVING WITH C

UE21CS141B

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C

Introduction

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Introduction

1. Computer Programming Language(CPL)

2. Why CPLs ?

3. Intro to Paradigms

4. Levels of Languages

5. Why C after Python?

6. Applications of C

7. First Programmer

8. History of PLs and Development of C

9. Features of C
PROBLEM SOLVING WITH C
Introduction

Computer Programming Language(CPL)?


● Any set of rules that converts strings, or graphical program elements in the case of
visual programming languages, to various kinds of machine code output
● An artificial language that can be used to control the behaviour of a machine,
particularly a computer
● CPLs, like human languages, are defined through the use of syntactic and semantic
rules, to determine structure and meaning respectively.
● CPLs are used to implement algorithms.

● CPL allows to give instructions to a computer in a language the computer understands.


PROBLEM SOLVING WITH C
Introduction

Why Computer Programming Language(CPL)?


● Advance our ability to develop real algorithms.

● Majority of CPLs come with a lot of features for the Computer Programmers - CP.

● CPLs can be used in a proper way to get the best results.

● Improve Customization of our Current Coding

● By using basic features of the existing CPL we can simplify things to program a better
option to write resourceful codes.
● There is no compulsion of writing code in a specific way, but rather is the usage of
features and clarity of the concept.
PROBLEM SOLVING WITH C
Introduction

Paradigm – Style of Programming

● Imperative
● First do this and next do that
● FORTRAN, Algol, COBOL, Pascal
● Structured programming
● Single entry and single exit. Avoid GOTO
● C
● Procedural
● Subset of imperative
● Use of subroutines
●C
● Declarative
● Declares a set of rules about what outputs should result from which inputs
● Lisp, SQL
PROBLEM SOLVING WITH C
Introduction

Paradigm – Continued..
● Functional
● Function should be the first class citizen. No side effects. Assign Function
name to another, pass function name as an argument, return function itself
● If and recursion. No loops
● Scheme, Haskell, Miranda and JavaScript
● Logical
● Uses predicates
● Extraction of knowledge from basic facts and relations
● ASP, Prolog and Datalog
● Object-Oriented
● User perception is taken into account.
● Data needs protection
● Java, c++, Python
PROBLEM SOLVING WITH C
Introduction

Levels of Languages
PROBLEM SOLVING WITH C
Introduction

First Programmer – Ada Lovelace


PROBLEM SOLVING WITH C
Introduction

Why C after Python ?


• Paradigms - Procedural vs OOP
• Aged compared to Python
• Growth rate of PLs - TIOBE Index
PROBLEM SOLVING WITH C
Introduction

TIOBE Index
• The Importance of Being Earnest
• An indicator of the popularity of programming
languages. Updated once in a month
• The ratings are based on the number of skilled engineers
world-wide, courses and third party vendors. Popular
search engines such as Google, Bing, Yahoo!, Wikipedia,
Amazon, YouTube and Baidu are used
• It is not about the best programming language or the
language in which most lines of code have been written.
PROBLEM SOLVING WITH C
Introduction

Applications of C/C++

 Embedded systems and mechatronic systems with hardware interfaces


 Linux Kernel: It is written in C
 Adobe Systems: Includes Photoshop and Illustrator
 Mozilla: Internet Browser Firefox Uses C++.
 Bloomberg: Provides real time financial information to investors
 Callas Software: Supports PDF creation, optimization, updation tools and plugins
 Symbian OS: Used in cellular phones.
PROBLEM SOLVING WITH C
Introduction
History of PLs
● 1820-1850 England, Charles Babbage invented two mechanical Computational device i.e., Analytical
Engine and Difference Engine
● In 1942, United States, ENIAC used electrical signals instead of physical motion
● In 1945, Von Newmann developed two concepts: Shared program technique and Conditional control
transfer
● In 1949, Short code appeared
● In 1951, Grace Hopper wrote first compiler, A-0
● Fortran: 1957, John Backus designed.
● Lisp, Algol- 1958
● Cobol: 1959
● Pascal: 1968, Niklaus Wirth
● C: 1972, D Ritchie
● C++: 1983, Bjarne Stroustrup, Compile time type checking, templates are used.
● Java: 1995, J. Gosling, Rich set of APIs and portable across platform through the use of JVM
PROBLEM SOLVING WITH C
Introduction

History.. Continued...

● Development of C
● Martin Richards, around 60’s developed BCPL [Basic Combined Programming
Language]
● Enhanced by Ken Thompson and Introduced B language.
● C is Originally developed between 1969 and 1973 at Bell Labs by Dennis Ritchie and
Kernighan. Closely tied to the development of the Unix operating system

● Standardized by the ANSI [American National Standards Institute] since 1989 and
subsequently by ISO[International Organization for Standardization].

● C Standard
● ANSI C, C89, C99, C11, C17, or C2x – Specifications of C
● C Standard Library
PROBLEM SOLVING WITH C
Introduction

FYK

• Charles Babbage – Father of Computer

• Dennis Ritchie

• Brian Kernighan
PROBLEM SOLVING WITH C
Introduction

Features of C Language
THANK YOU

Prof. Sindhu R Pai


Department of Computer Science and Engineering
[email protected]
PROBLEM SOLVING WITH C
UE21CS141B

Prof. Sindhu R Pai


Department of Computer Science
and Engineering
PROBLEM SOLVING WITH C

C Programming Environment

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
C Programming Environment

1. Installation of gcc on different Operating systems

2. Program Development Life Cycle [PDLC]

3. First Program in C

4. Structure of C Program

5. Steps involved in execution of C Program

6. GCC Insights

7. C Compiler standards

8. Errors during execution


PROBLEM SOLVING WITH C
C Programming Environment

Installation of gcc on different Operating systems


● Windows OS – Installation of gcc using Mingw.
● https://www.youtube.com/watch?v=sXW2VLrQ3Bs

● Linux OS – gcc available by default

● Mac OS – gcc available by default


PROBLEM SOLVING WITH C
C Programming Environment

Program Development Life Cycle [PDLC]

Fig 1: Phases involved in PDLC


PROBLEM SOLVING WITH C
C Programming Environment

First Program in C
● Case sensitive
#include<stdio.h>
int main()
● Indentation is not a language
{ requirement
printf(“Hello PES\n”);
return 0; ● The main() is the starting point of
} execution

//Importance of int main and return values ● Comments in C


● Using // for single line comment
● Using /* and */ for multiline
comment

● Statements must end with semicolon(;)


PROBLEM SOLVING WITH C
C Programming Environment

Program Structure
PROBLEM SOLVING WITH C
C Programming Environment

Steps involved in execution of code

Way 1:
Step1: gcc <filename> // image a.out is the output
Step2: ./a.out OR a.exe

Way 2: Creating the object files separately


Compile: gcc -c <filename> // filename.o is the output
Link: gcc filename.o OR gcc <list of object files> -l <library>
Execute: ./a.out OR a.exe

Way 3: Renaming the object files


Step1: gcc <filename> -o <imagename>
Step2: <imagename>
PROBLEM SOLVING WITH C
C Programming Environment

GCC insights cont..


• The original author of the GNU C Compiler (gcc) is Richard Stallman, the founder of the GNU Project
• GNU stands for GNU's not Unix
• The GNU Project was started in 1984 to create a complete Unix-like operating system as free software,
in order to promote freedom and cooperation among computer users and programmers
• The first release of gcc was made in 1987, as the first portable ANSI C optimizing compiler released as
free software
• A major revision of the compiler came with 2.0 series in 1992, added the ability to compile C++
• The acronym gcc is now used to refer to the “GNU Compiler Collection”
• Extended to support many additional languages, including Fortran, ADA, Java and Objective-C
PROBLEM SOLVING WITH C
C Programming Environment

GCC insights cont..


• It’s development is guided by the gcc Steering Committee, a group composed of representatives from
gcc user communities in industry, research and academia
• A portable compiler, it runs on most platforms available today, and can produce output for many types
of processors
• Supports microcontrollers, DSPs and 64-bit CPUs
• Not only a native compiler, it can also cross-compile any program, producing executable files for a
different system from the one used by gcc itself.
• Allows software to be compiled for embedded systems
• Written in C with a strong focus on portability, and can compile itself, so it can be adapted to new
systems easily
PROBLEM SOLVING WITH C
C Programming Environment

GCC insights cont..


• Has multiple language frontends, for parsing different languages
• Can compile or cross-compile programs in each language, for any architecture. For example, can
compile an ADA program for a microcontroller, or a C program for a supercomputer
• Has a modular design, allowing support for new languages and architectures to be added.
• A free software, distributed under the GNU General Public License (GNU GPL), which means we have the
freedom to use and to modify gcc, as with all GNU software.
• gcc users have the freedom to share any enhancements and also make use of enhancements to gcc
developed by others
PROBLEM SOLVING WITH C
C Programming Environment

GCC insights
• gcc will not produce any warnings unless they are enabled. gcc –Wall

• Compiler warnings are an essential aid in detecting problems when programming in c

• Source code which does not produce any warnings by gcc, is said to be compile cleanly.

• The following options are a good choice for finding problems in C and C++ programs
• gcc -ansi -pedantic -Wall -W -Wconversion -Wshadow -Wcast-qual -Wwrite-strings
PROBLEM SOLVING WITH C
C Programming Environment

C Compiler standards

Standardized by ANSI and ISO: C89, C99 and C11

Using c99:
gcc -std=c99 program.c

Using c11:
gcc -std=c11 program.c

Use __STDC_VERSION__ we can get the standard C version


PROBLEM SOLVING WITH C
C Programming Environment

Error:
• a mistake
• the state or condition of being wrong in conduct or judgement
• a measure of the estimated difference between the observed or calculated value
of a quantity and its true value
Errors during C program Execution:
• Compile time Error
• Link time Error
• Run time Error
• Logical Error
PROBLEM SOLVING WITH C
C Programming Environment

Compile time Error


• When the programmer does not follow the syntax of any programming language,
then the compiler will throw the Syntax Error, such errors are also called Compile
Time Error

• Syntax Errors are easy to figure out because the compiler highlights the line of
code that caused the error.

• Coding examples
PROBLEM SOLVING WITH C
C Programming Environment

Link time Error/ Linker Error

• Linker is a program that takes the object files generated by the compiler and combines them
into a single executable file.
• Linker Errors are the errors encountered when the executable file of the code can not be
generated even though the code gets compiled successfully.
• This Error is generated when a different object file is unable to link with the main object file.
• We can run into a linked error if we have imported an incorrect header file in the code
• Coding examples
PROBLEM SOLVING WITH C
C Programming Environment

Run time Error

• Errors that occur during the execution (or running) of a program.


• These errors occur after the program has been compiled and linked successfully.
• When a program is running, and it is not able to perform any particular operation, it means
that we have encountered a runtime error.
Example: Illegal operations like Divide by zero, Accessing the file that is not available, Lack of
free memory space
• Coding examples
PROBLEM SOLVING WITH C
C Programming Environment

Logical Error

• Sometimes, we do not get the output we expected after the compilation and execution of a
program.

• Even though the code seems error free, the output generated is different from the expected
one.
THANK YOU

Prof. Sindhu R Pai


Department of Computer Science and Engineering
[email protected]
PROBLEM SOLVING WITH C
UE21CS141B

Prof. Sindhu R Pai


Department of Computer Science
and Engineering
PROBLEM SOLVING WITH C

Simple Input / Output

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Simple Input/Output

1. Introduction

2. Formatted output function

3. Formatted input function

4. Unformatted functions
PROBLEM SOLVING WITH C
Simple Input/Output

Introduction
● Input and output functions are available in the c language to perform the most
common tasks.
● In every c program, three basic functions take place namely accepting of data as
input, the processing of data, and the generation of output
● When a programmer says input, it would mean that they are feeding some data in
the program. Programmer can give this input from the command line or in the form
of any file. This language comes with a set of various built-in functions for reading
the input and then feeding it to the available program as per our requirements.
● When a programmer says output, they mean displaying some data and information
on the printer, the screen, or any other file. ● The c language comes with various
built-in functions for generating the output of the data on any screen or printer, and
also redirecting the output in the form of binary files or text file
PROBLEM SOLVING WITH C
Simple Input/Output

Formatted output function – printf()


● int printf(const char *format, ...)
● Predefined function in stdio.h
● Sends formatted output to stdout by default
● Output is controlled by the first argument
● Has the capability to evaluate an expression
● On success, it returns the number of characters successfully written on
the output.
● On failure, a negative number is returned.
● Arguments to printf can be expressions
● Coding examples
PROBLEM SOLVING WITH C
Simple Input/Output

Format string
● % [flags] [field_width] [.precision] conversion_character
where components in brackets [] are optional. The minimum requirement is %
and a conversion character (e.g. %d).

● %d, %x, %o, %f, %c, %p, %lf, %s

● Coding examples
PROBLEM SOLVING WITH C
Simple Input/Output

Escape sequences
● Represented by two key strokes and represents one character

● \n, \t, \r, \a, \”, \’, \\, \b

● Coding examples
PROBLEM SOLVING WITH C
Simple Input/Output

Formatted input function – scanf()


● int scanf(const char *format, ...)
● Predefined function in stdio.h
● & : Address operator is compulsory in scanf for all primary types
● Reads formatted input using stdin. By default keyboard
● This function returns the following value
● >0 — The number of items converted and assigned successfully.
● 0 — No item was assigned.
● <0 — Read error encountered or end-of-file (EOF) reached before any
assignment was made
● Coding examples
PROBLEM SOLVING WITH C
Simple Input/Output

Unformatted functions
● Character input and output functions – getchar() and putchar()

● String input and output functions – gets() and puts() This will be discussed in unit – 2

● Coding examples
THANK YOU

Prof. Sindhu R Pai


Department of Computer Science and Engineering
[email protected]
+91 8277606459 – Available on whatsapp
PROBLEM SOLVING WITH C
UE21CS141B

Prof. Sindhu R Pai


Department of Computer Science
and Engineering
PROBLEM SOLVING WITH C

Simple Input / Output

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Simple Input/Output

1. Introduction

2. Formatted output function

3. Formatted input function

4. Unformatted functions
PROBLEM SOLVING WITH C
Simple Input/Output

Introduction
● Input and output functions are available in the c language to perform the most
common tasks.
● In every c program, three basic functions take place namely accepting of data as
input, the processing of data, and the generation of output
● When a programmer says input, it would mean that they are feeding some data in
the program. Programmer can give this input from the command line or in the form
of any file. This language comes with a set of various built-in functions for reading
the input and then feeding it to the available program as per our requirements.
● When a programmer says output, they mean displaying some data and information
on the printer, the screen, or any other file. ● The c language comes with various
built-in functions for generating the output of the data on any screen or printer, and
also redirecting the output in the form of binary files or text file
PROBLEM SOLVING WITH C
Simple Input/Output

Formatted output function – printf()


● int printf(const char *format, ...)
● Predefined function in stdio.h
● Sends formatted output to stdout by default
● Output is controlled by the first argument
● Has the capability to evaluate an expression
● On success, it returns the number of characters successfully written on
the output.
● On failure, a negative number is returned.
● Arguments to printf can be expressions
● Coding examples
PROBLEM SOLVING WITH C
Simple Input/Output

Format string
● % [flags] [field_width] [.precision] conversion_character
where components in brackets [] are optional. The minimum requirement is %
and a conversion character (e.g. %d).

● %d, %x, %o, %f, %c, %p, %lf, %s

● Coding examples
PROBLEM SOLVING WITH C
Simple Input/Output

Escape sequences
● Represented by two key strokes and represents one character

● \n, \t, \r, \a, \”, \’, \\, \b

● Coding examples
PROBLEM SOLVING WITH C
Simple Input/Output

Formatted input function – scanf()


● int scanf(const char *format, ...)
● Predefined function in stdio.h
● & : Address operator is compulsory in scanf for all primary types
● Reads formatted input using stdin. By default keyboard
● This function returns the following value
● >0 — The number of items converted and assigned successfully.
● 0 — No item was assigned.
● <0 — Read error encountered or end-of-file (EOF) reached before any
assignment was made
● Coding examples
PROBLEM SOLVING WITH C
Simple Input/Output

Unformatted functions
● Character input and output functions – getchar() and putchar()

● String input and output functions – gets() and puts() This will be discussed in unit – 2

● Coding examples
THANK YOU

Prof. Sindhu R Pai


Department of Computer Science and Engineering
[email protected]
+91 8277606459 – Available on whatsapp
PROBLEM SOLVING WITH C
UE21CS141B

Prof. Sindhu R Pai


Department of Computer Science
and Engineering
PROBLEM SOLVING WITH C

Language Specifications/Behaviors

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Language Specifications/Behaviors

1. Language Specification

2. Standards

3. Behaviors defined by C Standards

4. Undefined Behavior in detail


PROBLEM SOLVING WITH C
Language Specifications/Behaviors

Language Specification
 A documentation that defines a programming language so that users
and implementers can agree on what programs in that language mean.

 Are typically detailed and formal, and primarily used by implementers referring
to them in case of ambiguity.

 Can take several forms:


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
PROBLEM SOLVING WITH C
Language Specifications/Behaviors

Standards
de Jure: Practices that are legally recognized, regardless of whether the practice
exists in reality.
de Facto: Describes situations that exist in reality, even if not legally recognized

 Language may have one or more implementations which acts as deFacto Language may
be implemented and then specified, or vice versa or together.
 Languages can exist and be popular for decades without a specification - Perl
 After 20 years of usage, specification for PHP in 2014
 ALGOL 68 : First (and possibly one of the last) major language for which a full formal
definition was made before it was implemented
PROBLEM SOLVING WITH C
Language Specifications/Behaviors

Behaviors defined by C Standards

• Locale-specific behavior - Not discussed here

• Unspecified behavior - Order of evaluation of arguments in printf function

• Implementation-defined behavior – Size of each type

• Undefined behavior in detail


PROBLEM SOLVING WITH C
Language Specifications/Behaviors

Undefined Behavior in detail


 The result of executing a program whose behavior is prescribed to be unpredictable
in the language specification to which the computer code adheres.

 It is the name of a list of conditions that the program must not meet.

 Examples: Memory access outside of array bounds, Signed integer overflow

 Standard imposes no requirements: May fail to compile, may crash, may generate
incorrect results, may fortunately do what exactly programmer intended

 Coding Examples
THANK YOU

Prof. Sindhu R Pai


Department of Computer Science and Engineering
[email protected]
PROBLEM SOLVING WITH C
UE21CS141B

Prof. Sindhu R Pai


Department of Computer Science
and Engineering
PROBLEM SOLVING WITH C

Variables and Types

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Variables and Data Types

1. Identifiers

2. Variable declaration, definition and initialization

3. Keywords

4. Data types
PROBLEM SOLVING WITH C
Variables and Data Types

Identifiers
● It is a name used to identify a variable, keyword, function, or any
other user-defined item.

● Starts with a letter A to Z, a to z, or an underscore '_' followed by zero


or more letters, underscores, and digits (0 to 9)

● C does not allow few punctuation characters such as #, @ and %


within identifiers
PROBLEM SOLVING WITH C
Variables and Data Types

Keywords
PROBLEM SOLVING WITH C
Variables and Data Types

Variable declaration, definition and initialization

● Variable is a name given to a storage area that a code can manipulate

● Has a name, location, type, life, scope and qualifiers, Variable initialization: int a = 10;

● Variable declaration and definition: int a; //An uninitialized variable has some undefined
value. A variable can be assigned a value later in the code

● There is no rule on how long a variable name aka user defined identifier can be. Variable
name may run into problems in some compilers, if the variable name is longer than 31
characters

● c is a strongly typed language : Variable type cannot be changed once it is declared.


PROBLEM SOLVING WITH C
Variables and Data Types

Keywords
● Are identifiers which have special meaning in C.

● Cannot be used as constants or variables

● Few here: auto, else, long, switch, break, enum, case, extern, return
char, float, for, void, sizeof, int, double …

● int auto = 10; // Error


PROBLEM SOLVING WITH C
Variables and Data Types

Data Types
● The amount of storage to be reserved for the specified variable.

● Significance of types: Memory allocation, Range of values allowed, Operations bound to


this type, Type of data to be stored

● Categories: Primary  int, float, double and char


Secondary  Derived(Arrays, pointers, functions) and User defined(struct, enum, union and
typedef)

● sizeof(short int)<=sizeof(int)<=sizeof(long int)<=sizeof(long long int)<=


sizeof(float)<=sizeof(double)<=sizeof(long double)

● Coding examples on Range of values using limits.h


THANK YOU

Prof. Sindhu R Pai


Department of Computer Science and Engineering
[email protected]
PROBLEM SOLVING WITH C
UE20CS151

Prof. Sindhu R Pai


Department of Computer Science
and Engineering
PROBLEM SOLVING WITH C

Operators in C

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Operators in C

1. Operators and its Classification

2. Expression

3. Sequence point operation


PROBLEM SOLVING WITH C
Operators in C

Operator and its Classification


● Operator is a symbol used for calculations or evaluations
● Has rank, precedence and Associativity
● Classification: Based on the operation:
Arithmetic – Increment(++) & Decrement(--)
Relational - >, <, <=, >=, ==, !=
Logical(short circuit evaluation) - &&, ||, !
Bitwise - &, |, ~, ^, <<, >>
Address - &
Dereferencing Operator - *
Based on the operands: Unary, Binary, Ternary
PROBLEM SOLVING WITH C
Operators in C

Expression
● An expression consists of Operands
and Operators
● Evaluation of Operands: Order is not
defined
● Evaluation of Operators: Follows the
rules of precedence and rules of
Associativity
http://web.cse.ohio-
state.edu/~babic.1/COperatorPreceden
ceTable.pdf
● L-value and R-values.
● Side effects of Expression
● Coding examples
PROBLEM SOLVING WITH C
Operators in C

Sequence point Operation


● Specifies points in the code beyond which all side effects will definitely be
complete

● Beyond this, any variable can be used with no ambiguity

● Coding examples with &&


THANK YOU

Prof. Sindhu R Pai


Department of Computer Science and Engineering
[email protected]
PROBLEM SOLVING WITH C
UE21CS141B

Prof. Sindhu R Pai


Department of Computer Science
and Engineering
PROBLEM SOLVING WITH C

Control Structures

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Control Structures

1. Selection structures

2. Looping structures

3. Nested Control Structures

4. Practice Programs
PROBLEM SOLVING WITH C
Control Structures

Selection Structures
 If  Switch
if (e1) switch (expression)
<block>|<stmt> {
 If – else case integral constant: <stmt> break;
if (e1) case integral constant: <stmt> break;
<block>|<stmt> default: <stmt>

else }

<block>|<stmt>

 If – else if – else if – else  Coding Examples


if (e1)

<block>|<stmt>

else if (e2)

<block>|<stmt>

else

<block>|<stmt>
PROBLEM SOLVING WITH C
Control Structures

Looping Structures
 for
for(e1; e2; e3)
<block>|<stmt>
 while
while(e2)
<block>|<stmt>
 do while
do { <block>
}while(e2);
e1,e2,e3 are expressions where e1: initialization, e2: condition, e3: modification
 Infinite loop
 Coding Examples
PROBLEM SOLVING WITH C
Control Structures

Nested Control structures

 One loop may be inside another

 One if may be inside another: inner if is reached only if the Boolean condition of the outer if is
true

 Combination of above two

 Coding Examples
THANK YOU

Prof. Sindhu R Pai


Department of Computer Science and Engineering
[email protected]
PROBLEM SOLVING WITH C
UE21CS141B

Prof. Sindhu R Pai


Department of Computer Science
and Engineering
PROBLEM SOLVING WITH C

Control Structures

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Control Structures

1. Selection structures

2. Looping structures

3. Nested Control Structures

4. Practice Programs
PROBLEM SOLVING WITH C
Control Structures

Selection Structures
 If  Switch
if (e1) switch (expression)
<block>|<stmt> {
 If – else case integral constant: <stmt> break;
if (e1) case integral constant: <stmt> break;
<block>|<stmt> default: <stmt>

else }

<block>|<stmt>

 If – else if – else if – else  Coding Examples


if (e1)

<block>|<stmt>

else if (e2)

<block>|<stmt>

else

<block>|<stmt>
PROBLEM SOLVING WITH C
Control Structures

Looping Structures
 for
for(e1; e2; e3)
<block>|<stmt>
 while
while(e2)
<block>|<stmt>
 do while
do { <block>
}while(e2);
e1,e2,e3 are expressions where e1: initialization, e2: condition, e3: modification
 Infinite loop
 Coding Examples
PROBLEM SOLVING WITH C
Control Structures

Nested Control structures

 One loop may be inside another

 One if may be inside another: inner if is reached only if the Boolean condition of the outer if is
true

 Combination of above two

 Coding Examples
THANK YOU

Prof. Sindhu R Pai


Department of Computer Science and Engineering
[email protected]
PROBLEM SOLVING WITH C
UE21CS141B

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C

Programs on Control Structures

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Programs on Control Structures

1. Problem Statements

2. Demo of Solution using C

3. Practice Programs
PROBLEM SOLVING WITH C
Programs on Control Structures

Problem Statements – set 1


• You are transporting some boxes through a tunnel whose height is only 41 feet. Given the length,
width, and height of the box, calculate the volume of those boxes and check if they pass through
the tunnel.
Ex: Input = 5, 5, 5 Output = 125
Input = 1, 2, 40 Output = 80
Input = 10, 5, 41 Output = Can’t Pass!

• Given the number of rows, print a hollow diamond using star symbol: Ex: Input = 5
• Check whether the given number is divisible by the sum of its digits. Display appropriate message
• Write a C program to find the eligibility of admission for a professional course based on the
following criteria: Eligibility Criteria : Marks in Maths >=65 and Marks in Physics >=50 and Marks in
Chemistry>=55 and Total in all three subjects >=190 or Total in Maths and Physics >=140
PROBLEM SOLVING WITH C
Programs on Control Structures

Problem Statements – set 2

• Construct a C program to reverse the bits of an integer.

• Construct a menu-based calculator to perform arithmetic operations (Add, Subtract, Multiply) on


complex numbers.

• Given a number n, find the count of those numbers whose product of digits is equal to n and does
not contain 1. Ex: input: 4 output: 2 (2 x 2 = 4, so count is 2)
PROBLEM SOLVING WITH C
Programs on Control Structures

Demo of solutions
PROBLEM SOLVING WITH C
Programs on Control Structures

Practice Programs

• You are given a number N. Your task is to find if there exist two distinct natural numbers such
that their bitwise XOR is N and bitwise AND is 0. If such numbers exist, then print 1. Otherwise,
print 0. Ex: Input = 0 Output = 0 Input = 5 Output = 1 (Possible numbers are 4 and 1)

• Using Switch case, implement a converter to obtain an integer from a hexadecimal byte
THANK YOU

Prof. Sindhu R Pai


Department of Computer Science and Engineering
[email protected]
PROBLEM SOLVING WITH C
UE21CS141B

Prof. Sindhu R Pai


Department of Computer Science
and Engineering
PROBLEM SOLVING WITH C

Counting Problem

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Counting Problem

1. Statement of the Problem

2. Requirements to solve the problem

3. Demonstration of the C solution


PROBLEM SOLVING WITH C
Counting Problem

Statement of the problem

 Count and display the number of characters, number of words and number of lines in an user input
 Count and display the number of characters, number of words and number of lines in a given file
PROBLEM SOLVING WITH C
Counting Problem

Requirements to solve the problem

 how to read and display a character? - Discussed in Character I/O


 how to read a line?
 how to read from the file? - Input redirection Operator
 how to make out when we reach the end of file?
 how to break a given sequence of characters into words and lines?
PROBLEM SOLVING WITH C
Counting Problem

Solution to the problem

 Demonstration of C code
THANK YOU

Prof. Sindhu R Pai


Department of Computer Science and Engineering
[email protected]

You might also like