KEMBAR78
C programing language fundamentals in comouter.pptx
LECTURER: ENG. RAITONAMBELE
OIT 136- C/C++ Tutorial
Outline
 History of C programming
 What is C - Programming
 “HelloWorld" Program
 DataTypes &Variables
 printf()
 Arithmetic & Logical
Operations
 Conditionals
 Loops
 Arrays & Strings
 Pointers
 Functions
 Command-Line Argument
 Data Structure
 Memory Allocation
 Programming Tips
 C vs. C++
 Books recommended
History of C
1960:ALGOL (ALGOrithmic Language)
1967: BCPL (Basic Combined Programming Language)
1970: B programming language (typeless)
1972: C: BCPL plus B with types
1978: Kernighan + Ritchie standard for C
1989:ANSI standard for C
What is c language:-
 C is mother language of all programming language.
 It is system programming language.
 It is procedure-oriented programming language.
 It is also called mid level programming language.
A Structured Programming
Approach Using C
4
Features of C Language:-
There are many features of c language are given below.
1) Simple
2) Machine Independent or Portable
3) Mid-level programming language
4) structured programming language
5) Rich Library
6) Memory Management
7) Fast Speed
8) Pointers
9) Recursion
10) Extensible
A Structured Programming
Approach Using C
5
WHY WE USE C?
 Mainly because it produces code that runs nearly as fast as code
written in assembly language. Some examples of the use of C might
be:
 Operating Systems
 Language Compilers
 Assemblers
 Text Editors
 Print Spoolers
 Network Drivers
 Modern Programs
 Data Bases
 Language Interpreters
 Utilities
A Structured Programming
Approach Using C
6
Why C Still Useful?
 C provides:
 Efficiency, high performance and high quality s/ws
 flexibility and power
 many high-level and low-level operations  middle level
 Stability and small size code
 Provide functionality through rich set of function libraries
 Gateway for other professional languages like C  C++  Java
 C is used:
 System software Compilers, Editors, embedded systems
 data compression, graphics and computational geometry, utility programs
 databases, operating systems, device drivers, system level routines
 there are zillions of lines of C legacy code
 Also used in application programs
A Structured Programming
Approach Using C
7
Hello World Program
 The source code
#include <stdio.h>
int main()
{
printf("Hello Worldn");
return(0);
}
Name Description Size* Range*
char Character or small
integer
1 byte signed: -128 to 127
unsigned: 0 to 255
short int
(short)
Short integer 2 bytes signed: -32768 to 32767
unsigned: 0 to 65535
int Integer 4 bytes signed: -2147483648 to
2147483647
unsigned: 0 to 4294967295
long int
(long)
Long integer 4 bytes signed: -2147483648 to
2147483647
unsigned: 0 to 4294967295
float Floating point
number
4 bytes 3.4e +/- 38 (7 digits)
double Double precision
floating point number
8 bytes 1.7e +/- 308 (15 digits)
long
double
Long double
precision floating
point number
8 bytes 1.7e +/- 308 (15 digits)
Data types
C Program Structure
 Program defined by:
 global declarations
 function definitions
 May contain preprocessor
directives
 Always has one function
named main, may contain
others
Preprocessor Directives
Global Declarations
FunctionDefinitions
int main () {
}
Local Declarations
Statements
FIGURE 2-2 Structure of a C Program
A Structured Programming
Approach Using C
11
FIGURE 2-3 The Greeting Program
A Structured Programming
Approach Using C
12
PROGRAM 2-1 The Greeting Program
A Structured Programming
Approach Using C
13
FIGURE 2-4 Examples of Block Comments
A Structured Programming
Approach Using C
14
FIGURE 2-5 Examples of Line Comments
A Structured Programming
Approach Using C
15
Parts of a Program
#include <stdio.h>
int x;
int main () {
int y;
printf("Enter x and y: ");
scanf(&x,&y);
printf("Sum is %dn",x+y);
}
Preprocessor Directive
Global Declaration
Function
Local Declaration
Statements
Preprocessor Directives
 Begin with #
 Instruct compiler to perform some transformation to file
before compiling
 Example: #include <stdio.h>
 add the header file stdio.h to this file
 .h for header file
 stdio.h defines useful input/output functions
Declarations
 Global
 visible throughout program
 describes data used throughout program
 Local
 visible within function
 describes data used only in function
Functions
 Consists of header and body
 header: int main ()
 body: contained between { and }
 starts with location declarations
 followed by series of statements
 More than one function may be defined
 Functions are called (invoked) - more later
Main Function
 Every program has one function main
 Header for main: int main ()
 Program is the sequence of statements between the { }
following main
 Statements are executed one at a time from the one
immediately following to main to the one before the }
Comments
 Text between /* and */
 Used to “document” the code for the human reader
 Ignored by compiler (not part of program)
 Have to be careful
 comments may cover multiple lines
 ends as soon as */ encountered (so no internal comments - /*
An /* internal */ comment */)
Comment Example
#include <stdio.h>
/* This comment covers
* multiple lines
* in the program.
*/
int main () /* The main header */ {
/* No local declarations */
printf(“Too many commentsn”);
} /* end of main */
Documentation
 Global - start of program, outlines overall solution, may
include structure chart
 Module - when using separate files, indication of what each
file solves
 Function - inputs, return values, and logic used in defining
function
 Add documentation for key (tough to understand) comments
 Names of variables - should be chosen to be meaningful,
make program readable
Syntax of C
 Rules that define C language
 Specify which tokens are valid
 Also indicate the expected order of tokens
 Some types of tokens:
 reserved words: include printf int ...
 identifiers: x y ...
 literal constants: 5‘a’ 5.0 ...
 punctuation: { } ; < > # /* */
Identifiers
One feature present in all computer languages is the
identifier. Identifiers allow us to name data and other
objects in the program. Each identified object in the
computer is stored at a unique address.
A Structured Programming
Approach Using C
25
Table 2-1 Rules for Identifiers
A Structured Programming
Approach Using C
26
An identifier must start with a letter or underscore:
it may not have a space or a hyphen.
Note
A Structured Programming
Approach Using C
27
Variables
Variables are named memory locations that have a type,
such as integer or character, which is inherited from their
type. The type determines the values that a variable may
contain and the operations that may be used with its
values.
Variable Declaration
Variable Initialization
Topics discussed in this section:
A Structured Programming
Approach Using C
28
FIGURE 2-11 Variables
A Structured Programming
Approach Using C
29
Variable Definition vs Declaration
Definition Tell the compiler about the variable: its type and
name, as well as allocated a memory cell for the
variable
Declaration Describe information ``about'' the variable,
doesn’t allocate memory cell for the variable
 Variable Declaration
int length = 100;
char num =‘9’; //The actual value is 57
float deposit = 240.5;
unsigned short ID = 0x5544;
Try the following statements, and see what happens
unsigned char value = -1;
printf(“The value is %d n”, value);
unsigned char value = 300;
printf(“The value is %d n”, value);
Result
Definition Memory layout Display comment
unsigned char
value = -1
11111111 255
unsigned char
value = 300
00101100 44 overflow
Variable types
 Local variable
Local variables are declared within the body of a function, and can only be used
within that function.
 Static variable
Another class of local variable is the static type. It is specified by the keyword
static in the variable declaration.
The most striking difference from a non-static local variable is, a static variable is
not destroyed on exit from the function.
 Global variable
A global variable declaration looks normal, but is located outside any of the
program's functions. So it is accessible to all functions.
 An example
int global = 10; //global variable
int func (int x)
{
static int stat_var; //static local variable
int temp; //(normal) local variable
int name[50]; //(normal) local variable
……
}
printf()
The printf() function can be instructed to print integers,
floats and string properly.
 The general syntax is
printf( “format”, variables);
 An example
int stud_id = 5200;
char * name = “Mike”;
printf(“%s‘s ID is %d n”, name, stud_id);
 Format Identifiers
%d decimal integers
%x hex integer
%c character
%f float and double number
%s string
%p pointer
 How to specify display space for a variable?
printf(“The student id is %5d n”, stud_id);
The value of stud_id will occupy 5 characters space in the print-
out.
 Why “n”
It introduces a new line on the terminal screen.
a alert (bell) character  backslash
b backspace ? question mark
f formfeed ’ single quote
n newline ” double quote
r carriage return 000 octal number
t horizontal tab xhh hexadecimal number
v vertical tab
escape sequence
Arithmetic Operations
Arithmetic Assignment Operators
Increment and Decrement Operators
awkward easy easiest
x = x+1; x += 1 x++
x = x-1; x -= 1 x--
Example
 Arithmetic operators
int i = 10;
int j = 15;
int add = i + j; //25
int diff = j – i; //5
int product = i * j; // 150
int quotient = j / i; // 1
int residual = j % i; // 5
i++; //Increase by 1
i--; //Decrease by 1
 Comparing them
int i = 10;
int j = 15;
float k = 15.0;
j / i = ?
j % i = ?
k / i = ?
k % i = ?
 The Answer
j / i = 1;
j % i = 5;
k / i = 1.5;
k % i It is illegal.
Note: For %, the operands can only be integers.
Logical Operations
 What is “true” and “false” in C
In C, there is no specific data type to represent “true” and “false”. C uses value
“0” to represent “false”, and uses non-zero value to stand for “true”.
 Logical Operators
A && B => A and B
A || B => A or B
A == B => IsA equal to B?
A != B => IsA not equal to B?
A > B => IsA greater than B?
A >= B => IsA greater than or equal to B?
A < B => IsA less than B?
A <= B => IsA less than or equal to B?
 Don’t be confused
&& and || have different meanings from & and |.
& and | are bitwise operators.
Short circuiting
 Short circuiting means that we don't evaluate the second part
of anAND or OR unless we really need to.
Some practices
Please compute the value of the following logical
expressions?
int i = 10; int j = 15; int k = 15; int m = 0;
if( i < j && j < k) =>
if( i != j || k < j) =>
if( j<= k || i > k) =>
if( j == k && m) =>
if(i) =>
if(m || j && i ) =>
int i = 10; int j = 15; int k = 15; int m = 0;
if( i < j && j < k) => false
if( i != j || k < j) => true
if( j<= k || i > k) => true
if( j == k && m) => false
if(i) => true
if(m || j && i ) => true
Did you get the correct answers?
Conditionals
 if statement
Three basic formats,
if (expression){
statement …
}
if (expression) {
statement …
}else{
statement …
}
if (expression) {
statement…
} else if (expression) {
statement…
} else{
statement…
}
 An example
if(score >= 90){
a_cnt ++;
}else if(score >= 80){
b_cnt++;
}else if(score >= 70){
c_cnt++;
}else if (score>= 60){
d_cnt++
}else{
f_cnt++
}
 The switch statement
switch (expression)
{
case item1:
statement;
break;
case item2:
statement;
break;
default:
statement;
break;
}
Loops
 for statement
for (expression1; expression2; expression3){
statement…
}
expression1 initializes;
expression2 is the terminate test;
expression3 is the modifier;
 An example
int x;
for (x=0; x<3; x++)
{
printf("x=%dn",x);
}
First time: x = 0;
Second time: x = 1;
Third time: x = 2;
Fourth time: x = 3; (don’t execute the body)
 The while statement
while (expression) {
statement …
}
while loop exits only when the expression is false.
 An example
int x = 3;
while (x>0) {
printf("x=%d n",x);
x--;
}
for <==> while
for (expression1;
expression2;
expression3){
statement…
}
expression1;
while (expression2)
{
statement…;
expression3;
}
equals
Arrays & Strings
 Arrays
int ids[50];
char name[100];
int table_of_num[30][40];
 Accessing an array
ids[0] = 40;
i = ids[1] + j;
table_of_num[3][4] = 100;
Note: In C Array subscripts start at 0 and end one less than the
array size. [0 .. n-1]
 Strings
Strings are defined as arrays of characters.
The only difference from a character array is, a symbol “0” is used
to indicate the end of a string.
For example, suppose we have a character array, char name[8], and
we store into it a string “Dave”.
Note: the length of this string 4, but it occupies 5 bytes.
D a v e 0
Functions
Functions are easy to use; they allow complicated programs to be broken into
small blocks, each of which is easier to write, read, and maintain.This is called
modulation.
 How does a function look like?
returntype function_name(parameters…)
{
local variables declaration;
function code;
return result;
}
 Sample function
int addition(int x, int y)
{
int add;
add = x + y;
return add;
}
 How to call a function?
int result;
int i = 5, j = 6;
result = addition(i, j);
Pointers
Pointer is the most beautiful (ugliest) part of C, but also brings most
trouble to C programmers. Over 90% bugs in the C programs
come from pointers.
“The International Obfuscated C Code Contest ”
 What is a pointer?
A pointer is a variable which contains the address in memory of
another variable.
In C we have a specific type for pointers.
 Declaring a pointer variable
int * pointer;
char * name;
 How to obtain the address of a variable?
int x = 0x2233;
pointer = &x;
where & is called address of operator.
 How to get the value of the variable indicated by the pointer?
int y = *pointer;
33 22 00 00
0x5200 0x5203
0x5200
pointer
What happens in the memory?
Suppose the address of variable x is 0x5200 in the above
example, so the value of the variable pointer is 0x5200.
X
swap the value of two variables
Why is the left one not working?
swap
main
x, y
a, b
call swap(a, b) in main
x, y, a, b are
all local
variables
Why is the right one working?
 Pointers and Arrays
Pointers and arrays are very closely linked in C.
Array elements arranged in consecutive memory locations
 Accessing array elements using pointers
int ids[50];
int * p = &ids[0];
p[i] <=> ids[i]
 Pointers and Strings
A string can be represented by a char * pointer.
Char name[50];
name[0] =‘D’;
name[1] =‘a’;
name[2] =‘v’;
name[3] =‘e’;
name[4] =‘0’;
char * p = &name[0];
printf(“The name is %s n”, p);
Note:The p represents the string “Dave”, but not the array
name[50].
Command-Line Argument
In C you can pass arguments to main() function.
 main() prototype
int main(int argc,char * argv[]);
argc indicates the number of arguments
argv is an array of input string pointers.
 How to pass your own arguments?
./hello 10
 What value is argc and argv?
Let’s add two printf statement to get the value of argc and argv.
#include <stdio.h>
int main(int argc, char * argv[]);)
{
int i=0;
printf("Hello Worldn");
printf(“The argc is %d n”, argc);
for(i=0; i < argc; i++){
printf(“The %dth element in argv is %sn”, i, argv[i]);
}
return(0);
}
 The output
The argc is 2
The 0th element in argv is ./hello
The 1th element in argv is 10
The trick is the system always passes the name of the
executable file as the first argument to the main() function.
 How to use your argument?
Be careful. Your arguments to main() are always in string format.
Taking the above program for example, the argv[1] is string “10”,
not a number. You must convert it into a number before you can
use it.
Practical mini project titles for C programming MZA
 Library Management System
Develop a system to manage book inventory, member registrations, and
borrowing/returning books.
 Student Grading System
Create a program that calculates and displays grades for students based on
their scores in various subjects.
 Simple Banking System
Implement a banking application to manage customer accounts,
transactions, and balance inquiries.
 Weather Data Analyzer
 Build a program that collects and analyzes weather data, allowing users
to view statistics like average temperature.
 ExpenseTracker
Create an application to track personal expenses, categorize them,
and generate monthly reports.
 Contact Management System
Develop a program to manage contacts, allowing users to add, delete,
and search for contacts.
 Quiz Application
Design a quiz application that poses questions to users and evaluates
their answers, providing scores at the end.
 DEADLINE OFTHE PRACTICAL FOR MWANZA
STUDENTSWILL BE 01.02.2024
 TO BE SUBMITTED IN MOODLE PLATFORM ANDWILL
BE ZOOM PRESENTATION
Data Structure
A data structure is a collection of one or more variables, possibly of different
types.
 An example of student record
struct stud_record{
char name[50];
int id;
int age;
int major;
……
};
 A data structure is also a data type
struct stud_record my_record;
struct stud_record * pointer;
pointer = & my_record;
 Accessing a field inside a data structure
my_record.id = 10; “.”
or
pointer->id = 10; “->”
Memory Allocation
 Stack memory allocation
Non-static local variable is an example of stack memory
allocation.
Such memory allocations are placed in a system memory area
called the stack.
 Static memory allocation
Static local variable and global variable require static memory
allocation. Static memory allocation happens before the program
starts, and persists through the entire life time of the program.
 Dynamic memory allocation
It allows the program determine how much memory it needs at
run time, and allocate exactly the right amount of storage.
The region of memory where dynamic allocation and deallocation
of memory can take place is called the heap.
Note: the program has the responsibility to free the dynamic
memory it allocated.
Memory arrangement
 Functions for the dynamic memory allocation
void *malloc(size_t number_of_bytes);
allocates dynamic memory
size_t sizeof(type);
returns the number of bytes of type
void free(void * p)
releases dynamic memory allocation
 An example of dynamic memory allocation
int * ids;//id arrays
int num_of_ids = 40;
ids = malloc( sizeof(int) * num_of_ids);
…….. Processing …...
free(ids);
 Allocating a data structure instance
struct stud_record * pointer;
pointer = malloc(sizeof(struct stud_record));
pointer->id = 10;
Never calculate the size of data structure yourself. The reason is
the size of data types is machine-dependent. Give it to sizeof()
function.
size of int
32-bytes machines 32
64-bytes machines 64
Programming Tips
 Replacing numbers in your code with macros
- don’t use magic numbers directly
#define MAX_NAME_LEN 50;
char name[MAX_NAME_LEN];
 Avoiding global variables
- modulation is more important
 Giving variables and functions a nice name
- a meaning name
 Don’t repeat your code
- make a subroutine/function
 Don’t let the function body to exceed one screen
- hard to debug
 Indenting your code (clearance)
if(expression)
{
if(expression)
{
……
}
}
 Commenting your code
 Don’t rush into coding. Plan first.
 Printing out more debugging information
 Using debugger (gdb)
C vs. C++
 C++ is a superset of C
 C++ has all the characteristics of C
 Using g++ to compile your source code
Books recommended
 The C Programming Language, Brian Kernighan and Dennis
Ritchie. Second edition. Prentice-Hall, 1988. (C Bible)
 The C++ Programming Language, Bjarne Stroustrup.Third
edition.Addison-Wesley, 1997. (C++ Bible)
 Advanced Programming in the UNIX Environment,W. Richard
Stevens,Addison-Wesley, 1992. (APUE)
Thanks
QUESTIONS……

C programing language fundamentals in comouter.pptx

  • 1.
  • 2.
    Outline  History ofC programming  What is C - Programming  “HelloWorld" Program  DataTypes &Variables  printf()  Arithmetic & Logical Operations  Conditionals  Loops  Arrays & Strings  Pointers  Functions  Command-Line Argument  Data Structure  Memory Allocation  Programming Tips  C vs. C++  Books recommended
  • 3.
    History of C 1960:ALGOL(ALGOrithmic Language) 1967: BCPL (Basic Combined Programming Language) 1970: B programming language (typeless) 1972: C: BCPL plus B with types 1978: Kernighan + Ritchie standard for C 1989:ANSI standard for C
  • 4.
    What is clanguage:-  C is mother language of all programming language.  It is system programming language.  It is procedure-oriented programming language.  It is also called mid level programming language. A Structured Programming Approach Using C 4
  • 5.
    Features of CLanguage:- There are many features of c language are given below. 1) Simple 2) Machine Independent or Portable 3) Mid-level programming language 4) structured programming language 5) Rich Library 6) Memory Management 7) Fast Speed 8) Pointers 9) Recursion 10) Extensible A Structured Programming Approach Using C 5
  • 6.
    WHY WE USEC?  Mainly because it produces code that runs nearly as fast as code written in assembly language. Some examples of the use of C might be:  Operating Systems  Language Compilers  Assemblers  Text Editors  Print Spoolers  Network Drivers  Modern Programs  Data Bases  Language Interpreters  Utilities A Structured Programming Approach Using C 6
  • 7.
    Why C StillUseful?  C provides:  Efficiency, high performance and high quality s/ws  flexibility and power  many high-level and low-level operations  middle level  Stability and small size code  Provide functionality through rich set of function libraries  Gateway for other professional languages like C  C++  Java  C is used:  System software Compilers, Editors, embedded systems  data compression, graphics and computational geometry, utility programs  databases, operating systems, device drivers, system level routines  there are zillions of lines of C legacy code  Also used in application programs A Structured Programming Approach Using C 7
  • 8.
    Hello World Program The source code #include <stdio.h> int main() { printf("Hello Worldn"); return(0); }
  • 9.
    Name Description Size*Range* char Character or small integer 1 byte signed: -128 to 127 unsigned: 0 to 255 short int (short) Short integer 2 bytes signed: -32768 to 32767 unsigned: 0 to 65535 int Integer 4 bytes signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295 long int (long) Long integer 4 bytes signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295 float Floating point number 4 bytes 3.4e +/- 38 (7 digits) double Double precision floating point number 8 bytes 1.7e +/- 308 (15 digits) long double Long double precision floating point number 8 bytes 1.7e +/- 308 (15 digits) Data types
  • 10.
    C Program Structure Program defined by:  global declarations  function definitions  May contain preprocessor directives  Always has one function named main, may contain others Preprocessor Directives Global Declarations FunctionDefinitions int main () { } Local Declarations Statements
  • 11.
    FIGURE 2-2 Structureof a C Program A Structured Programming Approach Using C 11
  • 12.
    FIGURE 2-3 TheGreeting Program A Structured Programming Approach Using C 12
  • 13.
    PROGRAM 2-1 TheGreeting Program A Structured Programming Approach Using C 13
  • 14.
    FIGURE 2-4 Examplesof Block Comments A Structured Programming Approach Using C 14
  • 15.
    FIGURE 2-5 Examplesof Line Comments A Structured Programming Approach Using C 15
  • 16.
    Parts of aProgram #include <stdio.h> int x; int main () { int y; printf("Enter x and y: "); scanf(&x,&y); printf("Sum is %dn",x+y); } Preprocessor Directive Global Declaration Function Local Declaration Statements
  • 17.
    Preprocessor Directives  Beginwith #  Instruct compiler to perform some transformation to file before compiling  Example: #include <stdio.h>  add the header file stdio.h to this file  .h for header file  stdio.h defines useful input/output functions
  • 18.
    Declarations  Global  visiblethroughout program  describes data used throughout program  Local  visible within function  describes data used only in function
  • 19.
    Functions  Consists ofheader and body  header: int main ()  body: contained between { and }  starts with location declarations  followed by series of statements  More than one function may be defined  Functions are called (invoked) - more later
  • 20.
    Main Function  Everyprogram has one function main  Header for main: int main ()  Program is the sequence of statements between the { } following main  Statements are executed one at a time from the one immediately following to main to the one before the }
  • 21.
    Comments  Text between/* and */  Used to “document” the code for the human reader  Ignored by compiler (not part of program)  Have to be careful  comments may cover multiple lines  ends as soon as */ encountered (so no internal comments - /* An /* internal */ comment */)
  • 22.
    Comment Example #include <stdio.h> /*This comment covers * multiple lines * in the program. */ int main () /* The main header */ { /* No local declarations */ printf(“Too many commentsn”); } /* end of main */
  • 23.
    Documentation  Global -start of program, outlines overall solution, may include structure chart  Module - when using separate files, indication of what each file solves  Function - inputs, return values, and logic used in defining function  Add documentation for key (tough to understand) comments  Names of variables - should be chosen to be meaningful, make program readable
  • 24.
    Syntax of C Rules that define C language  Specify which tokens are valid  Also indicate the expected order of tokens  Some types of tokens:  reserved words: include printf int ...  identifiers: x y ...  literal constants: 5‘a’ 5.0 ...  punctuation: { } ; < > # /* */
  • 25.
    Identifiers One feature presentin all computer languages is the identifier. Identifiers allow us to name data and other objects in the program. Each identified object in the computer is stored at a unique address. A Structured Programming Approach Using C 25
  • 26.
    Table 2-1 Rulesfor Identifiers A Structured Programming Approach Using C 26
  • 27.
    An identifier muststart with a letter or underscore: it may not have a space or a hyphen. Note A Structured Programming Approach Using C 27
  • 28.
    Variables Variables are namedmemory locations that have a type, such as integer or character, which is inherited from their type. The type determines the values that a variable may contain and the operations that may be used with its values. Variable Declaration Variable Initialization Topics discussed in this section: A Structured Programming Approach Using C 28
  • 29.
    FIGURE 2-11 Variables AStructured Programming Approach Using C 29
  • 30.
    Variable Definition vsDeclaration Definition Tell the compiler about the variable: its type and name, as well as allocated a memory cell for the variable Declaration Describe information ``about'' the variable, doesn’t allocate memory cell for the variable
  • 31.
     Variable Declaration intlength = 100; char num =‘9’; //The actual value is 57 float deposit = 240.5; unsigned short ID = 0x5544; Try the following statements, and see what happens unsigned char value = -1; printf(“The value is %d n”, value); unsigned char value = 300; printf(“The value is %d n”, value);
  • 32.
    Result Definition Memory layoutDisplay comment unsigned char value = -1 11111111 255 unsigned char value = 300 00101100 44 overflow
  • 33.
    Variable types  Localvariable Local variables are declared within the body of a function, and can only be used within that function.  Static variable Another class of local variable is the static type. It is specified by the keyword static in the variable declaration. The most striking difference from a non-static local variable is, a static variable is not destroyed on exit from the function.  Global variable A global variable declaration looks normal, but is located outside any of the program's functions. So it is accessible to all functions.
  • 34.
     An example intglobal = 10; //global variable int func (int x) { static int stat_var; //static local variable int temp; //(normal) local variable int name[50]; //(normal) local variable …… }
  • 36.
    printf() The printf() functioncan be instructed to print integers, floats and string properly.  The general syntax is printf( “format”, variables);  An example int stud_id = 5200; char * name = “Mike”; printf(“%s‘s ID is %d n”, name, stud_id);
  • 37.
     Format Identifiers %ddecimal integers %x hex integer %c character %f float and double number %s string %p pointer  How to specify display space for a variable? printf(“The student id is %5d n”, stud_id); The value of stud_id will occupy 5 characters space in the print- out.
  • 38.
     Why “n” Itintroduces a new line on the terminal screen. a alert (bell) character backslash b backspace ? question mark f formfeed ’ single quote n newline ” double quote r carriage return 000 octal number t horizontal tab xhh hexadecimal number v vertical tab escape sequence
  • 39.
  • 40.
  • 41.
    Increment and DecrementOperators awkward easy easiest x = x+1; x += 1 x++ x = x-1; x -= 1 x--
  • 42.
    Example  Arithmetic operators inti = 10; int j = 15; int add = i + j; //25 int diff = j – i; //5 int product = i * j; // 150 int quotient = j / i; // 1 int residual = j % i; // 5 i++; //Increase by 1 i--; //Decrease by 1
  • 43.
     Comparing them inti = 10; int j = 15; float k = 15.0; j / i = ? j % i = ? k / i = ? k % i = ?
  • 44.
     The Answer j/ i = 1; j % i = 5; k / i = 1.5; k % i It is illegal. Note: For %, the operands can only be integers.
  • 45.
    Logical Operations  Whatis “true” and “false” in C In C, there is no specific data type to represent “true” and “false”. C uses value “0” to represent “false”, and uses non-zero value to stand for “true”.  Logical Operators A && B => A and B A || B => A or B A == B => IsA equal to B? A != B => IsA not equal to B?
  • 46.
    A > B=> IsA greater than B? A >= B => IsA greater than or equal to B? A < B => IsA less than B? A <= B => IsA less than or equal to B?  Don’t be confused && and || have different meanings from & and |. & and | are bitwise operators.
  • 47.
    Short circuiting  Shortcircuiting means that we don't evaluate the second part of anAND or OR unless we really need to. Some practices Please compute the value of the following logical expressions?
  • 48.
    int i =10; int j = 15; int k = 15; int m = 0; if( i < j && j < k) => if( i != j || k < j) => if( j<= k || i > k) => if( j == k && m) => if(i) => if(m || j && i ) =>
  • 49.
    int i =10; int j = 15; int k = 15; int m = 0; if( i < j && j < k) => false if( i != j || k < j) => true if( j<= k || i > k) => true if( j == k && m) => false if(i) => true if(m || j && i ) => true Did you get the correct answers?
  • 50.
    Conditionals  if statement Threebasic formats, if (expression){ statement … } if (expression) { statement … }else{ statement … }
  • 51.
    if (expression) { statement… }else if (expression) { statement… } else{ statement… }
  • 52.
     An example if(score>= 90){ a_cnt ++; }else if(score >= 80){ b_cnt++; }else if(score >= 70){ c_cnt++; }else if (score>= 60){ d_cnt++ }else{ f_cnt++ }
  • 53.
     The switchstatement switch (expression) { case item1: statement; break; case item2: statement; break; default: statement; break; }
  • 54.
    Loops  for statement for(expression1; expression2; expression3){ statement… } expression1 initializes; expression2 is the terminate test; expression3 is the modifier;
  • 55.
     An example intx; for (x=0; x<3; x++) { printf("x=%dn",x); } First time: x = 0; Second time: x = 1; Third time: x = 2; Fourth time: x = 3; (don’t execute the body)
  • 56.
     The whilestatement while (expression) { statement … } while loop exits only when the expression is false.  An example int x = 3; while (x>0) { printf("x=%d n",x); x--; }
  • 57.
    for <==> while for(expression1; expression2; expression3){ statement… } expression1; while (expression2) { statement…; expression3; } equals
  • 58.
    Arrays & Strings Arrays int ids[50]; char name[100]; int table_of_num[30][40];  Accessing an array ids[0] = 40; i = ids[1] + j; table_of_num[3][4] = 100; Note: In C Array subscripts start at 0 and end one less than the array size. [0 .. n-1]
  • 59.
     Strings Strings aredefined as arrays of characters. The only difference from a character array is, a symbol “0” is used to indicate the end of a string. For example, suppose we have a character array, char name[8], and we store into it a string “Dave”. Note: the length of this string 4, but it occupies 5 bytes. D a v e 0
  • 60.
    Functions Functions are easyto use; they allow complicated programs to be broken into small blocks, each of which is easier to write, read, and maintain.This is called modulation.  How does a function look like? returntype function_name(parameters…) { local variables declaration; function code; return result; }
  • 61.
     Sample function intaddition(int x, int y) { int add; add = x + y; return add; }  How to call a function? int result; int i = 5, j = 6; result = addition(i, j);
  • 62.
    Pointers Pointer is themost beautiful (ugliest) part of C, but also brings most trouble to C programmers. Over 90% bugs in the C programs come from pointers. “The International Obfuscated C Code Contest ”  What is a pointer? A pointer is a variable which contains the address in memory of another variable. In C we have a specific type for pointers.
  • 63.
     Declaring apointer variable int * pointer; char * name;  How to obtain the address of a variable? int x = 0x2233; pointer = &x; where & is called address of operator.  How to get the value of the variable indicated by the pointer? int y = *pointer;
  • 64.
    33 22 0000 0x5200 0x5203 0x5200 pointer What happens in the memory? Suppose the address of variable x is 0x5200 in the above example, so the value of the variable pointer is 0x5200. X
  • 65.
    swap the valueof two variables
  • 66.
    Why is theleft one not working? swap main x, y a, b call swap(a, b) in main x, y, a, b are all local variables
  • 67.
    Why is theright one working?
  • 68.
     Pointers andArrays Pointers and arrays are very closely linked in C. Array elements arranged in consecutive memory locations  Accessing array elements using pointers int ids[50]; int * p = &ids[0]; p[i] <=> ids[i]  Pointers and Strings A string can be represented by a char * pointer.
  • 69.
    Char name[50]; name[0] =‘D’; name[1]=‘a’; name[2] =‘v’; name[3] =‘e’; name[4] =‘0’; char * p = &name[0]; printf(“The name is %s n”, p); Note:The p represents the string “Dave”, but not the array name[50].
  • 70.
    Command-Line Argument In Cyou can pass arguments to main() function.  main() prototype int main(int argc,char * argv[]); argc indicates the number of arguments argv is an array of input string pointers.  How to pass your own arguments? ./hello 10
  • 71.
     What valueis argc and argv? Let’s add two printf statement to get the value of argc and argv. #include <stdio.h> int main(int argc, char * argv[]);) { int i=0; printf("Hello Worldn"); printf(“The argc is %d n”, argc); for(i=0; i < argc; i++){ printf(“The %dth element in argv is %sn”, i, argv[i]); } return(0); }
  • 72.
     The output Theargc is 2 The 0th element in argv is ./hello The 1th element in argv is 10 The trick is the system always passes the name of the executable file as the first argument to the main() function.  How to use your argument? Be careful. Your arguments to main() are always in string format. Taking the above program for example, the argv[1] is string “10”, not a number. You must convert it into a number before you can use it.
  • 73.
    Practical mini projecttitles for C programming MZA  Library Management System Develop a system to manage book inventory, member registrations, and borrowing/returning books.  Student Grading System Create a program that calculates and displays grades for students based on their scores in various subjects.  Simple Banking System Implement a banking application to manage customer accounts, transactions, and balance inquiries.  Weather Data Analyzer  Build a program that collects and analyzes weather data, allowing users to view statistics like average temperature.
  • 74.
     ExpenseTracker Create anapplication to track personal expenses, categorize them, and generate monthly reports.  Contact Management System Develop a program to manage contacts, allowing users to add, delete, and search for contacts.  Quiz Application Design a quiz application that poses questions to users and evaluates their answers, providing scores at the end.  DEADLINE OFTHE PRACTICAL FOR MWANZA STUDENTSWILL BE 01.02.2024  TO BE SUBMITTED IN MOODLE PLATFORM ANDWILL BE ZOOM PRESENTATION
  • 75.
    Data Structure A datastructure is a collection of one or more variables, possibly of different types.  An example of student record struct stud_record{ char name[50]; int id; int age; int major; …… };
  • 76.
     A datastructure is also a data type struct stud_record my_record; struct stud_record * pointer; pointer = & my_record;  Accessing a field inside a data structure my_record.id = 10; “.” or pointer->id = 10; “->”
  • 77.
    Memory Allocation  Stackmemory allocation Non-static local variable is an example of stack memory allocation. Such memory allocations are placed in a system memory area called the stack.  Static memory allocation Static local variable and global variable require static memory allocation. Static memory allocation happens before the program starts, and persists through the entire life time of the program.
  • 78.
     Dynamic memoryallocation It allows the program determine how much memory it needs at run time, and allocate exactly the right amount of storage. The region of memory where dynamic allocation and deallocation of memory can take place is called the heap. Note: the program has the responsibility to free the dynamic memory it allocated.
  • 79.
  • 80.
     Functions forthe dynamic memory allocation void *malloc(size_t number_of_bytes); allocates dynamic memory size_t sizeof(type); returns the number of bytes of type void free(void * p) releases dynamic memory allocation  An example of dynamic memory allocation int * ids;//id arrays int num_of_ids = 40; ids = malloc( sizeof(int) * num_of_ids); …….. Processing …... free(ids);
  • 81.
     Allocating adata structure instance struct stud_record * pointer; pointer = malloc(sizeof(struct stud_record)); pointer->id = 10; Never calculate the size of data structure yourself. The reason is the size of data types is machine-dependent. Give it to sizeof() function. size of int 32-bytes machines 32 64-bytes machines 64
  • 82.
    Programming Tips  Replacingnumbers in your code with macros - don’t use magic numbers directly #define MAX_NAME_LEN 50; char name[MAX_NAME_LEN];  Avoiding global variables - modulation is more important  Giving variables and functions a nice name - a meaning name  Don’t repeat your code - make a subroutine/function  Don’t let the function body to exceed one screen - hard to debug
  • 83.
     Indenting yourcode (clearance) if(expression) { if(expression) { …… } }  Commenting your code  Don’t rush into coding. Plan first.  Printing out more debugging information  Using debugger (gdb)
  • 84.
    C vs. C++ C++ is a superset of C  C++ has all the characteristics of C  Using g++ to compile your source code
  • 85.
    Books recommended  TheC Programming Language, Brian Kernighan and Dennis Ritchie. Second edition. Prentice-Hall, 1988. (C Bible)  The C++ Programming Language, Bjarne Stroustrup.Third edition.Addison-Wesley, 1997. (C++ Bible)  Advanced Programming in the UNIX Environment,W. Richard Stevens,Addison-Wesley, 1992. (APUE)
  • 86.