0% found this document useful (0 votes)
38 views22 pages

Ilovepdf Merged

The document provides an introduction to C programming basics. It discusses the five stages of computer programming: problem statement, algorithm development, program coding, program testing, and program documentation. It then describes three common programming errors: syntax errors, run-time errors, and logic errors. The document proceeds to explain the general structure of a C program using the preprocessor, main function, and return statement. It also covers variable declaration, the seven basic C data types, and fundamental operators like assignment.
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)
38 views22 pages

Ilovepdf Merged

The document provides an introduction to C programming basics. It discusses the five stages of computer programming: problem statement, algorithm development, program coding, program testing, and program documentation. It then describes three common programming errors: syntax errors, run-time errors, and logic errors. The document proceeds to explain the general structure of a C program using the preprocessor, main function, and return statement. It also covers variable declaration, the seven basic C data types, and fundamental operators like assignment.
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/ 22

C Programming Basics

Introduction

Welcome to the world of programming! In this course, you will learn how to write a program using Turbo
C.

What is computer programming?

Computer programming is creating a sequence of instructions to enable the computer to do something.

Computer programming has five stages.

1. Problem statement. The programming process begins with a clear, written statement of the
problem to be solved by the computer.
2. Algorithm development: Once the problem has been clearly stated and all the requirements have
been understood, the next step is to develop the program logic necessary for accomplishing the
task.
An algorithm is defined as a logical sequence of steps that must be performed in order to
accomplish a given task.
Sample Tool: Flowchart
3. Program coding: When the programmer is satisfied with the efficacy of the logic developed in the
preceding step, it is time to convert that logic (in either flowchart or pseudocode form) to the
specific syntax of the programming language that will be used.
4. Program testing: The coded program is next checked for errors.
5. Program documentation: The programming process is complete when the program has been fully
documented.

Before we start with learning how to write C codes, let’s have first the three common programming errors.

1. Syntax error occurs when your code violates one or more grammar rules of C and is detected by
the compiler as it attempts to translate your program. Note that if a statement has a syntax error,
it cannot be translated and your program will not be executed.
2. Run-time error is a detected error and displayed by the compiler during the execution of the
program. It occurs when the program directs the computer to perform illegal operation, such as
dividing a number by zero or an attempt to perform an invalid operation, and detected during
program execution. When a run-time error occurs, the computer will stop executing your program
and will display a diagnostic message that indicates the line where the error was detected.
3. Logic Errors occur when a program follows a faulty algorithm. It does not cause a run-time error
and does not display error messages, so is very difficult to detect. The only sign of a logic error
may be incorrect program output.

Brief Turbo C History

Turbo C was developed by Dennis MacAlistair Ritchie at AT&T Bell Laboratories.

What is Turbo C?

Turbo C is an Integrated Development Environment and compiler for the C programming language from
Borland. First introduced in 1987, it was noted for its integrated development environment, small size,
extremely fast compile speed, comprehensive manuals and low price.
C Programming Basics

Turbo C General Structure

Let’s start!

The following is the Turbo C general structure.


Preprocessor Directives
int main(void){
local declarations
statements
}

The following is your first sample program.

#include <stdio.h>
int main(void) {
printf("Hello World!\n");
return 0;
}
Now, let’s understand the structure.

The C Preprocessor is a program that is executed before the source code is compiled.

Directives are how C preprocessor commands are called, and begin with a pound / hash symbol (#). No
white space should appear before the #, and a semi colon is NOT required at the end.

There are two directives in C, namely, include and define. For this section, we will first get to know and
use include.

#include gives program access to a library. It tells the preprocessor that some names used in the program
are found in the standard header file. It causes the preprocessor to insert definitions from a standard
header file into the program before compilation.

For example:

#include<stdio.h> tells the preprocessor to open the library “stdio.h” that contains built-in
functions like scanf and printf.

Every C program has a main function. This is where program execution begins. Note that you cannot
change the name of main.

Braces {} enclose the body of the function and indicate the beginning and end of the function main.

Main has two parts.

1. Declaration is the part of the program that tells the compiler the names of memory cells in a
program needed in the function, commonly data requirements identified during problem analysis.
C Programming Basics

Example:
int num1, num2, sum;

2. Executable statements are derived statements from the algorithm into machine language and
later executed.

Example:
printf(“Enter 2 numbers: ”);
scanf(“%d%d”,&num1,&num2);
sum = num1 + num2;
printf(“Sum = %d”,sum);
return 0;

The complete program is shown below.

Try this!

#include<stdio.h>
int main(void) {
int num1, num2, sum;
printf(“Enter 2 numbers: ”);
scanf(“%d%d”,&num1,&num2);
sum = num1 + num2;
printf(“Sum = %d”,sum);
return 0;
}

Note: The programs inside the textboxes are executable.


C Programming Basics

Variable Declaration

As a programmer, one of the most important things to consider is how to allocate memory that would
handle the data.

Variable declaration is a statement that communicates to the C compiler the names of all variables used
in the program and the kind of information stored in each variable. It also tells how that information will
be represented in memory.

In C, a variable is declared before a pre-defined function.

Here is the syntax for declaration:


Data type variable list;

Examples:
int x,age;
float sum,a,b;
char middle_intial;

What is a data type?

Data Type is a set of values and a set of operations that can be performed on those values.

The following are the standard pre-defined data types in C:

1. char

2. double

3. int

The three data types above have the following modifiers.

 short

 long

 signed

 unsigned

The modifiers define the amount of storage allocated to the variable. The amount of storage allocated is
not cast in stone. ANSI has the following rules:

short int <= int <= long int

float <= double <= long double

Seven Basic C Data Types:

1. Text (data type char) – made up of single characters (example x,#,9,E) and strings (“Hello”), usually
8 bits, or 1 byte with the range of 0 to 255.
C Programming Basics

2. Integer values – those numbers you learned to count with.

3. Floating-point values – numbers that have fractional portions such as 12.345, and exponents
1.2e+22.

4. Double-floating point values – have extended range of 1.7e-308 to 1.7e+308.

5. Enumerated data types – allow for user-defined data types.

6. void – signifies values that occupy 0 bit and have no value. You can also use this type to create
generic pointers.

7. Pointer – does not hold information as do the other data types. Instead, each pointer contains the
address of the memory location.

Explaining each of the data types:

int is used to define integer numbers.

Example:

int Count;

Count = 5;

float is used to define floating point numbers.

Example:

float Miles;

Miles = 5.6;

double is used to define BIG floating point numbers. It reserves twice the storage for the number.

Example:

double Atoms;

Atoms = 2500000;

char defines characters.

Example:

char Letter;

Letter = 'x';

What is a variable?

Variable is like a container in your computer's memory - you can store a value in it and retrieve or modify
it when necessary. It is associated with a memory cell whose value can change as the program executes.
C Programming Basics

A variable is an identifier. An identifier is name that identifies or labels the identity of an object. In C, the
following are the naming conventions for an identifier.

1. Names are made up of letters and digits.

2. The first character must be a letter.

3. C is case-sensitive, example ‘s’ is not the same with ‘S’.

4. The underscore symbol (_) is considered as a letter in C. It is not recommended to be used,


however, as the first character in a name.

5. At least the first 3 characters of a name are significant.

Examples:

Names... Example

CANNOT start with a number 2i

CAN contain a number elsewhere h2o

CANNOT contain any arithmetic operators... r*s+t

CANNOT contain any other punctuation marks... #@x%£!!a

CAN contain or begin with an underscore _height_

CANNOT be a C keyword struct

CANNOT contain a space im stupid

CAN be of mixed cases XSquared

The following is an example of a variable declaration.


int num;

Here is another one.

int num, num2;

Here is another one.


int num, num2, sum=0;

The previous example has a variable sum that is initialized during declaration.
Sequential Control Structure

Fundamental Commands and Operators

The following are the basic operators fundamental in the development of a program.

1. Equal sign (=) is called an assignment operator in C. It is the most basic operator where the value
on the right of the equal sign is assigned to the variable on the left.
The syntax of the use of the assignment operator is,
lvalue = rvalue;

The left value or lvalue is the destination variable, while the right value or rvalue can be a value, a
process or arithmetic expression, or a command that receives a value.

The following are some examples on how to use the assignment operator.

c = c + 1;

radius = 2 * diameter;

stat = getch();

2. The binary operators are arithmetic operators that take two operands and return a result.

Operator Use Result

+ op1 + op2 adds op1 to op2

- op1 - op2 subtracts op2 from op1

* op1 * op2 multiplies op1 by op2

/ op1 / op2 divides op1 by op2

% op1 % op2 computes the remainder from dividing op1 by op2

3. Address operator (&) returns the address of a variable. This operator is significant in the input
process when the command needs to get the address of a variable to know where to put the data
and when using a reference variable to indirectly access a value. The first use will be explained
briefly in the next lesson. The second use will not be discussed in this course.

Sample Program for the Fundamental Operators


Sequential Control Structure

Try this!

#include<stdio.h>
int main(void){
int c;
Output: 6
// Assign 5 to variable c.
c = 5;

// Add 1 to c and assign the result back to c.


c = c + 1;
printf(“%d”,c);
}

_____________________________________________________________________________________

Fundamental Input Command - scanf

The following are the basic commands fundamental in the development of a program.

scanf() is one of the Turbo C object streams that is used to accept data from the standard input,
usually the keyboard. Though it can accept any type of data, it has limits when used to input a
value other than numeric.

The following is the syntax of scanf.


scanf(“format specifier”, &var_name);

The data received from the standard input is assigned to the variable. The address operator returns
the address of the variable where to assign the data.

Format specifier defines the type of data to be accepted from the standard input. The list of format
specifiers for scanf is shown in the table below.

The following are examples on the use of scanf.


scanf(“%d”, &num1);
scanf(“%d%d”, &num1, &num2);

The first example assigns an integer value to num1 since %d is a format specifier for int and num1
should be of type int. The second example accepts two inputs, thus needs to have two formats.
The assignment of value is done by position. Whitespace input separates the values.

The following table summarizes the scanf format specifiers for each of the data types.
Sequential Control Structure

Date Types Format

long double %Lf

Double %lf

Float %f

unsigned long int %lu

long int %ld

unsigned int %u

Int %d

Short %hd

Char %c

_____________________________________________________________________________________

Try this!

#include<stdio.h> Input: 10
int main(void){ Output: 10
int num1;
//Input a value and assign it to variable
num1.
scanf("%d", &num1);
printf("%d", num1);
}
Sequential Control Structure

#include<stdio.h> Input: 5
int main(void){ 10
int num1, num2; Output: 5 10
//Input two integer values and assign them
to variables num1 and num2.
scanf("%d%d", &num1, &num2);
printf("%d %d", num1, num2);
}

_____________________________________________________________________________________

Fundamental Output Command - printf

printf() writes formatted output to the standard output device such as the monitor. It can be a
statement with either pure string expression, a formatted value or a mixed expression. A
formatted value is a value from a variable.

The following are syntaxes of printf.


printf(“string expression”);
printf(“format specifier”,var_name);
printf(“format specifier with string expression ”,var_name);

The following are examples of the use of printf.


printf(“Hello world”);
printf(“%d”,num1);
printf(“Value: %d”,num1);

The first example displays “Hello world”. The second statement displays the value of num1. The format is
%d if num1 is of type int. The third statement should display “Value: 10” if the value of num1 is 10.

Format specifier defines the type of data to be printed in the standard output. The list of format specifiers
for printf is shown in the table below.

The following table summarizes the printf format specifiers for each of the data types.

Date Types Format

long double %Lf


Sequential Control Structure

Double %f

Float %f

unsigned long int %lu

long int %ld

unsigned int %u

Int %d

Short %hd

Char %c

_____________________________________________________________________________________

Try this!

1. Displays the message “Hello world”.

#include<stdio.h> Hello world


int main(void){
printf("Hello world");
}

2. Displays the value of num1.

#include<stdio.h>
int main(void){ 5

int num1;
num1 = 5;
printf("%d",num1);
}
Sequential Control Structure

3. Displays the value of num1 with the message “The value of num1: __”.
#include<stdio.h>
int main(void){ The value of num1: 5
int num1;
num1 = 5;
printf("The value of num1: %d",num1);
}
Sequential Control Structure

We now proceed to defining a programming problem.

The following are the five steps.

1. Restate the problem.

2. Analyze the problem.

3. Identify the output.

4. Identify the input.

5. Identify the process.

In general, the following is the block diagram of the programming life cycle.

Input Process Output

Let us try solving a problem.

Write a program that accepts two integers and computes and displays their sum.

First, we define the programming problem. After restating and analyzing the problem, we do the last three
steps:

Identifying the output: sum

Identifying the inputs: two integers

Identifying the process: add / addition

Next, we identify the variables to use. Let us use

sum for sum,

num1 for the first integer, and

num2 for the second integer.

Always remember that you can use any variable name that best describes its meaning as long as it is not
a reserved word.

Finally, we write the code. We follow the correct structure of the C program as shown below.
Preprocessor Directives
int main(void){
local declarations
statements
}
Sequential Control Structure

Here is the algorithm. We skip directly to the content of the program. The directive and the main header
are pre-defined.

1. Declare the variables.

Variables should be declared using their appropriate data types, thus, we use int for all the
variables.

2. Then we follow the programming life cycle.


a. Read two integer values.
b. Add the two numbers.
c. Display the sum.

Here is the final program.


#include<stdio.h> //preprocessor directive
int main(void){ //function main header
int num1, num2,sum; //variable declarations
printf(“Enter two numbers: ”);
scanf(“%d”,&num1); //input
scanf(“%d”,&num2); //input
sum = num1 + num2; //process
printf(“Sum = %d”,sum); //output
}

Try it!

#include<stdio.h>
int main(void){
int num1, num2,sum;
printf(“Enter two numbers: ”);
scanf(“%d”,&num1);
scanf(“%d”,&num2);
sum = num1 + num2;
printf(“Sum = %d”,sum);
}
FLOWCHARTING
FLOWCHARTING

Flowchart - a graphical representation of the


solution in computing a problem in a logical
and step by step process.
- consists of geometrical symbol that are
interconnected to provide a pictorial
representation of data processing.
FLOWCHARTING SYMBOLS

1. Terminal Symbol
- used to designate the beginning and end of
a program.

2. Input Symbol
- represents an instruction to an input device
FLOWCHARTING SYMBOLS
3. Processing Symbol
- used to represent a group of program instructions that
perform a processing function or activity such as
mathematical operations or logical comparisons.

4. Output Symbol
- represents an instruction to an output device
FLOWCHARTING SYMBOLS

5. Decision Symbol
- denotes a point in the program where more than
one path can be taken or used to designate a
decision making process.

6. Flow lines and Arrowheads


- used to show reading order or sequence in which
flowchart symbols are to be lead.
- show the direction of processing of data flows.
FLOWCHARTING SYMBOLS

7. On-page Connector
- non processing symbol
- used to connect one part of the flowchart
to another without drawing flow lines.

A Denotes an Denotes an
entry A exit
FLOWCHARTING SYMBOLS

8. Off-page connector
- designate an exit or entry to page when a
flowchart requires more than one page.
9. Preparation Symbol
- commonly used for initialization of counters or
defining constants.
ALGORITHMS AND FLOWCHARTING

10. Predetermined Symbol


- used as a subroutine symbol
- inner procedure needs to be repeated several
times.

You might also like