Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Modul 1 Complete

Download as pdf or txt
Download as pdf or txt
You are on page 1of 184

Module - 1

MCSC1C03: Principles of Programming Methodology

LEESHMA K
ASSISTANT PROFESSOR
DEPT. OF COMPUTER SCIENCE
ST.JOSEPH’S COLLEGE , DEVAGIRI
References:

1. Martin M. Lipschutz and Seymour Lipschutz, Schaum’s Outline of

Theory and Problems of Data Processing.

2. Anil Bikas Chaudhuri, The Art Of Programming Through Flowcharts

& Algorithms, Laxmi Publications, New Delhi.

3. Jean Paul Trembley and Pual G Sorenson, An Introduction to Data

Structures with Applications, Tata McGraw Hill.


Syllabus
Problem Solving - Flow Chart – Algorithm Design - Introduction to C Programming - overview and
importance of C - C Program Structure and Simple programs - Creation and Compilation of C
Programs under Linux and Windows Platforms. Elements of C Language and Program constructs -
structure of C program - character set, tokens, keywords, identifier - Data types, constants,
symbolic constants, variables, declaration, data input and output, assignment statements.
Operators in C - arithmetic operators, relational operators, logical operators, assignment
operators, increment and decrement operators, conditional operators, special operators,
precedence of operators - arithmetic expressions - evaluation of expressions, type conversion
inexpressions - precedence and associativity - mathematical functions - I/O operations.
Problem-solving
Problem-solving in programming methodology involves a systematic approach
to analyzing, designing, and implementing solutions to computational
problems.

Step 1: understand the problem.

Step 2: create a step-by-step plan for how you’ll solve it.

Step 3: carry out the plan and write the actual code.

Step 4: look back and possibly refactor your solution if it could be better.
Problem solving

Problem solving is a sequential process of analyzing information related to a given situation and generating
appropriate response options.

• In order to solve a problem by the computer , one has to pass through certain stages or steps. They are :

1. Understand the problem


7. Optimize and refine
2. Formulate a model 8. Document and Maintain
3. Develop an algorithm 9. Iterate and Improve
4. Write the problem

5. Test the problem

6. Evaluate the solution


1. Understand the problem
• Understand completely the problem given before design.
• It is very important to specify exactly the set of inputs that the problem needs to handle.

• Identify the problem domain


• Ask clarifying questions
• Consider edge cases and exceptions: Think about any potential edge cases or exceptions that might arise in
the problem. These can include scenarios where inputs are at their minimum or maximum values, cases
where unexpected or invalid input is provided, or situations where certain conditions may cause the
solution to behave differently.
• Visualize the problem
• Research if necessary: If the problem involves unfamiliar concepts or techniques, consider conducting
research to enhance your understanding.
2. Formulate the problem
• Processing part of the problem
• define the problem in a clear and concise manner
• It involves understanding the requirements, constraints, and desired outcomes, and translating
them into a well-defined problem statement.
• Define the boundaries and scope of the problem.
• Provide examples or sample inputs and expected outputs to illustrate the problem statement.
• Review the problem statement to ensure that it captures all the necessary information accurately
and completely.
3. Develop an algorithm
 Develop a precise plan of what we want the computer to do.

 A set of sequential steps usually written in ordinary language to solve a given problem is
called Algorithm.

 It may be possible to solve a problem in more than one ways, resulting in more than one
algorithm.

 Algorithms can solve many, but not all, problems

 Many problems can be solved in a reasonable time

 Some require heuristic (approximate) approaches to solve them in a reasonable time

 Some problems cannot be solved using any algorithm


4. Write the program

• Now we have to transform the algorithm from into a set of instructions that can be
understood by the computer.

• Writing a program is often called “writing code” or “implementing algorithm” . So


the source code is actually the program itself.

• Below is a program that implements our algorithm for finding the average of a set
of grades
5. Test the program
• Once you have a program written that compiles , you need to make sure that it solves the problem that it

was intended to solve and that the solutions are correct.


• What are Programming Bugs?

A software bug is an error or mistake that causes a computer program to misbehave. These bugs

are generally the result of mistakes made by the programmer either in the design or the source

code. Some are caused by compilers that generated invalid code.

• In other words, if an error is encountered during the test it can cause malfunction. For example, incorrect

data description, statements, input data, design, etc.


• If the output of your program is incorrect , it is possible that you did not convert your algorithm into

a proper program.

• You should fix as many bugs in your program as you can find.

• To find bugs effectively , you should test your program with many test cases .

• It is also a good idea to have others test your program because they may think up situations or input

data that you may never have thought of.

• The process of finding and fixing errors in your code is called debugging.
6. Evaluate the solution
• Evaluating the solution is an essential step in problem solving as it helps
determine the effectiveness, feasibility, and suitability of the proposed
solution.

• It involves assessing whether the solution addresses the underlying


problem, meets the desired objectives, and considers various factors such
as cost, resources, and potential risks.
• Once your program produces a result that seems correct , you need to re-consider

the original problem and make sure that the answer is formatted into a proper

solution to the problem. This process is known as evaluation.

• It is important to remember that the computer will only do what you told it to do.

It is up to you to interpret the results in a meaningful way and determine whether

or not it solves the original problem.


• Examine the feasibility of implementing the solution. Assess whether it can be
realistically implemented within the available resources, time constraints, and any
other limitations. Consider factors such as technical feasibility, resource availability,
expertise required, and any legal or ethical considerations.
7. Optimize and refine:

• Analyze the efficiency and performance of your


solution.
• Look for opportunities to optimize the code by
reducing time complexity or improving memory
usage.
• Refactor the code to make it more readable,
maintainable, and modular.
8. Document and maintain:

• Document your code by adding comments


and writing clear explanations of the logic
and functionality.
• This helps in understanding and maintaining
the code in the future.
9. Iterate and improve:

• If the solution does not meet all the


requirements or if there are additional
features to be implemented, iterate
through the problem-solving process again,
starting from step 1.
Types of algorithm representation
1. Pseudo code :

• Pseudocode is a simplified programming language-like notation that describes the


steps of an algorithm in a more structured manner.

• It uses a combination of natural language and basic programming constructs, such


as conditional statements, loops, and function calls.

• Pseudocode allows for a more detailed and precise representation of the algorithm
without getting into the specifics of a particular programming language.
2. Flow chart:
• Flowcharts use graphical symbols and arrows to represent the steps and
flow of an algorithm.
• Each symbol represents an action or decision point, and the arrows depict
the order in which the steps are executed.
• Flowcharts provide a visual representation of the algorithm's logic and can
be helpful in understanding the overall structure and flow of a solution.
Flow Chart for Structured Programming

• Flowchart is a graphical representation of an algorithm. Programmers


often use it as a program-planning tool to solve a problem. It makes
use of symbols which are connected among them to indicate the flow
of information and processing.

• In structured programming, flowcharts are commonly used to


represent the structure and control flow of a program.

• The process of drawing a flowchart for an algorithm is known as


“flowcharting”.
Basic Symbols used in Flowchart Designs

• Terminal: The oval symbol indicates Start, Stop and Halt in a


program’s logic flow. A pause/halt is generally used in a
program logic under some error conditions. Terminal is the
first and last symbols in the flowchart.
• Input/Output: A parallelogram denotes any function of
input/output type. Program instructions that take input from
input devices and display output on output devices are
indicated with parallelogram in a flowchart.
• Processing: A box represents arithmetic instructions. All
arithmetic processes such as adding, subtracting,
multiplication and division are indicated by action or process
symbol.
• Decision Diamond symbol represents a decision point.
Decision based operations such as yes/no question or
true/false are indicated by diamond in flowchart.
• Connectors: Whenever flowchart becomes complex or it
spreads over more than one page, it is useful to use connectors
to avoid any confusions. It is represented by a circle.

• Flow lines: Flow lines indicate the exact sequence in which


instructions are executed. Arrows represent the direction of
flow of control and relationship among different symbols of
flowchart.
Rules
For Creating Flowchart :
A flowchart is a graphical representation of an algorithm. It should follow
some rules while creating a flowchart

• Rule 1: Flowchart opening statement must be ‘start’ keyword.

• Rule 2: Flowchart ending statement must be ‘end’ keyword.

• Rule 3: All symbols in the flowchart must be connected with an arrow line.

• Rule 4: The decision symbol in the flowchart is associated with the arrow
line.
RULES FOR PSEUDOCODE
1. Write only one statement per line

• Each statement in your pseudo code should express just one action for the computer.

• If the task list is properly drawn, then in most cases each task will correspond to one
line of pseudo code.
2. Capitalize initial keyword

• READ and WRITE are in caps. There are just a few keywords we will use:

• READ, WRITE, IF, ELSE, ENDIF, WHILE, ENDWHILE, REPEAT, UNTIL


3. Indent to show hierarchy
• We will use a particular indentation pattern in each of the design structures:

• SEQUENCE: keep statements that are “stacked” in sequence all starting in the
same column.

• SELECTION: indent the statements that fall inside the selection structure, but not
the keywords that form the selection

• LOOPING: indent the statements that fall inside the loop, but not the keywords
that form the loop
4. End multiline structures

• The ENDIF (or END whatever) always is in line with the IF (or whatever starts the
structure).

• Use any of the END keywords to end multi-line sections (ENDIF, ENDWHILE).
5. Keep statements language independent

Resist the urge to write in whatever language you are most comfortable with. In the

long run, you will save time! There may be special features available in the language

you plan to eventually write the program in; if you are SURE it will be written in that

language, then you can use the features. If not, then avoid using the special features.
Advantages of Pseudo code
• Improves the readability of any approach. It’s one of the best approaches to start implementation
of an algorithm.

• Acts as a bridge between the program and the algorithm or flowchart. Also works as a rough
documentation, so the program of one developer can be understood easily when a pseudo code is
written out. In industries, the approach of documentation is essential. And that’s where a pseudo-
code proves vital.

• The main goal of a pseudo code is to explain what exactly each line of a program should do, hence
making the code construction phase easier for the programmer.
find area of a circle of radius r.
• Inputs to the algorithm: Radius r of the circle.
• Expected output : Area of the circle.
• Algorithm
• Step 1: start
Step 2: Read/input the radius r of the circle.
Step 3 : Area pi*r*r //calculation of area
Step 4 : Print Area.
Step 6 : End
• Inputs to the algorithm: First num1, Second num2
Write an
• Expected output : sum of two numbers
• Algorithm algorithm to
Step 1: start read two
Step 2 : read the first num1
Step 3 : read the second num2 numbers and
Step 4 : Sum ------ num1+num2 //calculation of sum find their sum
Step 5 : Print Sum
Step 6 : End
What is a Flowchart?

• Flowchart is a graphical representation of an algorithm. Programmers often


use it as a program-planning tool to solve a problem. It makes use of
symbols which are connected among them to indicate the flow of
information and processing.

• The process of drawing a flowchart for an algorithm is known as


“flowcharting”.
flowchart to calculate the average of two
numbers.
Example : Draw a flowchart to find the area of a
circle of radius r.

r*r
Write the algorithm and flow chart to convert temperature from
Fahrenheit to Celsius.

• Inputs to the algorithm : Temperature in Fahrenheit.


• Expected output : Temperature in Celsius.
• Algorithm
Step 1 : start
Step 2 : read temperature in Fahrenheit F
Step 3 : C5/9*(F - 32)
Step 4 : Print temperature in Celsius: C
Atep 5 : End.
Types of control sequences

• There are 3 types of control sequences in programming . They are :

– Sequences

– Branching ( Selection)

– Loop ( Repetition)
Write algorithm and draw flow chart to find the greater
number between two numbers.
• Algorithm
• Step 1 : start
• Step 2 : read / Input A and B READ

• Step 3 : If A greater than B then print A


• Step 4 : If B greater than A then print B
• Step 5 : End

PRIN
PRIN
T
T
Write algorithm and draw flow chart to find the
greater number between three numbers.
Inputs to the algorithm : Temperature in
Fahrenheit.
• Expected output : Temperature in Celsius.
• Algorithm
Step 1 : start
Step 2 : read / Input A ,B and C
Step 3 : If(A>=B) and (A>=C) then print A is the largest.
Step 4 : If(B>=A) and (B>=C) then print B is the largest.
Step 4 : If(C>=A) and (C>=B) then print A is the largest.
Step 5 : End
Example 1
• Write an algorithm to determine a student’s final
grade and indicate whether it is passing or failing. The
final grade is calculated as the average of four marks.
Pseudo code:
1. Start
2. Input a set of 4 marks
3. Calculate their average by summing and dividing by 4
4. if average is below 50 Print
“FAIL”
5. else
Print “PASS”
6. Stop
1. START:
2. Initialize variables:
- mark1, mark2, mark3, mark4: float (input marks obtained in four subjects)
- average: float (to store the calculated average)
- passingGrade: float (define the minimum passing grade, e.g., 50)
3. Input marks for four subjects:

4. Calculate the average:


- average = (mark1 + mark2 + mark3 + mark4) / 4

5. Check if the average is greater than or equal to passingGrade:


- IF average >= passingGrade:
- Display "Passing"
- ELSE:
- Display "Failing"

6. Print the final grade and the student's passing status


7. END
Example
• Write an algorithm to find the maximum element in an array
of integers. The function should take an array of integers as
input and return the maximum value present in the array.
Algorithm
1. Start the function findMaximumElement which takes an array of integers as

input.

2. Check if the array is empty:

If it is empty, return None as there is no maximum element.

3. Initialize a variable maxElement with the first element of the array.

4. Iterate through the array from the second element to the last element:

5. Compare each element with maxElement.

6. If the current element is greater than maxElement, update maxElement to

the current element.

7. After the loop ends, maxElement will hold the maximum value in the array.

8. Return maxElement as the result.


C For Loop Flowchart
Step 1: Start.

Step 2: Initialize variables.

Step 3: Check FOR condition.

Step 4: If the condition is true, then go to step 5 otherwise


go to step 7.

Step 5: f = f * i.

Step 6: Go to step 3.

Step 7: Print value of factorial.

Step 8: Stop.
Program to find all numbers
between 1 to 100 divisible by 4
Algorithm:
Step 1: Start

Step 2: Initialize variables

Step 3: For condition

Step 4: If condition. If it is true, then go to step


5 otherwise to step 7

Step 5: Print value

Step 6: Increment the value of "i" by 1

Step 7: Go to step 3

Step 8: Stop
How does the while loop work?
Step 1. The while loop evaluates the controlling expression.
Step 2. If the controlling expression is false, the body of the while
statement is never executed, and control skips the while statement and
jumps to the next statement in the program.
Step 3. If the controlling expression is true or any non zero value, then
control jump within the body of while loop and execute the statements
in a sequential way. Might be there is only a single statement attached
with a while loop.
Step 4. After the execution of while loop statements, the process is
repeated from step 1.
While Loops
do...while loop
do while loop
• The do while loop is a post tested loop. Using the do-
while loop, we can repeat the execution of several
parts of the statements. The do-while loop is mainly
used in the case where we need to execute the loop at
least once. The do-while loop is mostly used in menu-
driven programs where the termination condition
depends upon the end user.
Introduction to the C Language

Introduction to the C Language



C Has Become Very Popular for Various Reasons

o



Disadvantages of C

• C does not provide Object Oriented Programming (OOP) concepts.

• There are no concepts of Namespace in C.

• C does not provide binding or wrapping up of data in a single unit.

• C does not provide Constructor and Destructor.


o Difficult to debug.

o C allows a lot of freedom in writing code, and that is why you can put an empty line or white space
anywhere in the program. And because there is no fixed place to start or end the line, so it is
difficult to read and understand the program.

o C compilers can only identify errors and are incapable of handling exceptions (run-time errors).

o C provides no data protection.

o It also doesn't feature reusability of source code extensively.

o It does not provide strict data type checking

• (for example an integer value can be passed for floating data type).
1. Documentation Section

The documentation section is a part of the


program, where the programmer writes
everything about the program. Typically, the
programmer writes the name of the program,
about the author of the program and other details
such as the date, and the program description.
In short, it gives the reader an overview of the
program.

ATK
• /* File Name: program.c
• * Author: Programmer Name
• * date: 09/08/2019
• * description: a program to explain basic structure of c
programming
• *user enters the radius
• **/
• We usually use multiline Comments for documentation purposes.
Comments are ignored by the compiler.
2. Link Section
The link section of the program is used to declare all the header files that will
be used in the program the link section provides instructions to the compiler to
link functions from the system library.

#include<stdio.h>
#include<conio.h>
We use #include to declare header files in the link section.

ATK
3. Definition Section
This section of the program is used to declare the symbolic constant that will be
used in the program. A symbolic constant is a constant value given to a name
that can't be changed in the program.

#define NAME value


#define NAME (expression)
We use #define to declare the symbolic constant in the Definition Section.

NOTE: Do not put a semicolon (;) at the end of the #define statements.
ATK
4.Global Declaration section

The Global Declaration section is a part of the program, where the programmer
declares variables that are used in more than one function.

Such variables are called global variables. User-defined functions are also
declared in this part of the code.

ATK
5.Main function section

• The main function is the section from where the actual program begins.
• The main function begins with opening curly braces and ends with closing curly braces.
• The program should have one main function.

• The main function consists of two parts.


1. A declaration part
2. An execution part.
• Declaration part where all variables are declared that are used in the executable part.
• The executable part contains at least one statement. All statements in the declaration and
executable parts end with a semicolon.

ATK
6.Sub program:

The subprogram section is a part of the program, where the


programmer declares all user-defined functions to perform a specific
task. User-defined functions are usually posted soon after the main ()
function.

ATK
FIGURE The Greeting Program
ATK
FIGURE Structure of a C Program
ATK
How to Write and Run a C Program
in Linux
• Linux is an open-source and free operating system.

• We use Linux command-line tool, the Terminal, in order to compile a


program. To open the Terminal, you can use the Ctrl+Alt+T shortcut.

ATK
ATK
ATK
How to Write and Run a C Program in Windows
Step 1: Creating a Source Code

Source code is a file with C programming instructions in a high-level language. To create source code, we
use any text editor to write the program instructions. The instructions written in the source code must
follow the C programming language rules. The following steps are used to create a source code file in
Windows OS…
• Click on the Start button
• Select Run
• Type cmd and press Enter
• Type cd c:\TC\bin in the command prompt and press Enter
• Type TC press Enter
• Click on File -> New in C Editor window
• Type the program
• Save it as FileName.c (Use shortcut key F2 to save)
ATK
Step 2: Compile Source Code (Alt + F9)

The compilation is the process of converting high-level language instructions


into low-level language instructions. We use the shortcut key Alt + F9 to
compile a C program in Turbo C.

The compilation is the process of converting high-level language instructions


into low-level language instructions.

ATK
• Whenever we press Alt + F9, the source file is going to be
submitted to the Compiler.
• On receiving a source file, the compiler first checks for the Errors.
If there are any Errors then compiler returns List of Errors, if there
are no errors then the source code is converted into object
code and stores it as a file with .obj extension.
• Then the object code is given to the Linker. The Linker combines
both the object code and specified header file code and generates
an Executable file with a .exe extension

ATK
ATK
ATK
The file which contains c program instructions in a high-level
language is said to be source code. Every c program source file is
saved with .c extension, for example, Sample.c.

Whenever we press Alt + F9 the source file is submitted to the


compiler. Compiler checks for the errors, if there are any errors, it
returns a list of errors, otherwise generates object code in a file with
name Sample.obj and submit it to the linker. The linker combines
the code from specified header file into an object file and generates
executable file as Sample.exe. With this compilation process
completes.

Now, we need to run the executable file (Sample.exe). To run a


program we press Ctrl + F9. When we press Ctrl + F9 the
executable file is submitted to the CPU. Then CPU performs the
task according to the instructions written in that program and place
the result into UserScreen.
Comments in C
• Comments in C language are used to provide information about
lines of code. It is widely used for documenting code. There are
2 types of comments in the C language.
1. Single Line Comments
Single line comments are represented by double slash \\.
Let's see an example of a single line comment in C.
1. Multi-Line Comments
Multi-Line comments are represented by slash asterisk \*
... *\. It can occupy many lines of code, but it can't be
nested
printf() and scanf() in C

The printf() and scanf() functions are used for input and output in C language. Both functions
are inbuilt library functions, defined in stdio.h (header file).

printf() function
The printf() function is used for output. It prints the given statement to the console.
The syntax of printf() function is given below:

printf("format string",argument_list);

The format string can be %d (integer), %c (character), %s (string), %f (float) etc.


int a=10,b=20;//declaring 2 variable of integer type


float f=20.8;
char c='A';



Data Types in C
Signed Data Type
• A signed data type can represent both positive and negative numbers.
• The most significant bit (MSB) is used as the sign bit, indicating whether the
number is positive or negative.
• For example, in a 4-bit signed integer, the range of representable values is from -8
(-2^3) to 7 (2^3 - 1).

Unsigned Data Type


• An unsigned data type can represent only non-negative (zero and positive)
numbers.
• All bits are used to represent magnitude, and there is no sign bit.
• For example, in a 4-bit unsigned integer, the range of representable values is from
0 to 15 (2^4 - 1).
Types Data Types
Basic Data Type int, char, float, double
Derived Data Type array, pointer, structure,
union
Enumeration Data Type enum
Void Data Type void



Output

num1 (int): 1000


num2 (short): 200
Keywords in C
• A keyword is a reserved word. You cannot use it as a
variable name, constant name, etc. There are only 32
reserved words (keywords) in the C language.
• A list of 32 keywords in the c language is given below:

auto break case char const continue default do


double else enum extern float for goto if
int long register return short signed sizeof static
struct switch typedef union unsigned void volatile while


1. The first character of an identifier should be either an alphabet or an underscore,
and then it can be followed by any of the character, digit, or underscore.
2. It should not begin with any numerical digit.
3. In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can
say that identifiers are case sensitive.
4. Commas or blank spaces cannot be specified within an identifier.
5. Keywords cannot be represented as an identifier.
6. The length of the identifiers should not be more than 31 characters.
7. Identifiers should be written in such a way that it is meaningful, short, and easy to
read.
Keyword Identifier
Keyword is a pre-defined The identifier is a user-defined
word. word
It must be written in a It can be written in both
lowercase letter. lowercase and uppercase
letters.
Its meaning is pre-defined in Its meaning is not defined in
the c compiler. the c compiler.
It is a combination of It is a combination of
alphabetical characters. alphanumeric characters.
It does not contain the It can contain the underscore
underscore character. character.
C Operators

ATK
ATK
ATK
Relational Operators:


ATK
• Logical operators in C are used to perform logical
operations on Boolean expressions or values (true or
false).
• These operators are used in conditional statements to
combine multiple conditions and make decisions based
on the truth values of those conditions.
• The logical AND operator && takes two operands
(Boolean expressions) and returns 1 (true) if both
operands are true. Otherwise, it returns 0 (false).
• The logical OR operator || takes two operands
(Boolean expressions) and returns 1 (true) if at least
one of the operands is true. If both operands are
false, it returns 0 (false).
• The logical NOT operator ! takes a single operand
(Boolean expression) and returns 1 (true) if the
operand is false. If the operand is true, it returns 0
(false).
• It basically inverts the truth value of the operand.














#include <stdio.h>
int main() {
int num1, num2;
// Input two numbers
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
int greaterNumber = (num1 > num2) ? num1 : num2;
printf("The greater number is: %d\n", greaterNumber);
return 0;
}
Comma Operator:
, :


Type conversion

ATK

ATK
ATK
ATK
ATK
#include <stdio.h>

int main() {
// Implicit Type Conversion
int num1 = 5;
double num2 = 3.14;
double result = num1 + num2;
printf("Implicit Type Conversion:\n");
printf("num1 + num2 = %lf\n\n", result);

// Explicit Type Casting


double num3 = 10.75;
int num4;
num4 = (int)num3; // Explicitly cast double to int
printf("Explicit Type Casting:\n");
printf("num3 (double) = %lf\n", num3);
printf("num4 (int) = %d\n", num4);

return 0;
}
Mathematical functions
• C programming allows us to perform mathematical
operations through the functions defined in <math.h>
header file.

• The <math.h> header file contains various methods for


performing mathematical operations such as sqrt(),
pow(), ceil(), floor() etc.

presentation title 164


165
output

4.000000
4.000000
3.000000
3.000000
4.000000
2.645751
16.000000
27.000000
12
The absolute value of 1234 is 1234.000000
The absolute value of -344 is 344.000000
// C code to illustrate
// the use of fmod function
#include <math.h>
#include <stdio.h>
int main()
{
float a, b;
int c;
a = 8.2;
b = 5.7;
c = 3;
printf("Remainder of %f / %d is %lf\n", a, c,fmod(a, c));
printf("Remainder of %f / %f is %lf\n", a, b,fmod(a, b));
return (0);
}
Remainder of 8.200000 / 3 is 2.200000
Remainder of 8.200000 / 5.700000 is 2.500000
Square root of 225.000000 is 15.000000
Square root of 300.000000 is 17.320508
Value 8.0 ^ 3 = 512.000000
Value 3.05 ^ 1.98 = 9.097324


printf
• This function is used to print formatted output to the standard output
(usually the console).
• It takes a format string as the first argument and additional arguments for
the values to be displayed based on the format specifiers in the format
string.

178
scanf
• This function is used to read formatted input from the standard input (usually the
keyboard).
• It takes a format string as the first argument and pointers to the variables where the read
values should be stored based on the format specifiers in the format string.

#include <stdio.h>

int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("You entered: %d\n", num);
return 0;
}
getchar and putchar

• The int getchar(void) function reads the next available character from the screen and returns it as
an integer. This function reads only single character at a time. You can use this method in the loop
in case you want to read more than one character from the screen.
• The int putchar(int c) function puts the passed character on the screen and returns the same
character. This function puts only single character at a time. You can use this method in the loop in
case you want to display more than one character on the screen.
The gets() and puts() Functions
The char *gets(char *s) function reads a line from
stdin into the buffer pointed to by s until either a
terminating newline or EOF (End of File).
The int puts(const char *s) function writes the string
's' and 'a' trailing newline to stdout.
NOTE: Though it has been deprecated to use gets()
function, Instead of using gets, you want to use
fgets().

181
File I/O:
• C provides functions to perform I/O
operations on files. You can use
functions like fopen, fclose, fscanf,
fprintf, fgets, fputs, etc., for file
handling.

182
Precedence and associativity

presentation title 183


#include <stdio.h>

int main() {
int a = 5, b = 10, c = 15;
int result = a + b * c;
printf("Result: %d\n", result);
return 0;
}

184

You might also like