0% found this document useful (0 votes)
14 views33 pages

Course Book

Uploaded by

aungkyawmyatsep
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)
14 views33 pages

Course Book

Uploaded by

aungkyawmyatsep
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/ 33

C Programming Youth Hope Engineering Training Centre 09-898 599 994

Chapter (1)
Introduction to C
Welcome To C Programming
❖ C is a powerful computer programming language.
❖ C is appropriate for technically oriented people with little or no programming
experience.
❖ C is also for experienced programmers to use in building substantial
information systems.
❖ C is a general-purpose programming language and can efficiently work on
enterprise applications, games, graphics and applications requiring calculations,
etc.
Computer Organization (Six Logical Units)
1. Input Unit: “receiving” section.
2. Output Unit: “shipping” section.
3. Memory Unit: This rapid-access, relatively low-capacity “warehouse” section.
(Volatile)
4. Arithmetic and Logic Unit (ALU): “manufacturing”.
5. Central Processing Unit (CPU): “administrative” section.
6. Secondary storage Unit. This is the long-term, high-capacity “warehousing”
section. (persistent)
Typical C Development Environment
C programs typically go through six phases to be executed.
1. Creating a program
2. Processing a C program
3. Compiling a C program
4. Linking
5. Loading
6. Execution
C Programming Youth Hope Engineering Training Centre 09-898 599 994
C Programming Youth Hope Engineering Training Centre 09-898 599 994
Chapter (2)
Simple C Program

First Program in C: Printing a line of Text


#include<stdio.h>
int main(void)
{
printf(“Welcome to C!\n”);
return 0;
}
Welcome to C!

int main ( ) void main( )


Return type function No return type function

stdio standard input/output


Input read from keyboard
Output display on screen

{ printf(“Welcome to C!\n”); }
➢ The left brace, {, begins the body of every function.
➢ A corresponding right brace, }, ends function.
➢ This pair of braces and the portion of the program between the braces is called
a block.
➢ The block is an important program unit in C.
➢ The entire line, including printf, its argument within the parentheses and the
semicolon (;), is called a statement.
➢ Every statement must end with a semicolon (also known as the statement
terminator).
C Programming Youth Hope Engineering Training Centre 09-898 599 994
\n
➢ The backslash (\) is called an escape character.
➢ The compiler looks ahead at the next character and combines it with the
backslash to form an escape sequence.
➢ The escape sequence \n means newline.
return 0;
When the return statement is used at the end of main, the value 0 indicates that the
program has terminated successfully.
Some Common Escape Sequences

Escape Sequence Description

\n New line

\t Horizontal tab

\a Alert

\\ Backslash

\” Double quote

Eg 1: Using escape sequence


#include<stdio.h>
int main(void)
{
printf(“Welcome to C!\nAre you ready?\tBe Happy!”);
return 0;
}
C Programming Youth Hope Engineering Training Centre 09-898 599 994
Ex 1: Create a program that uses required escape sequences with single printf
statement. The output of the program is as follow:
*
***
*****
*
*
*
*
Ex 2: What does the following code print?
printf(“*\n**\n***\n****\n*****\n”);

Programming Terms
Keywords
• Keywords are predefined, reserved words in C language and each of which is
associated with specific features.
• These words help to use the functionality of C language.
• They have special meaning to the compilers.
• There are total 32 keywords in C.
auto, double, int, float, char, struct, break, continue, if, else, switch, case, for,
do, while, long, short, enum, register, typedef, extern, union, signed, unsigned,
void, return, static, const, default, goto, sizeof, volatile
Compilation
➢ Compiling is the transformation from Source Code (human readable) into object
code before it become an executable program.
➢ After the compiler has produced object code, it is passed through a linker.
➢ The linker combines the modules and gives real values to all symbolic
addresses, there by producing machine code.
C Programming Youth Hope Engineering Training Centre 09-898 599 994
Execution
➢ Execution is the process of running a program or the carrying out of the
operation called for by an instruction.
➢ Each instruction of a program is a description of a particular action which must
be carried out, in order for a specific problem to be solved.
➢ Execution involves repeatedly following a ‘fetch-decode-execute’ cycle for
each instruction.
➢ Programs may be executed in a bath process without human interaction or user
may type commands in an interactive session of an interpreter.
➢ The term run is used almost synonymously.

Expended Executable
C Program preprocessor compiler Assembly Code assembler Object Code linker loader
Source Code Code Execution
(simple.c) (simple.s) (simple.obj) (simple.exe)
(simple.i)

Fig. Compilation Process of C


Input and Output Statements
• The standard input/output header (<stdio.h>) contains information used by the
compiler.
• When compiling the program, the compiler calls to standard input/output library
functions such as scanf and printf.
➢ The printf standard library function displays information on the screen.
➢ The characters normally print exactly as they appear between the double quotes
in the printf statement.
➢ eg: printf(“C Programing Language.”);
➢ The scanf standard library function is used to obtain data from the keyboard
(user).
➢ eg: scanf(“%d”, &num); ampersand
➢ In this example, two arguments are included.
1. Format control string indicates the type of data (variable) that should be input
by the user.
2. Address operator (&) combined with the variable name (num), &num tells
scanf the location in memory at which variable is stored.
3. The %d conversion specifier indicates that the data should be an integer.
C Programming Youth Hope Engineering Training Centre 09-898 599 994

Some Conversion Specifiers

Exercises:
1. Input three integers and display on the screen.
2. Assume x=2 what is the output of the following statements.
(a) printf(“%d”, x);
(b) printf(“x = %d”, x);
( c) printf(“x = ”);
C Programming Youth Hope Engineering Training Centre 09-898 599 994

Chapter (3)
Arithmetic in C
Variables
• Variable name in C is any valid identifier.
• An identifier is a series of characters consisting of letters, digits and underscores
(_) that does not begin with a digit. Eg; integer, integer1, integer_1, 1integer.
• C is a case sensitive: upper case and lower case letters are different in C.
• A1 and a1 are different identifier.

• int integer1; is definition.


• The name integer1 is the name of variable.
• A variable is a location in memory where a value can be stored for use by the
program.
• The definition specifies that the variable integer1 is of type int, which means that
the variable will hold integer value, i.e., whole numbers such as 7, -11,0, 31914.
• All variables must be defined with a name and a data type immediately after the
left brace that begins the body of main before they can be used (any executable
statements) in a program.
Memory Concepts
• Variable names actually correspond to locations in the computer’s memory.
• Every variable has a name, a type and a value.
• scanf(“%d”, &integer1); is executed, the value typed by the user is placed into a
memory location to which the name integer1 has been assigned.
• Suppose the user enters the number 45 as the value for integer1.
The computer will place 45 into location integer1.
C Programming Youth Hope Engineering Training Centre 09-898 599 994
• Whenever a value is placed in a memory location, the value replaces the
previous value in that location.
• Placing a new value into a memory location is said to be destructive.
• When a value is read from a memory location, the process is said to be
nondestructive.

Rules of Operator Precedence


• Parentheses are used in C expressions in the same manner as in algebraic
expression for grouping subexpressions.
• C applies the operators in arithmetic expressions in a precise sequence
determined by the rules of operator precedence.

Table - Precedence of Arithmetic Operators.

Examples
C Programming Youth Hope Engineering Training Centre 09-898 599 994

Assignment Operator and Equality Operator


• Assignment Operator ( = ), should be read “gets” or “is assigned the value
of”.
• Right to left
• a = 2; >>>a is assigned the value of 2. a gets 2. int a;
• 2 >>> memory &a 2
• Equality Operator ( == ), should be read “double equal”.
• a == b; a double equal b, a is equal to b.
• &b 2
• int a;
• int b; Sum is 5
• int c;
• a = 2;
• b = 3;
• c = a + b; 2 + 3>>>5
• &c>>>5
printf(“Sum is %d”, c);

Adding Two Integers


• Inputs two integers from the keyboard and computes the sum of these values.
Prints the result using printf.
• Here is a simple input/output dialog.
C Programming Youth Hope Engineering Training Centre 09-898 599 994

Exercise
• Inputs two integers from the keyboard and computes the following
operations of these values. Prints the results of these operations using printf
functions.
• (1) Addition of two numbers. (2) Subtraction of the second number from
the first.
• (3) Multiplication of two numbers. (4) Division of first number by the
second.
• (5) Modulo division of first number by the second.
• Here is a simple input/output dialog.
C Programming Youth Hope Engineering Training Centre 09-898 599 994

Using <iostream.h>
• <iostream.h> is the header file used in C++ programming.
• It means to stream the input and output operation that is performed in the
programming.
• Fundamentally, the <iostream> library are two types named istream and ostream.
• istream represents the input and ostream represents output streams.
• Function of cout, cin and other related input and output function is defined in
this library.
Eg 1: #include<iostream.h>
int main(void)
{
int a;
a = 2;
cout<<"The value of a = “<<a;
return 0;
}
• The fatal error is appeared during execution time of the program as follow;
fatal error: iostream: No such file or directory |
• To solve the error with <iostream.h>, should use <iostream>.
• If that didn’t work put this statement after the header files. using namespace std;
Eg 2:#include<iostream>
using namespace std;
int main(void)
{
int a;
a = 2;
cout<<"The value of a = "<<a;
return 0;
C Programming Youth Hope Engineering Training Centre 09-898 599 994
}
✓ The program file is saved as .cpp.
Data Types in C
A data type specifies the type of data that a variable can store such as integer,
floating, character, etc.
➢ Basic
➢ Derived
➢ Enumeration
➢ Void

Memory Size of the Basic Data Types


➢ The basic data types are integer-based and floating-point based. C language
supports both signed and unsigned literals.
➢ The memory size of the basic data types may change according to 32 or 64-bit
operating system.
➢ Its size is given according to 32-bit architecture
C Programming Youth Hope Engineering Training Centre 09-898 599 994

Integer and Floating Point


C Programming Youth Hope Engineering Training Centre 09-898 599 994
C Programming Youth Hope Engineering Training Centre 09-898 599 994
C Programming Youth Hope Engineering Training Centre 09-898 599 994

Control Structures
Sequential execution
Normally, statements in a program are executed one after the other in the
order in which they’re written.
Transfer of control
Various C statements enable to specify that the next statement to be executed
may be other than the next one in the sequence.
There are three control structures:
1. the sequence structure
2. the selection structure
3. the repetition structure.
The sequence structure is built into C.
❖ C provides three types of selection structures in the form of statements.
❖ Single-selection statement: if statement.
C Programming Youth Hope Engineering Training Centre 09-898 599 994
❖ Double-selection statement: if … else statement.
❖ Multiple-selection statement: switch statement.
C provides three types of repetition structures in the form of statements.
1. for repetition statement.
2. while repetition statement.
3. do … while repetition statement.
C has only seven control statements: sequence, three types of selection and three
types of repetition.
The if Selection Statement

Single-selection statement

Example of the if Selection Statement


C Programming Youth Hope Engineering Training Centre 09-898 599 994

The if … else Selection Statement


Double-selection statement.

Example of if… else Selection Statement


C Programming Youth Hope Engineering Training Centre 09-898 599 994

Nested if … else Statements


if(condition1)
{statement1;}
elseif(condition2)
{statement2;}
else if(condition3)
{statement3;}
...
else {statement;}
Ex 1: Write a program to determine the grade of the test result for a student by
using if…else selection statement. The exam mark for a subject is read from
the keyboard and prints the result as grade.
If the exam mark is greater than or equal to 90, print “A”.
If the exam mark is greater than or equal to 80, print “B”.
If the exam mark is greater than or equal to 70, print “C”.
If the exam mark is greater than or equal to 60, print “D”.
If the exam mark is less than 60, print “F”.
C Programming Youth Hope Engineering Training Centre 09-898 599 994

Chapter (4)
Operators
Logical Operators
-To test multiple conditions in the process of making a decision, we had to perform
these tests in separate statements or in nested if or if…else statements.
-C provides logical operators that may be used to form more complex conditions by
combining simple conditions.
The logical operators are:
1. && (logical AND)
2. | | (logical OR )
3. ! (logical NOT also called logical negation)
&& Operator: two conditions are both truth.
| | Operator: two conditions that either or both of two conditions are true.

Truth table:
C Programming Youth Hope Engineering Training Centre 09-898 599 994

Example of Logical Operators

#include <stdio.h>
int main()
{
int a, b, c;
printf("Enter three integer numbers: ");
scanf("%d%d%d", &a, &b, &c);
if( a>b && b>c)
{
printf("%d is largest number.\n", a);
}
if(a>c && c>b)
{
printf("%d is largest number.\n", a);
}
if( b>a && a>c)
{
printf("%d is largest number.\n", b);
}
if(b>c && c>a)
{
printf("%d is largest number.\n", b);
}
if( c>b && b>a)
{
printf("%d is largest number.\n", c);
}
if( c>a && a>b)
{
printf("%d is largest number.\n", c);
}
return 0;
}
C Programming Youth Hope Engineering Training Centre 09-898 599 994

#include <stdio.h>
int main()
{
int a, b, c;
printf("Enter three integer numbers: ");
scanf("%d%d%d", &a, &b, &c);
if( a>b)
{
if(b>c)
printf("%d is largest number.\n", a);
}
if(a>c)
{
if(c>b)
printf("%d is largest number.\n", a);
}
if( b>a)
{
if(a>c)
C Programming Youth Hope Engineering Training Centre 09-898 599 994
printf("%d is largest number.\n", b);
}

if(b>c)
{
if(c>a)
printf("%d is largest number.\n", b);
}
if( c>b)
{
if(b>a)
printf("%d is largest number.\n", c);
}
if( c>a)
{
if(a>b)
printf("%d is largest number.\n", c);
}
return 0;
}
C Programming Youth Hope Engineering Training Centre 09-898 599 994
C Programming Youth Hope Engineering Training Centre 09-898 599 994

HomeWorks
Ex 4: Write a program to find the volume of the tank. ( volume = length * width *
height )
Ex 5: Write a program that inputs three different integers from the keyboard, then
prints the sum and average values of these numbers.

a, b, c →
sum = a + b + c →
avg = sum / no. of values →
avg = sum / 3
Data types for values are:
int for a, b, c, and sum
float for avg

The while Repetition Statement


A repetition statement allows to specify that an action is to be repeated while some
condition remains true.
C Programming Youth Hope Engineering Training Centre 09-898 599 994
Eg: Print the integer values of 1 to 5.
Example of using while
C Programming Youth Hope Engineering Training Centre 09-898 599 994
Counter-Controlled Repetition
A counter-controlled repetition is often called definite repetition.
The number of repetitions is known before the loop begins executing.
Eg: grade counter is less than or equal to ten.
C Programming Youth Hope Engineering Training Centre 09-898 599 994
C Programming Youth Hope Engineering Training Centre 09-898 599 994

e Class erage ro lem it Co nter Controlled epetition


: A class of ten students took a qui . The grades (integers in the range 0 to 00) for this qui
are available to you. Determine the class average on the qui . ere is a sample
input output dialog. np ts o e for co nt
de for grade inp t
o l for s m grade
e e for class a erage

nitiali ation
co nter 1
total
esting
co nter 1

peration tatements
total total grade
co nter co nter 1
a erage total 1
C Programming Youth Hope Engineering Training Centre 09-898 599 994
The Class Average Problem with Sentinel-Controlled Repetition
Eg 5: Develop a class averaging program that will process an arbitrary number of
grades each time the program run.
No indication is given of how many grades are to be entered.
How can the program determine when to stop the input of grades?
How will it know when to calculate and print the class average?
One way to solve this problem is to use a special value called a sentinel value to
indicate “end of data entry”.
Sentinel-controlled repetition is often called indefinite repetition because
the number of repetitions is not known before the loop begins executing.
C Programming Youth Hope Engineering Training Centre 09-898 599 994
#include<stdio.h>
int main(void)
{
int counter;
int grade;
int total;
int average;
total = 0;
counter = 1;
while( counter <= 10)
{
printf(“Enter grade: ”);
scanf(“%d”, &grade);
total = total + grade;
counter = counter + 1;
}
average = total / 10;
printf(“Class average is %d\n”, average);
return 0;
}
#include<stdio.h>
int main(void)
{
int counter;
int grade;
int total;
float average;
total = 0;
counter = 0;
C Programming Youth Hope Engineering Training Centre 09-898 599 994
printf(“Enter grade, -1 to end: ”);
scanf(“%d”, &grade);
while( grade != -1)
{
total = total + grade;
counter = counter +1;
printf(“Enter grade: ”);
scanf(“%d”, &grade);
}
counter=0 → grade input → 75
75 != -1
total = 0 + 75 = 75
counter = 0 + 1= 1
grade input → 94
→ 94 != -1
total = 75 + 94 = 169
counter = 1 + 1= 2
grade input → -1
→ -1 != -1 → end loop
counter = 2, total =169
counter != 0 → average = total / counter
= 169 / 2 = 84.5
Class average is 84.50

You might also like