05-Basics of C Programming

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

Basics of C Programming

Programming Fundamentals
§ Features of good programming design
§ Basics of C language
§ Data Types
§ Literals, Variables, and constants
§ Arithmetic operations (Precedence and Associativity)
§ Modularizing a Program
Features of Good Programming
Design
Programming style
§ Programming style is a term used to describe the effort a
programmer should take to make his or her code easy to read
and easy to understand.
§ Good organization of the code and meaningful variable
names help readability, and liberal use of comments can help
the reader understand what the program does and why.

§ Style Principle
“Structure and document your program the way you wish
other programmers would.”
Good Programming Practices

Indentation

Meaningful Variable Names

Internal Documentation

External Documentation

Miscellaneous Comments
Basics of C Language
History of C
UNIX developed c. 1969 -- DEC PDP-7 Assembly
Language

BCPL -- a user friendly OS providing powerful


development tools developed from BCPL. Assembler
tedious long and error prone. (Martin Richards)

A new language “B” a second attempt. c. 1970.


(Ken Thompson)

A totally new language “C” a successor to “B”.


c. 1971 (Dennis Ritchie)

By 1973 UNIX OS almost totally written in “C”.


Characteristics of C
§ Small size
§ Extensive use of function calls
§ Loose typing -- unlike PASCAL
§ Structured language
§ Low level (BitWise) programming readily available
§ Pointer implementation - extensive use of pointers for memory,
array, structures and functions.
Uses of C Language
§ It has high-level constructs.
§ It can handle low-level activities.
§ It produces efficient programs.
§ It can be compiled on a variety of computers.
Digital Machine
Computer System
(binary)

§ Source
§ Text form using the C statements
§ Compiler
§ Convert the source code to machine language

Source Code Target Code


Compiler
.c .exe
C Program Structures
§ Preprocessor Commands
§ Type definitions
§ Function prototypes -- declare function types and variables
passed to function.
§ Variables
§ Functions
C Program Structures
§ Function
§ Building blocks of C
§ Collection instruction that perform one or more task called
statements.
§ Arguments
§ Information passed from calling function to the called function
§ Braces { }
§ Block of codes, marks the beginning & end of the block of statements
§ Semi-colon ;
§ Terminator for each statements
C Program Structures
§ “Whitespace” Characters (enter, space, tab)
§ When used for alignment / comprehensible
§ C compiler don't pay much attention to these characters
§ Comments /* */ or //
§ Ignored by the compiler
§ Compiler Directive #
§ Tells the compiler that some very important info about the built-in
function used can be found in the file named.
C Program Structures
§ Header Files
§ Head of the program
§ main()
§ Main module of the program
§ First function called when program execution begins
§ C is a case sensitive language
Data Types
Types
§ Type defines a set of values and a set of operations that can
be applied on those values.
Types General Categories

C Types

Floating-
Void Integral Derived
point

Boolean Character Integer Real Imaginary Complex


Data Types
Bytes
Variable Type Keyword Range
Required
Character char 1 -128 to 127
Integer int 2 -32768 to 32767
-2147483648 to
Long integer long int 4
2147483647
Float float 4 1.2E-38 to 3.4E38
Double
double 8 2.2E-308 to 1.8E308
precision
Literals, Variables, and constants

UNIT 4: Programming Fundamentals


Variable Declaration
§ A variable is a named data storage location in your
computer’s memory. Variables in C can contain letters, digits
and the underscore character ( _ ). It should be remembered
that C language is case sensitive; two similar words in different
cases generate two different variables.

§ A variable declaration tells the compiler the name and type


of a variable and optionally initializes the variable to a specific
value. When a variable is declared, the compiler sets aside a
storage space for the variable.
Variable Declaration
§ Syntax

data_type variable_name;
Constants
§ Constants are data values that cannot be changed during
the execution of a program.

§ Constant Representation
§ Boolean constants
§ Character constants
§ Integer constants
§ Real constants
§ Complex constants
§ String constants
Coding Constants
§ Literal Constants
§ Unnamed constants used a specific data
§ Example: a = b +5;

§ Defined Constants
§ Use preprocessor command define; placed at the beginning of the
program
§ Example:
#define SALES_TAX_RATE .0825
Coding Constants
§ Memory Constants
§ Indicate that the data cannot be changed ; give a type and size to a
named object in memory

const type identifier = value;

§ Example: const float cPi = 3.14159;


Output Formatting
§ printf() – is a library function that displays information on-
screen. The statement can display a simple text message or a
message and the value of one or more program variables

§ system(“cls”) – clears the screen and place the cursor at the


upper left hand portion of the screen
Format Specifier
%c character %f float
%s string %f double
%hd short integer %Lf long double
%d integer %e exponential
%ld long integer %x hexadecimal
%lld long long integer %o octal
Input Formatting
§ scanf() – reads data from the keyboard according to a specified
format and assigns the input data to one or more program
variables. For numeric variables, the address can be passed by the
address of operator, the ampersand (&) that is placed at the
beginning of the variable name.

§ getch() / getche() – gets a character from the keyboard. It waits


until a key is pressed and then returns the inputted character to the
calling function. Unlike the scanf() function, getch/e() does not
wait for the carriage return key to be pressed.
Escape Sequences
\r carriage return
\n newline
\t move to the next tab
\a beep the speaker
\b backspace
\’ prints single quote
\” prints double quote
\\ prints backslash character
\xdd prints character which is in
hexadecimal form
Example
§ Write a program that uses defines constants for the vowels in
alphabet and memory constants for the even decimal digits
(0-9). It then prints the following three lines using literal
constants for the odd digits.

§ Program that ask an integer, float and character and print


them back in single printf statement.
Arithmetic operations (Precedence
and Associativity)

UNIT 4: Programming Fundamentals


Operators
§ An operator is a symbol that instructs the code to perform
some operations or actions on one or more operands.
§ C operators are categorized to several types:

Operators

Assignment Mathematical Relational Logical

Unary Binary
Assignment Operator
§ The assignment operator which is the equal sign ( = ). If you
write c = y in a C program, the value of y is assigned to c.

§ In assigning, the right side can be any expression and the left
side must be a variable name.
Mathematical Operators
§ C mathematical operators can be classified into two: unary
and binary

§ Unary operators
§ C has two unary operators: the increment and the decrement
§ Prefix or infix : ++x for increment and - - x for decrement
§ Postfix : x++ for increment and x - - for decrement
Mathematical Operators
§ Binary operators
§ Mathematical operators perform math operations such as:
§ addition ( + ), subtraction ( - ), multiplication ( * ), division ( / ) and
modulus ( % ).
Operator Precedence
§ An expression contains more than one operator. The order in
which operations are performed pose a significance. This
order is called operator precedence. Operations with higher
precedence are performed first when an expression is
evaluated.
Operators Relative Precedence
++ - - 1
* / % 2
+ - 3
§ If an expression contains more than one
operator with the same precedence level,
the operators are performed in left to right
order as they appear in the expression.

§ C also uses parentheses to modify the


evaluation order. A sub expression enclosed
in parentheses is evaluated first without
regard to operator precedence.
Relational Operators

Operator Symbol Example


Equal == X==‘A’
Not equal != A!=0
Less than < X<0
Greater than > y>10
Less than or equal to <= X<=20
Greater than or equal to >= Y>=100
Logical Operators

Operator Symbol Example

AND && var1 & & var2


OR || var1 | | var2
NOT ! !var1
Lab Exercises 1
ARITHMETIC OPERATORS
Modularizing a Program

UNIT 4: Programming Fundamentals


Functions
§ Building blocks of C

§ Function in C is an independent module that will be called to


do a specific task.

§ The execution of the programs always starts and ends with


main, but it can call other functions to do special task.
Functions
§ Structure Chart for a Program
Function Prototype declaration
§ Function Prototype

type_specifier function_name(parameter_declaration_list);

§ General form of a Function


type_specifier function_name(parameter_declaration_list)
{
body of the function
}
Function Prototype declaration
§ type_specifier
§ specifies the type of the value that function will return using the return
statement
§ default return an integer result

§ parameter_declaration_list
§ comma separated list of variable types & name that will receive the
values of the arguments when function is called
§ example: func (int x, int y, float z)
Function Arguments
NO RETURN VALUE, WITH PARAMETER

§ Example 1

#include<stdio.h>
void sqr (int x)
void sqr (int x);
main() {
{ prinft(“%d squared is %d”,x, x*x);
int num = 100;
getch();
sqr (num);
}
}
Function Arguments
NO RETURN VALUE, WITH PARAMETER
§ Example 2

#include<stdio.h>
void mul (int a, int b); void mul (int a, int b)
main() {
{ printf(“%d”, a*b);
mul (10, 11); getch();
} }
Function Returning Values
WITH RETURN VALUE, WITH PARAMETER
§ Example 1
#include<stdio.h>
int mul (int a, int b);
main()
{
int answer;
answer = mul (10, 11);
printf(“The answer is % d”, answer);
getch();
}
int mul (int a, int b)
{
return a*b;
}
Scope
§ Scope determines the region of the program in which a
defined object is visible, that is, the part of the program in
which you can use the its name.

§ A program in C has 2 possible regions of scope:


§ Global Scope Area – the visibility of objects defined in this area is
visible from its definition until the end of the program.
§ Local Scope Area – variables defined within a block have a local
scope. Local variables are in scope from their point of definition until
the end of their function or block.
Example
§ Programs reads a number and prints its square.

main

getNum sqrNum printSqr


Global Variables
§ example:
#include <stdio.h> func2 ()
int count; {
main() int count;
{ for(count = 1; count<=10;
count = 100; count ++)
func1(); printf(“.”);
} }

func1()
{
func2();
printf(“count is %d”, count);
}
Calling Functions
§ Call by Value
§ copies value of an argument into the formal parameter of the
subroutine

§ Call by Reference
§ the address of an argument is copied into the parameter
Calling Functions
§ Pointer Operator
§ Ampersand (&)
§ unary operator that returns the memory address of its operand (“the address of
”)

§ Asterisk (*)
§ returns the value of variable located at the address that follows (“value at
address”)
Call by Value
#include<stdio.h>
main()
{
int t=10;
printf(“%d %d”, sqr(t), t);
getch();
}

int sqr (int x)


{
x = x*x;
return x;
}
Call by Reference
#include<stdio.h>
main()
{
int x, y;
x = 10; y = 20;
printf(“Initial value of x & y: %d %d \n”, x, y);
swap(&x, &y);
printf(“Swapped Value of x & y: %d %d”, x, y);
getch();
}

void swap(int *x, int *y)


{
int temp;
temp = * x;
*x = *y;
* y = temp;
}
Lab Exercises 2
FUNCTIONS

You might also like