0% found this document useful (0 votes)
13 views85 pages

02-Introduction-to-C

Uploaded by

Annah Abrenica
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)
13 views85 pages

02-Introduction-to-C

Uploaded by

Annah Abrenica
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/ 85

INTRODUCTION TO C

Topic 02

Prepared by: Jay Vince D. Serato


Introduction to C
https://www.youtube.com/watch?v=yZg2L_ZSHsk

Prepared by: Jay Vince D. Serato


Introduction to C
Who have experienced C
programming?

Prepared by: Jay Vince D. Serato


Introduction to C
• C is a powerful and compact computer language that allows
you to write programs that specify exactly what you want your
computer to do.

• You’re in charge: you create a program, which is just a set of


instructions, and your computer will follow them.

Prepared by: Jay Vince D. Serato


Introduction to C
Introduction

Prepared by: Jay Vince D. Serato


Introduction to C
What is C?
• The simplest way to define C is to call it a computer
programming language, meaning you can write software
with it that a computer can execute.

• The result could be a large computer application, like your


Web browser, or a tiny set of instructions embedded in a
microprocessor or other computer component.

Prepared by: Jay Vince D. Serato


Introduction to C
History of C

Prepared by: Jay Vince D. Serato


Introduction to C
History of C
• The language C was developed in 1972 at
Bell Laboratories, primarily credited to the
work of Ken Thompson and Dennis Ritchie. Ken Thompson
born 04 February 1943

Dennis Ritchie
Sept 1941 – Dec 2011
Prepared by: Jay Vince D. Serato
Introduction to C
Why was it created?

• Programmers needed a more user-friendly set of


instructions for the UNIX operating system, which at the
time required programs written in assembly language.

• Assembly programs, which speak directly to a computer's


hardware, are long and difficult to debug, and they required
tedious, time-consuming work to add new features.

Prepared by: Jay Vince D. Serato


Introduction to C
Assembly Code Sample

Prepared by: Jay Vince D. Serato


Introduction to C
Why was it created?
• Thompson's first attempt at a high-level language was called
B, a tribute to the system programming language BCPL on
which it was based.

• When Bell Labs acquired a Digital Equipment Corporation


(DEC) UNIX system model PDP-11, Thompson reworked B to
better fit the demands of the newer, better system hardware.

Prepared by: Jay Vince D. Serato


Introduction to C
Why was it created?
• Thus, B's successor, C, was born.

• By 1973, C was stable enough that UNIX itself could be


rewritten using this innovative new higher-level language.

Prepared by: Jay Vince D. Serato


Introduction to C
Beyond Bell Labs
• Before C could be used effectively beyond Bell
Labs, other programmers needed a document
that explained how to use it.

• In 1978, the book "The C Programming


Language" by Brian Kernighan and Dennis
Ritchie, known by C enthusiasts as K&R or the
"White Book," became the definitive source for
C programming.

Prepared by: Jay Vince D. Serato


Introduction to C
Beyond Bell Labs
• To ensure that people didn't create their own dialects over
time, C developers worked through the 1980s to create
standards for the language.

• The U.S. standard for C, American National Standards


Institute (ANSI) standard X3.159-1989, became official in
1989.

Prepared by: Jay Vince D. Serato


Introduction to C
Beyond Bell Labs
• The International Organization for Standardization (ISO)
standard, ISO/IEC 9899:1990, followed in 1990.

• The versions of C after K&R reference these standards and


their later revisions (C89, C90 and C99).

• You might also see C89 referred to as "ANSI C," "ANSI/ISO C"
or "ISO C."

Prepared by: Jay Vince D. Serato


Introduction to C
C in the Developing World
• C and its use in UNIX was just one part of the boom in
operating system development through the 1980s.

• For all its improvements over its predecessors, though, C was


still not effortless to use for developing larger software
applications.

• As computers became more powerful, demand increased for


an easier programming experience.
Prepared by: Jay Vince D. Serato
Introduction to C
C in the Developing World
• This demand prompted programmers to build their
own compilers, and thus their own new
programming languages, using C.

• These new languages could simplify coding


complex tasks with lots of moving parts.

• For example, languages like C++ and Java, both


developed from C, simplified object-oriented
programming, a programming approach that
optimizes a programmer's ability to reuse code.
Prepared by: Jay Vince D. Serato
Introduction to C
Creating C Programs

Prepared by: Jay Vince D. Serato


Introduction to C
Four Fundamental Stages
• Editing

• Compiling

• Linking

• Executing

Prepared by: Jay Vince D. Serato


Introduction to C
Editing
• This is the process of creating and modifying C source code.

• The editor often provides a complete environment for


writing, managing, developing, and testing your programs.

• This is sometimes called an integrated development


environment, or IDE.

Prepared by: Jay Vince D. Serato


Introduction to C
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.

• The compiler can detect a wide range of errors that are due to
invalid or unrecognized program code, as well as structural
errors where, for example, part of a program can never be
executed.
Prepared by: Jay Vince D. Serato
Introduction to C
Compiling

• The output from the compiler is known as object code and is


stored in files called object files, which usually have names
with the extension .obj in the Microsoft Windows
environment, or .o in the Linux/UNIX environment.

Prepared by: Jay Vince D. Serato


Introduction to C
Linking
• The linker combines the various modules generated by the
compiler from source code files, adds required code
modules from program libraries supplied as part of C, and
welds everything into an executable whole.

• The linker can also detect and report errors, for example, if
part of your program is missing or a nonexistent library
component is referenced.

Prepared by: Jay Vince D. Serato


Introduction to C
Executing

• The execution stage is where you run your program, having


completed all the previous processes successfully.

Prepared by: Jay Vince D. Serato


Introduction to C
Four Fundamental Stages

Prepared by: Jay Vince D. Serato


Introduction to C
Creating your First Program

Prepared by: Jay Vince D. Serato


Introduction to C
Step One
• Open your IDE (i.e. Dev-C++)

Prepared by: Jay Vince D. Serato


Introduction to C
Step Two (Your first program)
• Type exactly what is here:

#include <stdio.h>

int main(void)
{
printf("Hello world!");
return 0;
}
Prepared by: Jay Vince D. Serato
Introduction to C
Step Two (Your second
• Type exactly what is here:
program)

#include <stdio.h>

int main(void)
{
printf(“Don\’t give up! Try and try again!");
return 0;
}

Prepared by: Jay Vince D. Serato


Introduction to C
Step Two (Your third
• Type exactly what is here:
program)

#include <stdio.h> /* This is a preprocessor directive */


int main(void) /* This identifies the function main() */
{ /* This marks the beginning of main() */

printf("Beware!"); /* This line displays a text */


return 0; /* This returns control to the operating system */
} /* This marks the end of main() */

Prepared by: Jay Vince D. Serato


Introduction to C
Comments
• This isn’t actually part of the program code, in that it isn’t
telling the computer to do anything.

• It’s simply a comment, and it’s there to remind you, or


someone else reading your code, what the program does.

Prepared by: Jay Vince D. Serato


Introduction to C
Comments
• Anything between /* and */ or anything that starts with // is
treated as a comment.

• As soon as your compiler finds /* in your source file, it will


simply ignore anything that follows (even if the text looks
like program code) until it finds the matching */ that marks the
end of the comment.

• As soon as your compiler finds // in your source file, it will


simply ignore anything that follows until the end of the line.

Prepared by: Jay Vince D. Serato


Introduction to C
Your third program
#include <stdio.h> /* This is a preprocessor directive */

int main(void) /* This identifies the function main() */


{ /* This marks the beginning of main() */

printf("Beware!"); /* This line displays a text */


return 0; /* This returns control to the operating system */
} /* This marks the end of main() */

Prepared by: Jay Vince D. Serato


Introduction to C
Preprocessor Directives
• #include <stdio.h>
• #define AGE 20

• The preprocessor directives are commands that give


instructions to the C preprocessor, whose job it is to modify
the text of a C program before it is compiled.

• A preprocessor directive begins with a number symbol (#) as


its first nonblank character.
Prepared by: Jay Vince D. Serato
Introduction to C
Preprocessor Directives
• #include <stdio.h>

• The C language explicitly defines only a small number of


operations: Many actions that are necessary in a computer
program are not defined directly by C.

• Instead, every C implementation contains collections of useful


functions and symbols called libraries.

Prepared by: Jay Vince D. Serato


Introduction to C
Preprocessor Directives
• #include <stdio.h>

• The #include directive gives a program access to a library.

• This directive causes the preprocessor to insert definitions


from a standard header file into a program before
compilation.

Prepared by: Jay Vince D. Serato


Introduction to C
Preprocessor Directives
• #include <stdio.h>

• The directive
#include <stdio.h> /* printf definitions */
notifies the preprocessor that some names used in the
program (such as printf) are found in the standard header
file <stdio.h>.

Prepared by: Jay Vince D. Serato


Introduction to C
Preprocessor Directives
• #define PI 3.14159

• The #define directive associates the constant macro PI with


the meaning 3.14159.

• This directive instructs the preprocessor to replace each


occurrence of PI in the text of the C program by 3.14159
before compilation begins.

Prepared by: Jay Vince D. Serato


Introduction to C
Your third program
#include <stdio.h> /* This is a preprocessor directive */

int main(void) /* This identifies the function main() */


{ /* This marks the beginning of main() */

printf("Beware!"); /* This line displays a text */


return 0; /* This returns control to the operating system */
} /* This marks the end of main() */

Prepared by: Jay Vince D. Serato


Introduction to C
Main() Function
• A function is just a named block of code between braces that
carries out some specific set of operations.

• Every C program consists of one or more functions, and


every C program must contain a function called main().

• The main() function dictates the execution.

Prepared by: Jay Vince D. Serato


Introduction to C
Main() Function

• The function body is the bit between the opening and closing
braces that follow the line where the function name appears.

• The function body contains all the statements that define


what the function does.

Prepared by: Jay Vince D. Serato


Introduction to C
Main() Function
• End execution of the main() function and specify the value to
be returned in the statement:
return 0; /* This returns control to the operating system */

• This is a return statement that ends execution of the main()


function and returns that value 0 to the operating system.

• You return a zero value from main() to indicate that the


program terminated normally.
Prepared by: Jay Vince D. Serato
Introduction to C
Main() Function

Prepared by: Jay Vince D. Serato


Introduction to C
Outputting Information
• The body of the main() function in the example includes a
statement that calls the printf() function:
printf("Beware!"); /* This line displays a text */

• printf() is a standard library function, and it outputs


information to the display screen based on what appears
between the parentheses that immediately follow the function
name.

Prepared by: Jay Vince D. Serato


Introduction to C
Arguments
printf("Beware!"); /* This line displays a text */

• Items enclosed between the parentheses following a


function name, as with the printf() function in the above
statement, are called arguments, which specify data that is to
be passed to the function.

• When there is more than one argument to a function, they


must be separated by commas.
Prepared by: Jay Vince D. Serato
Introduction to C
Control Characters
• You could alter the program to display two sentences on
separate lines. Try typing in the following code:

#include <stdio.h>
int main(void) {
printf("\nMy formula for success?\nRise early.");
return 0;
}

Prepared by: Jay Vince D. Serato


Introduction to C
Control Characters
• \n Represents a newline
character • \a Inserts a bell (alert) character
• \r Represents a carriage return • \? Inserts a question mark (?)
• \b Represents a backspace • \“ Inserts a double quote (")
• \t Represents a horizontal tab • \’ Inserts a single quote (‘)
• \v Represents a vertical tab • \\ Inserts a backslash (\)

Prepared by: Jay Vince D. Serato


Introduction to C
Activity
• Try to print the following text:

"It is a wise father that knows his own child." Shakespeare

Prepared by: Jay Vince D. Serato


Introduction to C
How to write?

Prepared by: Jay Vince D. Serato


Introduction to C
Basic Steps
• Understanding the Problem

• Detailed Design

• Implementation

• Testing

Prepared by: Jay Vince D. Serato


Introduction to C
Understanding the Problem
• Get a clear idea on what to do

• Before coding, get a paper, write down the problem, think


about the possible solutions

• Translate your solutions into code

Prepared by: Jay Vince D. Serato


Introduction to C
Detailed Design

• Specify what the program does by dividing it into a set of


well-defined and manageable chunks that are reasonably
self-contained

Prepared by: Jay Vince D. Serato


Introduction to C
Implementation
• Write the source code one unit at a time.

• As one part is completed, you can write


the code for the next.

• Each part will be based on the detailed


design specifications, and you’ll verify
that each piece works, as much as you
can, before proceeding.

Prepared by: Jay Vince D. Serato


Introduction to C
Testing
• Each of your program modules—the pieces that make up your
program—will need to be tested individually.

• When they don’t work properly, you need to debug them.

Prepared by: Jay Vince D. Serato


Introduction to C
Testing
• Debugging is the process of finding and correcting errors
in your program.

• This term is said to have originated in the days when finding


the errors in a program involved tracing where the
information went and how it was processed by using the
circuit diagram for the computer.

Prepared by: Jay Vince D. Serato


Introduction to C
First Steps in Programming

Prepared by: Jay Vince D. Serato


Introduction to C
Variables
• A variable is a specific piece of memory in your computer
that consists of one or more contiguous bytes.

• Every variable has a name, and you can use that name to refer
to that place in memory to retrieve what it contains or store a
new data value there.

Prepared by: Jay Vince D. Serato


Introduction to C
Data Types
• A data type is a set of values and a set of operations on
those values.

• Knowledge of the data type of an item (a variable or value)


enables the C compiler to correctly specify operations on
that item.

• A standard data type in C is a data type that is predefined,


such as char, double, and int.
Prepared by: Jay Vince D. Serato
Introduction to C
Data Types: Integer Types
• Integer-type holds integer variables.
Integer Types Value Range
short -32,767 to 32,767
unsigned short 0 to 65,535
int -2,147,183,647 to 2,147,183,647
unsigned 0 to 4,294,967,295
long -2,147,183,647 to 2,147,183,647
unsigned long 0 to 4,294,967,295

Prepared by: Jay Vince D. Serato


Introduction to C
Data Types: Floating-Point Types
• Floating-Point-type holds numbers with decimals.
Floating Point Types Approximate Value Range Significant Digits
float 10−37 to 1038 6
double 10−307 to 10308 15
long double 10−4931 to 104932 19

Prepared by: Jay Vince D. Serato


Introduction to C
Data Types: Character Types
• Data type char represents an individual character value—a
letter, a digit, or a special symbol.

• Each type char value is enclosed in apostrophes (single


quotes) as shown here:

'A' 'z' '2' '9' '*' ':' '"' ' '

Prepared by: Jay Vince D. Serato


Introduction to C
ASCII Codes
• You should know that a character is represented in memory as
an integer.

• The value stored is determined by the code used by your C


compiler. The ASCII code (American Standard Code for
Information Interchange) is the most common.

Prepared by: Jay Vince D. Serato


Introduction to C
ASCII Codes
• The digit characters '0' through '9' have code values of 48
through 57 (decimal).

• The order relationship that follows holds for the digit


characters (i.e., '0' < '1' , '1' < '2' , and so on).

Prepared by: Jay Vince D. Serato


Introduction to C
ASCII Codes
• In ASCII, uppercase letters have the decimal code values 65
through 90.

• The order relationship that follows holds for uppercase letters.


'A' < 'B' < 'C' < ... < 'X' < 'Y' < 'Z’

• Lowercase letters have the consecutive decimal code values


97 through 122, and the following order relationship holds:
'a' < 'b' < 'c' < ... < 'x' < 'y' < 'z'
Prepared by: Jay Vince D. Serato
Introduction to C
ASCII Codes

Prepared by: Jay Vince D. Serato


Introduction to C
Naming Variables
• The name that 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
begins with a letter (incidentally, the underscore character
counts as a letter).

Prepared by: Jay Vince D. Serato


Introduction to C
Naming Variables
• Examples of legal variable names are as follows:
• Radius
• diameter
• Auntie_May
• D678

• Variable name can’t begin with a digit, it can’t include any


other characters besides letters, underscores and digits.
• It is also case-sensitive.
• Declare first the variable before you can use it.
Prepared by: Jay Vince D. Serato
Introduction to C
Program 2.1 – Using a Variable
#include <stdio.h>
int main(void) {
int a = 5; /* Declare a variable called a */
int b = 10; /* Declare a variable called b */
int sum; /* Declare a variable called sum */
sum = a + b; /* A simple arithmetic assignment statement */
printf(“The sum is %d.", sum);
return 0;
}

Prepared by: Jay Vince D. Serato


Introduction to C
Assignment Statement
• An assignment statement stores a value or a computational result
in a variable and is used to perform most arithmetic operations in
a program.

• The assignment statement


sum = a + b;
assigns a value to the variable sum.
• The value assigned is the result of the sum of the variable a and the
variable b.

• The memory cell for a and b must contain valid information (in this
case, a real number) before the assignment statement is executed.
Prepared by: Jay Vince D. Serato
Introduction to C
Assignment
#include <stdio.h>
Operators
int main(void) {
int Total_Pets;
int Cats;
int Dogs;
int Ponies;
int Others;
/* Set the number of each kind of pet */
Cats = 2;
Dogs = 1;
Ponies = 1;
Others = 46;
/* Calculate the total number of pets */
Total_Pets = Cats + Dogs + Ponies + Others;
printf("We have %d pets in total", Total_Pets); /* Output the result */
return 0;
Prepared by: Jay Vince D. Serato
} Introduction to C
The / and % Operators
• When an int is divided by an int, its result is the closest
integer less than or equal to the answer.

• 5.0 / 2.0 = 2.5


• 5/2 = 2

• 49.0/10.0 = 4.9
• 49/10 = 4

Prepared by: Jay Vince D. Serato


Introduction to C
The / and % operator
• When an int a is applied a modulo operator (%) to another
int b, it will result to the remainder of a/b.

• 15%10 = 5
• 16%4 = 0
• 91%9 = 1

Prepared by: Jay Vince D. Serato


Introduction to C
The / and
#include <stdio.h>
% operator
int main(void) {
int cookies = 45; /* Number of cookies in the jar */
int children = 7; /* Number of children */
int cookies_per_child = 0; /* Number of cookies per child */
int cookies_left_over = 0; /* Number of cookies left over */

/* Calculate how many cookies each child gets when they are divided up */
cookies_per_child = cookies/children; /* Number of cookies per child */
printf("You have %d children and %d cookies", children, cookies);
printf("\nGive each child %d cookies.", cookies_per_child);
/* Calculate how many cookies are left over */
cookies_left_over = cookies%children;
printf("\nThere are %d cookies left over.\n", cookies_left_over);
return 0;
}
Prepared by: Jay Vince D. Serato
Introduction to C
Input/Output Operations

Prepared by: Jay Vince D. Serato


Introduction to C
Input/Output Operations
• You copy data into a variable if you want a program to
manipulate different data each time it executes.
• This data transfer from the outside world into memory is
called an input operation.

• As it executes, a program performs computations and stores


the results in memory.
• These program results can be displayed to the program user
by an output operation.
Prepared by: Jay Vince D. Serato
Introduction to C
Input/Output Operations
• All input/output operations in C are performed by special
program units called input/output functions.

• The most common input/output functions are supplied as part


of the C standard input/output library to which we gain
access through the preprocessor directive:
#include <stdio.h>

Prepared by: Jay Vince D. Serato


Introduction to C
printf() Function
• To see the results of a program execution, we must have a way
to specify what variable values should be displayed.

printf(“The sum is %d.", sum);

• A function call consists of two parts: the function name and


the function arguments, enclosed in parentheses.

• The arguments for printf consist of a format string (in quotes)


and a print list (the variable sum).
Prepared by: Jay Vince D. Serato
Introduction to C
printf() Function
printf(“The sum is %d.", sum);

• The function call above displays the line


The sum is 15.
which is the result of displaying the format string “The sum is
%d." after substituting the value of sum for its placeholder
(%d) in the format string.
• A placeholder always begins with the symbol %. Here the
placeholder %d marks the display position for a type integer
variable.
Prepared by: Jay Vince D. Serato
Introduction to C
printf() Function
Placeholder Variable Type Function Use
%c char printf/scanf
%d int printf/scanf
%f double printf
%lf double scanf

Prepared by: Jay Vince D. Serato


Introduction to C
Using more variables
#include <stdio.h>
int main(void) {
int brothers; /* Declare a variable called brothers */
int brides; /* and a variable called brides */
brothers = 7; /* Store 7 in the variable brothers */ brides = 7; /* Store 7
in the variable brides */
/* Display some output */
printf("%d brides for %d brothers", brides, brothers);
return 0;
}
Prepared by: Jay Vince D. Serato
Introduction to C
More functionalities
#include <stdio.h>
int main(void) {
int cookies = 5;
int cookie_calories = 125; /* Calories per cookie */
int total_eaten = 0; /* Total cookies eaten */
int eaten = 2; /* Number to be eaten */
cookies = cookies - eaten; /* Subtract number eaten from cookies */
total_eaten = total_eaten + eaten;
printf("I have eaten %d cookies. There are %d cookies left", eaten, cookies);

eaten = 3; /* New value for cookies to be eaten */


cookies = cookies - eaten; /* Subtract number eaten from cookies */
total_eaten = total_eaten + eaten;
printf("\nI have eaten %d more. Now there are %d cookies left\n", eaten, cookies);
printf("\nTotal energy consumed is %d calories.\n", total_eaten*cookie_calories);
return 0;
Prepared by: Jay Vince D. Serato
} Introduction to C
Program 2.2 – Using scanf()
#include <stdio.h>
int main(void) {
int a; /* Declare a variable called a */
int b; /* Declare a variable called b */
int sum; /* Declare a variable called sum */
scanf(“%d”, &a);
scanf(“%d”, &b);
sum = a + b; /* A simple arithmetic assignment statement */
printf(“The sum is %d.", sum);
return 0;
}
Prepared by: Jay Vince D. Serato
Introduction to C
scanf() Function
• The statement
scanf("%d", &a);
calls function scanf to copy data into the variable a.

• Where does function scanf get the data it stores in the


variable a?
• It copies the data from the standard input device.
• In most cases the standard input device is the keyboard;
consequently, the computer will attempt to store in a whatever data
the program user types at the keyboard.
Prepared by: Jay Vince D. Serato
Introduction to C
scanf() Function
scanf("%d", &a);
• Notice that in a call to scanf, the name of each variable that is
to be given a value is preceded by the ampersand character
(&).

• The & is the C address-of operator.


• In the context of this input operation, the & operator tells the
scanf function where to find each variable into which it is to
store a new value.
Prepared by: Jay Vince D. Serato
Introduction to C
Quiz

Prepared by: Jay Vince D. Serato


Introduction to C

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