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

ICS Lecture 4-7

The document provides an overview of some key concepts in C programming including variables, data types, functions, operators, and the general structure of a C program. It also gives examples of writing simple C programs to convert between Fahrenheit and Celsius and find the largest of two numbers. The document discusses the typical program development cycle of analyzing a problem, designing an algorithmic solution, implementing the program, and testing and debugging it.

Uploaded by

priyanshuvrao
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)
32 views

ICS Lecture 4-7

The document provides an overview of some key concepts in C programming including variables, data types, functions, operators, and the general structure of a C program. It also gives examples of writing simple C programs to convert between Fahrenheit and Celsius and find the largest of two numbers. The document discusses the typical program development cycle of analyzing a problem, designing an algorithmic solution, implementing the program, and testing and debugging it.

Uploaded by

priyanshuvrao
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/ 57

ICS - Lecture

यिद आपको अंग्रेजी के कारण कोई समस्या आ रही है तो हमसे संपकर् करने में संकोच न करें

Slides are prepared from various sources on the web.


Int main (void) vs void main()
• int main() can be called with any number of arguments,
but int main(void) can only be called without any argument.
• Although it doesn’t make any difference most of the times,
using “int main(void)” is a recommended practice in C.
• Will discuss more when we will discuss functions
Reading values from keyboard

#include <stdio.h>
int main(void) {
int num ;
scanf ("%d", &num) ;
printf (“No. of students is %d\n”, num) ;
}
Common GCC file types
• .c -> C source code file.
• .h -> Header file contained in the program.
• .o -> Target file after compilation.
• .out -> Executable files, which do not have a fixed suffix. The
system distinguishes executable files from inexecutable files
based on file attributes. If the name of an executable file is
not given, GCC generates a file named a.out.
Compiling using GCC
• $ gcc test.c -o test
• ./test
Variables
• Must declare variables before use #include <stdio.h>
int main(void) {
• Variable declaration: int n; float phi;
int num ;
• int - integer data type
scanf ("%d", &num) ;
• float - floating-point data type printf (“No. of students is
• Many other types %d\n”, num) ;
}
• What are variables?
Variables
• Variables are containers for storing data values, like numbers
and characters in the memory. Can we change the content of a
container?

You can imagine


something like
this

How big container do we need to pack the content? Container type / Datatype
Variables
• A variable is a named storage location in the computer’s
memory.
• If we want to hold some value in memory for later use, we need to
use as variable.
• Variables have 3 characteristics:
• Name – the name we use in our code to refer to the memory location.
• Type – characteristic that defines what legal values the variable can
hold.
• Value – what is actually held inside of the memory location.
Data Types
• Types of Data Types in C - The C programming language has
two basic data types:
• Primary
• Derived
Datatypes: some built-in/primitive datatypes
• The datatype of a variable determines how much space it occupies in
memory and how the bit pattern stored is interpreted.
Datatypes: some built-in/primitive datatypes
• The datatype of a variable determines how much space it occupies in
memory and how the bit pattern stored is interpreted.
What would happen in 32 bit environment
What would happen in 32 bit environment
• In the table, the integer is 16-bit or 2 bytes wide. Thus, the
compiler is also 16-bit or 2 bytes wide.
• If the compiler was 32-bit wide, the int type size would have
been about 32-bits or 4 bytes.
• However, this might not be the case every single time.
• It is also possible that the integer size is 32-bits or 4 bytes
for a 64-bits processor. It entirely depends on the type of
compiler.
What would happen in 32 bit environment
• Int: 2,147,483,647 (\pm)
Pop Quiz - (correct/incorrect)

• int money$owed

Pop Quiz - (correct/incorrect)

• int money$owed
• int total_count

Pop Quiz - (correct/incorrect)

• int money$owed
• int total_count
• int score2

Pop Quiz - (correct/incorrect)

• int money$owed
• int total_count
• int score2
• int 2ndscore
Pop Quiz - (correct/incorrect)

• int money$owed
• int total_count
• int score2
• int 2ndscore
• int long
Pop Quiz - (correct/incorrect)

• int money$owed; (incorrect: cannot contain $)


• int total_count (correct)
• int score2 (correct)
• int 2ndscore (incorrect: must start with a letter)
• int long (incorrect: cannot use keyword)
#include <stdio.h> Format Specifiers
int main () Declaring variables
{ A few of them are as follows.
%c --- character
int a, b, c; %d --- Signed integer (%7d)
a = 5; %f --- Float values (%.3f)
%lf --- Long double
b = 6; %s --- Strings
%o --- Octal
c = a+b; Etc…………….
printf (“The sum is %d”, c);
} Assigning some value in the variables
Void
• Is a type, but not a data type.
• Functions can have a void return type, which means they do
not return a value.
• The parameter list of a function can also be void. It means
the function takes no parameters.
• For now, you can think of void more as a
placeholder for “nothing”.
Let us write some programs
• Convert Fahrenheit to Centigrade
• How you would go about it?
Fahrenheit to Centigrade
#include<stdio.h>
int main()
{
float cent, fahr;
scanf(“%f”,&fahr);
cent = ((fahr-32)*5/9);
printf("%f F = %f C", fahr, cent);
return 0;
}
Largest of two numbers
• How you would go about it?
Largest of two numbers
#include <stdio.h>
void main()
{
int x, y;
scanf(“%d%d”,&x,&y);
if (x>y) printf(“Largest is %d\n”,x);
else printf(“Largest is %d\n”,y);
}
The C Character Set
• The C language alphabet
• Uppercase letters ‘A’ to ‘Z’
• Lowercase letters ‘a’ to ‘z’
• Digits ‘0’ to ‘9’
• Certain special characters:
! # % ^ & * ( )
- _ + = ~ [ ] \
| ; : ‘ “ { } ,
. < > / ? blank

A C program should not contain anything else


Structure of a C program

• A collection of functions (we will see what they are later)


• Exactly one special function named main must be present.
Program always starts from there
• Each function has statements (instructions) for declaration,
assignment, condition check, looping etc.
• Statements are executed one by one
Operators in C

Operators are used to perform


operations on variables and values.

increments/ decrements the values by 1

mathematical operations such as add, sub, etc.


checks the relationship between two operands
An expression containing logical operator returns either 0 or 1 depending
upon whether expression results true or false.
Performs bit-level operations
Unary operator that returns the size of data
Assignment operator is used for assigning a value to a variable

Conditional - similar to if-else


Program Development Cycle
• Many programmers follow a sequence of Steps to create their
programs.

1. Analyze – Define the Problem


• Make sure that you understand what the program should do. What
should the user be able to enter? How? How does the program
come up with an answer? What does the program output? How?
• User – a person who uses a computer program.
• End User – the user that the program was made for.
Program Development Cycle
• Many programmers follow a sequence of Steps to create their programs.
1. Analyze – Define the Problem
• Make sure that you understand what the program should do. What should the
user be able to enter? How? How does the program come up with an answer?
What does the program output? How?
• User – a person who uses a computer program.
• End User – the user that the program was made for.

2. Design – Plan a Solution for the Problem


• Develop a PRECISE sequence of steps to solve the problem
• An algorithm is a precise sequence of steps to solve a problem.
Develop an Algorithm
• Imagine you want a program that tells a user how many
stamps they need in order to mail a certain number of pages.
• You need one stamp for every 5 pages
• 6 pages = 2 stamps
• 12 pages = 3 stamps
•…
• Write an algorithm (the steps needed) to solve this problem
Program Development Cycle – Design
• Typically a program follows three general steps
1. Input
2. Processing (Formulas)
3. Output

With this knowledge, try writing the algorithm


Algorithm for estimating number of stamps
required

1. Request the number of sheets of (input)


paper; call it Sheets.
Algorithm for estimating number of stamps
required

1. Request the number of sheets of (input)


paper; call it Sheets.
2. Divide Sheets by 5. (processing)
Algorithm for estimating number of stamps
required

1. Request the number of sheets of (input)


paper; call it Sheets.
2. Divide Sheets by 5. (processing)
3. Round the quotient up to the next (processing)
highest whole number; call it
Stamps.
Algorithm for estimating number of stamps
required

1. Request the number of sheets of paper; (input)


call it Sheets.
2. Divide Sheets by 5. (processing)
3. Round the quotient up to the next (processing)
highest whole number; call it Stamps.
4. Reply with the number Stamps. (output)
Program Development Cycle – Design
• Are those three steps enough?
• What about if the user enters “Banana” instead of a number of
sheets?
• The program does not know how to find the number of stamps
required to mail “Banana” number of sheets
• In order for the program to run without crashing, our algorithm must
make sure that the user inputs some valid data.
• There are two main ways of doing this:
1. Prevention – Making sure that the user is not physically able to enter in invalid data.
2. Validation – Allowing the user to enter invalid data, but checking it to make sure it is
valid before processing.
Program Development Cycle – Design
So, there are really 4 general steps most programs follow:
1. Input
1. Read Input
2. Validate Input
2. Process
3. Output
Develop an Algorithm, 3rd Attempt
• OK, now with THAT information, try developing the algorithm
Develop an Algorithm, 3rd Attempt
• OK, now with THAT information, try developing the algorithm
• One good algorithm developed could look like this:
1. Request the number of sheets of paper from the user; call it Sheets
(Input/Read)
2. Make sure Sheets is a positive whole number (Input/Validation)
3. Divide Sheets by 5 (Processing)
4. Round the result from step 3 up to the highest whole number; call it
Stamps (Processing)
5. Reply with the number Stamps (Output)
Programming Tools
• Flowcharts – A chart that consists of symbols connected by
arrows. Within each symbol is a phrase presenting the
activity at that step. The shape of the symbol indicates the
type of operation that is to occur.

• Pseudocode – an abbreviated plain English version of actual


computer code. Kind of a mix between English and code.
THERE IS NO OFFICIAL SYNTAX TO PSEUDOCODE.
Flow Charts
• Flow Line - indicates the flow of logic

• Terminal – indicates the start or end of a task

• Input/Output – used for input or output operations. What is


to be input or output should be in the figure.
Flow Charts
• Processing - used to show a processing step. The instructions are
displayed in the figure.

• Decision – used to show when a decision needs to be made. Lines for


yes and no come out of it. The question is displayed in the figure.

• Connector – Used to join flow lines.


Stamps Flowchart
Start

Read
Sheets

Display No Is sheets a
positive
whole
Error number?

Message Yes
Set Stamps
= Sheets/5

Round Stamps to
nearest whole
number

Display
Stamps

End
Pseudocode
and
Flowchart
Pseudocode
and
Flowchart
Program Development Cycle
3. Write the Code – Implement a solution
• The instructions in a programming language collectively called code.
• Your code should be a translation of your algorithm developed into the
programming language.
• In this class we use C, but there are many other programming languages: C++, C#,
Ruby, Python, Visual Basic, etc.

• This is the major focus of this course, but note that you need to be able
to think algorithmically in order to do this.
• Meaning, you need to be able to logically solve the problem in order to write a
program for it.
Program Development Cycle
4. Testing and Debugging – Locate and remove any errors in
the program

• Testing is the process of finding errors in a program


• Debugging is the process of removing errors in a program.
• An error in a program is called a bug.
• We will talk more specifically about the kinds of errors that can
occur in a program once we start programming.
Program Development Cycle
5. Complete All Documentation – Organize the material that
describes the program.
• Documentation is any material whose purpose is to allow another
person or programmer to use or understand the program
• Two kinds of documentation:
1. External Documentation – Material outside of the code files that describe the
program.
2. Internal Documentation – Lines inside of a code file that do nothing except
describe details of the program. In Java, these are called comments.
Write an algorithm to select what dress is
appropriate for a given outside temperature
Write an algorithm to select what dress is
appropriate for a given outside temperature
Control Statements
• Allow different sets of instructions to be executed
depending on whether certain conditions is evaluated
to be true or false.
• Also called branching.
• A Condition can an expression
• Expression = non-zero value ---> True
• Expression = Zero value ------> False
Syntax

if(expression)
{
//code to be executed
}
If-else: Control Statements (Cont.…)

Syntax

if(expression)
{
//Statements
}
else
{
//Statements
}
• IF without an else is possible.
• Else without an if is not possible.
if-else-if ladder: Control Statements (Cont.…)
if(condition1)
{
//statements
}
else if(condition2)
{
//statements
}
else if(condition3)
{
//statements
}
else
{ ***Dangling else problem
//statements
}
Determine dress
• if (temperature > 40)
• printf(“wear shorts”);
• else if (temperature >25)
• printf(“ideal weather - wear nice dress”);
• else if (if temperature > 10)
• printf(“chilly weather - wear warm cloths”);
• else
• printf(“stay inside”);
Nested if-else: Control Statements (Cont.…)

if( expression )
{
if( expression1 )
{
statement-block1;
}
else
{
statement-block 2;
}
}
else
{ Any levels of nested if-else is possible.
statement-block 3;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy