SlidePlayer

  • My presentations

Auth with social network:

Download presentation

We think you have liked this presentation. If you wish to download it, please recommend it to your friends in any social system. Share buttons are a little bit lower. Thank you!

Presentation is loading. Please wait.

Basics of “C” Programming

Published by Leon Stevens Modified over 8 years ago

Similar presentations

Presentation on theme: "Basics of “C” Programming"— Presentation transcript:

Basics of C Programming

CSE 105 Structured Programming Language (C)

ppt presentation on c language

Module 6: Introduction to C Language ITEI102 Introduction to Programming Structure of C++ Program - Programming Terminologies - Microsoft Visual Studio.

ppt presentation on c language

EC-111 Algorithms & Computing Lecture #1 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.

ppt presentation on c language

Chapter 3: Beginning Problem Solving Concepts for the Computer Programming Computer Programming Skills /1436 Department of Computer Science.

ppt presentation on c language

Lecture 2 Introduction to C Programming

ppt presentation on c language

Three types of computer languages

ppt presentation on c language

1 Key Concepts:  Why C?  Life Cycle Of a C program,  What is a computer program?  A program statement?  Basic parts of a C program,  Printf() function?

ppt presentation on c language

Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.

ppt presentation on c language

 2003 Prentice Hall, Inc. All rights reserved. 1 Machine Languages, Assembly Languages, and High-level Languages Three types of computer languages 1.Machine.

ppt presentation on c language

Programming C/C++ on Eclipe C Training Trình bày : Ths HungNM.

ppt presentation on c language

Guide To UNIX Using Linux Third Edition

ppt presentation on c language

Introduction to C Programming

ppt presentation on c language

C programming Language and Data Structure For DIT Students.

ppt presentation on c language

Introduction to C language

ppt presentation on c language

CHAPTER 1: INTORDUCTION TO C LANGUAGE

ppt presentation on c language

Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.

ppt presentation on c language

Using C Programming Language.  The programs that run on a computer are referred to as software.  You’ll learn key programming methodology that are enhancing.

ppt presentation on c language

Copyright 2003 Scott/Jones Publishing Brief Version of Starting Out with C++, 4th Edition Chapter 1 Introduction to Computers and Programming.

ppt presentation on c language

Computer Science 210 Computer Organization Introduction to C.

About project

© 2024 SlidePlayer.com Inc. All rights reserved.

Search code, repositories, users, issues, pull requests...

Provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

C Programming Lecture PPT

rizvicoe/cplect

Folders and files, repository files navigation, c programming, prof. shiburaj, rizvi college of engineering.

Hello everyone,

These set of pages are the materials used by me for the delivery of the lectures in the course of C Programming.

  • Introduction to components of a Computer System
  • Introduction to Algorithm and Flowchart
  • Keywords, Identifiers, Constants and Variables
  • Data types in C
  • Operators in C
  • Basic Input and Output Operations
  • Expressions and Precedence of Operators
  • In-built Functions
  • Introduction to Control Structures
  • If statement, If-else statement, Nested if-else, else-if Ladder
  • Switch statement
  • For loop, While loop
  • Introduction to functions
  • Function prototype, Function definition, Accessing a function and parameter passing.
  • Introduction to Arrays
  • Declaration and initialization of one dimensional and two-dimensional arrays.
  • Definition and initialization of String
  • String functions
  • Concept of Structure and Union
  • Declaration and Initialization of structure and union
  • Nested structures
  • Array of Structures
  • Passing structure to functions
  • Fundamentals of pointers
  • Declaration, initialization and dereferencing of pointers
  • Operations on Pointers
  • Concept of dynamic memory allocation

Sections of a C Program

C compilers.

  • GNU GCC (Link 1) (Link for Windows - Mingw)
  • Tiny C Compiler (Link)
  • Portable C Compiler (Link)
  • CLang (Link)
  • Digital Mars Compiler (Link)

IDE for C Programming

  • CodeBlocks (http://www.codeblocks.org/)
  • Bloodshed Dev C++ (https://www.bloodshed.net)
  • Notepad++ (https://notepad-plus-plus.org) (Use NppExec Plugin with Gcc Compiler)
  • Visual Studio Comunity Edition (Link)
  • Turbo C++ (Link to Website)

GCC Compiler Parameters

  • -o name = Set the name of the output file eg: -o test.exe
  • -E = Used to return the preprocessor output (.i extention)
  • -S = Used to return assembly code (.s extension)
  • -C = Used to create the object file (.o extension)
  • -save-temps = To generate all the intermediate files during compilation.
  • -ansi = To enable the ANSI standard
  • -std=c89|c99|c9x = To change the standard
  • -pedantic-errors = Strict conformance to ISO standards
  • -Wall = Show errors and warnings
  • List of C Programs (https://www.faceprep.in/c-programming-questions/)
  • List of C Programs Link 2 (https://www.studytonight.com/c/programs/)

C Program Structure (Basic)

C program structure (advanced), contributors 2.

  • JavaScript 52.4%

Home Collections Technology Introduction To C Programming Language PPT

Introduction to C Programming Language PPT and Google Slides

Introduction to C Programming Language PPT and Google Slides

Introduction To C Programming Language Presentation Slide 

C is a high-level programming language that was originally developed in the early 1970s for system programming and has since become widely used for a variety of applications. It is a procedural language that allows for structured programming and modular design, making it highly flexible and efficient. C has a rich set of built-in functions and operators, and allows for low-level memory manipulation, making it ideal for applications that require high performance and speed. It has also been widely adopted in the field of embedded systems and microcontrollers. C continues to be an important language for software development today. By using our template, you can convey your message in a clear and concise manner.

Features of the template:

  • 100% customizable slides and easy to download.
  • Easy to change the slide's colors.
  • The slide contained 16:9 and 4:3 format.
  • Highly compatible with PowerPoint and Google Slides.
  • Content ready slides with colorful visuals.
  • Programming
  • Programming Language
  • Software Design And Coding
  • Coding Language
  • Coder Programming
  • C Programming Language
  • Introduction To C Programming
  • Google Slides

Networking Powerpoint Templates

325+ Templates

Technology Powerpoint Templates

1592+ Templates

Artificial Intelligence Powerpoint Templates

Artificial Intelligence

210+ Templates

Security Powerpoint Templates

132+ Templates

Mockup Powerpoint Templates

48+ Templates

Cloud computing Powerpoint Templates

Cloud computing

186+ Templates

Cyber security Powerpoint Templates

Cyber security

259+ Templates

Mobile Phones Powerpoint Templates

Mobile Phones

218+ Templates

Drone Powerpoint Templates

26+ Templates

Robot Powerpoint Templates

66+ Templates

You May Also Like These PowerPoint Templates

Best Presentation Technology PPT Template

Search

  • Most Popular
  • Explore all categories

c - programming ppt

  • C - Programming ppt

Upload: gyanendra-giri

Post on 09-Apr-2015

7.505 views

Embed Size (px): 344 x 292 429 x 357 514 x 422 599 x 487

DESCRIPTION

Page 1: C  -  Programming  ppt

C Programming

Welcome to C!

Page 2: C  -  Programming  ppt

Course Objectives

Be able to read and write C programs Understand all C language constructs Be able to use pointers Have a good overview of the Standard Library Be aware of some of C’s traps and pitfalls

Page 3: C  -  Programming  ppt

Practical Exercises

Practical exercises are a very important part of the course

An opportunity to experience some of the traps first hand!

Solutions are provided, discuss these amongst yourselves and/or with the tutor

If you get stuck, ask If you can’t understand one of the solutions, ask If you have an alternative solution, say

Page 4: C  -  Programming  ppt

Features of C

C can be thought of as a “high level assembler” Designed for maximum processor speed Safety a definite second! THE system programming language (Reasonably) portable Has a “write only” reputation

Page 5: C  -  Programming  ppt

History of C

Developed by Brian Kernighan and Dennis Ritchie of AT&T Bell Labs in 1972

In 1983 the American National Standards Institute began the standardisation process

In 1989 the International Standards Organisation continued the standardisation process

In 1990 a standard was finalised, known simply as “Standard C”

Everything before this is known as “K&R C”

Page 6: C  -  Programming  ppt

Standard C vs K&R C

Parameter type checking added Proper floating point support added Standard Library covered too Many “grey areas” addressed New features added

Standard C is now the choice All modern C compilers are Standard C The course discusses Standard C

Page 7: C  -  Programming  ppt

A C Program

#include <stdio.h> /* comment */

int main(void){

printf("Hello\n");printf("Welcome to the Course!\n");

HelloWelcome to the Course!

tells compiler about standard input and output functions (i.e. printf + others)

main function

flag success to operating system

Page 8: C  -  Programming  ppt

The Format of C

Statements are terminated with semicolons Indentation is ignored by the compiler C is case sensitive - all keywords and Standard

Library functions are lowercase Strings are placed in double quotes Newlines are handled via \n Programs are capable of flagging success or

error, those forgetting to do so have one or other chosen randomly!

Page 9: C  -  Programming  ppt

Another Example

#include <stdio.h>

printf("Enter two numbers: ");scanf("%i %i", &a, &b);

printf("%i - %i = %i\n", a, b, a - b);

create two integer variables, “a” and “b”

read two integer numbers into “a”

write “a”, “b” and “a-b” in the format specified

Enter two numbers: 21 1721 - 17 = 4

Page 10: C  -  Programming  ppt

Variables must be declared before use immediately after “{”

Valid characters are letters, digits and “_” First character cannot be a digit 31 characters recognised for local variables

(more can be used, but are ignored) Some implementations recognise only 6

characters in global variables (and function names)!

Upper and lower case letters are distinct

Page 11: C  -  Programming  ppt

printf and scanf

printf writes integer values to screen when %i is used

scanf reads integer values from the keyboard when %i is used

“&” VERY important with scanf (required to change the parameter, this will be investigated later) - absence will make program very ill

“&” not necessary with printf because current value of parameter is used

Page 12: C  -  Programming  ppt

Integer Types in C

C supports different kinds of integers maxima and minima defined in “limits.h”

type format bytes minimum maximum

char %c 1 CHAR_MIN CHAR_MAX

signed char %c 1 SCHAR_MIN SCHAR_MAX

unsigned char %c 1 0 UCHAR_MAX

short [int] %hi 2 SHRT_MIN SHRT_MAX

unsigned short %hu 2 0 USHRT_MAX

int %i 2 or 4 INT_MIN INT_MAX

unsigned int %u 2 or 4 0 UINT_MAX

long [int] %li 4 LONG_MIN LONG_MAX

unsigned long %lu 4 0 ULONG_MAX

Page 13: C  -  Programming  ppt

Integer Example

#include <stdio.h>#include <limits.h>

unsigned long big = ULONG_MAX;

printf("minimum int = %i, ", INT_MIN);printf("maximum int = %i\n", INT_MAX);printf("maximum unsigned = %u\n", UINT_MAX);printf("maximum long int = %li\n", LONG_MAX);printf("maximum unsigned long = %lu\n", big);

return 0;} minimum int = -32768, maximum int = 32767

maximum unsigned = 65535maximum long int = 2147483647maximum unsigned long = 4294967295

minimum int = -32768, maximum int = 32767maximum unsigned = 65535maximum long int = 2147483647maximum unsigned long = 4294967295

Page 14: C  -  Programming  ppt

Character Example

char lower_a = 'a';char lower_m = 'm';

printf("minimum char = %i, ", CHAR_MIN);printf("maximum char = %i\n", CHAR_MAX);

printf("after '%c' comes '%c'\n", lower_a, lower_a + 1);printf("uppercase is '%c'\n", lower_m - 'a' + 'A');

return 0;} minimum char = 0, maximum char = 255

after 'a' comes 'b'uppercase is 'M'

minimum char = 0, maximum char = 255after 'a' comes 'b'uppercase is 'M'

Note: print integer value of character

Page 15: C  -  Programming  ppt

Integers With Different Bases

It is possible to work in octal (base 8) and hexadecimal (base 16)

int dec = 20, oct = 020, hex = 0x20;

printf("dec=%d, oct=%d, hex=%d\n", dec, oct, hex);printf("dec=%d, oct=%o, hex=%x\n", dec, oct, hex);

dec=20, oct=16, hex=32dec=20, oct=20, hex=20

zero puts compiler into octal mode!

zero “x” puts compiler into hexadecimal

Page 16: C  -  Programming  ppt

Real Types In C

C supports different kinds of reals maxima and minima are defined in “float.h”

float %f %e %g 4 FLT_MIN FLT_MAX

double %lf %le %lg 8 DBL_MIN DBL_MAX

long double %Lf %Le %Lg 10 LDBL_MIN LDBL_MAX

Page 17: C  -  Programming  ppt

Real Example

#include <stdio.h>#include <float.h>

double f = 3.1416, g = 1.2e-5, h = 5000000000.0;

printf("f=%lf\tg=%lf\th=%lf\n", f, g, h);printf("f=%le\tg=%le\th=%le\n", f, g, h);printf("f=%lg\tg=%lg\th=%lg\n", f, g, h);

printf("f=%7.2lf\tg=%.2le\th=%.4lg\n", f, g, h);

f=3.141600 g=0.000012 h=5000000000.000000f=3.141600e+00 g=1.200000e-05 h=5.000000e+09f=3.1416 g=1.2e-05 h=5e+09f= 3.14 g=1.20e-05 h=5e+09

Page 18: C  -  Programming  ppt

Constants have types in C Numbers containing “.” or “e” are double: 3.5,

1e-7, -1.29e15 For float constants append “F”: 3.5F, 1e-7F For long double constants append “L”: -

1.29e15L, 1e-7L Numbers without “.”, “e” or “F” are int, e.g.

10000, -35 (some compilers switch to long int if the constant would overflow int)

For long int constants append “L”, e.g. 9000000L

Page 19: C  -  Programming  ppt

double f = 5000000000.0;double g = 5000000000;

printf("f=%lf\n", f);printf("g=%lf\n", g);

f=5000000000.000000g=705032704.000000

double constant created because of “.”

constant is int or long but 2,147,483,647 is the

Page 20: C  -  Programming  ppt

Named Constants

Named constants may be created using const

const long double pi = 3.141592653590L;const int days_in_week = 7;const sunday = 0;

days_in_week = 5;

creates an integer

Page 21: C  -  Programming  ppt

Preprocessor Constants

Named constants may also be created using the Preprocessor– Needs to be in “search and replace” mode

– Historically these constants consist of capital letters

#define PI 3.141592653590L#define DAYS_IN_WEEK 7#define SUNDAY 0

int day = SUNDAY;long flag = USE_API;

search for “PI”, replace with 3.1415....

“PI” is NOT substituted here

Note: no “=” and no “;”

Page 22: C  -  Programming  ppt

Take Care With printf And scanf!

short a = 256, b = 10;

printf("Type a number: ");scanf("%c", &a);

printf("a = %hi, b = %f\n", a, b);

“%c” fills one byte of “a” which is two

bytes in size

“%f” expects 4 byte float in IEEE format, “b” is 2 bytes and

NOT in IEEE format

Type a number: 1a = 305 b = Floating support not loaded

Page 23: C  -  Programming  ppt

K&R C vs Standard C main, printf Variables Integer types Real types Constants Named constants Preprocessor constants Take care with printf and scanf

Page 24: C  -  Programming  ppt

Operators in C

Arithmetic operators Cast operator Increment and Decrement Bitwise operators Comparison operators Assignment operators sizeof operator Conditional expression operator

Page 25: C  -  Programming  ppt

Arithmetic Operators

C supports the arithmetic operators:

- subtraction

* multiplication

% modulo (remainder)

“%” may not be used with reals

Page 26: C  -  Programming  ppt

Using Arithmetic Operators

The compiler uses the types of the operands to determine how the calculation should be done

int i = 5, j = 4, k;double f = 5.0, g = 4.0, h;

k = i / j;h = f / g;h = i / j;

“i” and “j” are ints, integer division is done, 1 is

assigned to “k”

“f” and “g” are double, double division is done, 1.25

is assigned to “h”

integer division is still done, despite “h” being double. Value assigned is 1.00000

Page 27: C  -  Programming  ppt

The Cast Operator

The cast operator temporarily changes the type of a variable

int i = 5, j = 4;double f;

f = (double)i / j;f = i / (double)j;f = (double)i / (double)j;f = (double)(i / j);

integer division is done here, the result, 1, is changed to a

double, 1.00000

if either operand is a double, the other is automatically

Page 28: C  -  Programming  ppt

Increment and Decrement

C has two special operators for adding and subtracting one from a variable

++ increment

- - decrement

These may be either prefix (before the variable) or postfix (after the variable):

int i = 5, j = 4;

i++;--j;++i;

“i” becomes 6

“j” becomes 3

“i” becomes 7

Page 29: C  -  Programming  ppt

Prefix and Postfix

The prefix and postfix versions are different

int i, j = 5;

i = ++j;printf("i=%d, j=%d\n", i, j);

j = 5;i = j++;printf("i=%d, j=%d\n", i, j);

return 0;} i=6, j=6

i=6, j=6i=5, j=6

equivalent to: 1. j++; 2. i = j;

equivalent to: 1. i = j; 2. j++;

Page 30: C  -  Programming  ppt

To understand C’s comparison operators (less than, greater than, etc.) and the logical operators (and, or, not) it is important to understand how C regards truth

There is no boolean data type in C, integers are used instead

The value of 0 (or 0.0) is false Any other value, 1, -1, 0.3, -20.8, is true

if(32)printf("this will always be printed\n");

if(0)printf("this will never be printed\n");

Page 31: C  -  Programming  ppt

Comparison Operators

C supports the comparison operators:

< less than

<= less than or equal to

> greater than

>= greater than or equal to

== is equal to

!= is not equal to

These all give 1 (non zero value, i.e. true) when the comparison succeeds and 0 (i.e. false) when the comparison fails

Page 32: C  -  Programming  ppt

Logical Operators

C supports the logical operators:

&& and

These also give 1 (non zero value, i.e. true) when the condition succeeds and 0 (i.e. false) when the condition fails

int i, j = 10, k = 28;

i = ((j > 5) && (k < 100)) || (k > 24);

Page 33: C  -  Programming  ppt

Logical Operator Guarantees

C makes two important guarantees about the evaluation of conditions

Evaluation is left to right Evaluation is “short circuit”

if(i < 10 && a[i] > 0)printf("%i\n", a[i]);

“i < 10” is evaluated first, if false the whole statement is false (because false AND anything is false) thus “a[i] > 0”

would not be evaluated

Page 34: C  -  Programming  ppt

Remember to use parentheses with conditions, otherwise your program may not mean what you think

int i = 10;

if(!i == 5)printf("i is not equal to five\n");

elseprintf("i is equal to five\n");

in this attempt to say “i not equal to five”, “!i” is evaluated first. As “i” is 10, i.e. non zero, i.e. true, “!i” must be false, i.e. zero. Zero is

compared with five

i is equal to fivei is equal to five

Page 35: C  -  Programming  ppt

Bitwise Operators

C has the following bit operators which may only be applied to integer types:

& bitwise and

| bitwise inclusive or

^ bitwise exclusive or

~ one’s compliment

>> right shift

<< left shift

Page 36: C  -  Programming  ppt

Bitwise Example

short a = 0x6eb9;short b = 0x5d27;unsigned short c = 7097;

printf("0x%x, ", a & b);printf("0x%x, ", a | b);printf("0x%x\n", a ^ b);

printf("%u, ", c << 2);printf("%u\n", c >> 1);

0x4c21, 0x7fbf, 0x339e28388, 3548

0x6eb9 0110 1110 1011 10010x5d27 0101 1101 0010 01110x4c21 0100 1100 0010 0001

0x6eb9 0110 1110 1011 10010x5d27 0101 1101 0010 01110x7fbf 0111 1111 1011 1111

0x6eb9 0110 1110 1011 10010x5d27 0101 1101 0010 01110x339e 0011 0011 1001 1110

7097 0001 1011 1011 100128388 0110 1110 1110 0100

7097 0001 1011 1011 1001 3548 0000 1101 1101 1100

Page 37: C  -  Programming  ppt

Assignment is more flexible than might first appear

An assigned value is always made available for subsequent use

int i, j, k, l, m, n;

i = j = k = l = m = n = 22;

printf("%i\n", j = 93);

“n = 22” happens first, this makes 22 available for assignment to “m”. Assigning 22 to “m” makes 22 available for assignment to “l” etc.

“j” is assigned 93, the 93 is then made available to printf for printing

Page 38: C  -  Programming  ppt

One of the most frequent mistakes is to confuse test for equality, “==”, with assignment, “=”

if(i = 0)printf("i is equal to zero\n");

elseprintf("somehow i is not zero\n");

somehow i is not zerosomehow i is not zero

Page 39: C  -  Programming  ppt

Other Assignment Operators

There is a family of assignment operators:

+= -= *= /= %=

&= |= ^=

<<= >>=

In each of these:

expression1 op= expression2

is equivalent to:

(expression1) = (expression1) op (expression2)

a += 27;a += 27;

a = a + 27;a = a + 27;

f /= 9.2;f /= 9.2;

f = f / 9.2;f = f / 9.2;

i *= j + 2;i *= j + 2;

i = i * (j + 2);i = i * (j + 2);

Page 40: C  -  Programming  ppt

sizeof Operator

C has a mechanism for determining how many bytes a variable occupies

printf("\"big\" is %u bytes\n", sizeof(big));printf("a short is %u bytes\n", sizeof(short));printf("a double is %u bytes\n", sizeof double);

"big" is 4 bytesa short is 2 bytesa double is 8 bytes

Page 41: C  -  Programming  ppt

Conditional Expression Operator

The conditional expression operator provides an in-line if/then/else

If the first expression is true, the second is evaluated

If the first expression is false, the third is evaluated

int i, j = 100, k = -1;

i = (j > k) ? j : k;

i = (j < k) ? j : k;

if(j > k)i = j;

if(j < k)i = j;

Page 42: C  -  Programming  ppt

Precedence of Operators

C treats operators with different importance, known as precedence

There are 15 levels In general, the unary operators have higher

precedence than binary operators Parentheses can always be used to improve

clarity#include <stdio.h>

int j = 3 * 4 + 48 / 7;

printf("j = %i\n", j);

j = 18j = 18

Page 43: C  -  Programming  ppt

Associativity of Operators

For two operators of equal precedence (i.e. same importance) a second rule, “associativity”, is used

Associativity is either “left to right” (left operator first) or “right to left” (right operator first)

int i = 6 * 4 / 7;

printf("i = %d\n", i);

Page 44: C  -  Programming  ppt

Precedence/Associativity Table

Associativity() [] -> .

left to right

! ~ ++ -- - + (cast) * & sizeof

right to left

<< >>

< <= >= >

= += -= *= /= %= etc

Page 45: C  -  Programming  ppt

int i = 0, j, k = 7, m = 5, n;

j = m += 2;printf("j = %d\n", j);

j = k++ > 7;printf("j = %d\n", j);

j = i == 0 & k;printf("j = %d\n", j);

n = !i > k >> 2;printf("n = %d\n", n);

Page 46: C  -  Programming  ppt

Control Flow

Decisions - if then else More decisions - switch Loops - while, do while, for Keyword break Keyword continue

Page 47: C  -  Programming  ppt

Decisions - if then

Parentheses surround the test One statement becomes the “then part” If more are required, braces must be used

scanf("%i", &i);

if(i > 0)printf("a positive number was entered\n");

if(i < 0) {printf("a negative number was entered\n");i = -i;

Page 48: C  -  Programming  ppt

A semicolon after the condition forms a “do nothing” statement

printf("input an integer: ");scanf("%i", &j);

if(j > 0);printf("a positive number was entered\n");

input an integer: -6

a positive number was entered

Page 49: C  -  Programming  ppt

if then else

An optional else may be added One statement by default, if more are required,

braces must be used

if(i > 0)printf("i is positive\n");

elseprintf("i is negative\n");

else {printf("i is negative\n");i = -i;

Page 50: C  -  Programming  ppt

Nesting ifs

else associates with the nearest if

int i = 100;

if(i > 0)if(i > 1000)

printf("i is big\n");else

printf("i is reasonable\n");

printf("i is reasonable\n"); i is reasonablei is reasonable

int i = -20;

if(i > 0) {if(i > 1000)

printf("i is big\n");} else

printf("i is negative\n");

printf("i is negative\n");i is negativei is negative

Page 51: C  -  Programming  ppt

C supports a switch for multi-way decision making

switch(c) { case 'a': case 'A':

printf("area = %.2f\n", r * r * pi);break;

case 'c': case 'C':printf("circumference = %.2f\n", 2 * r * pi);break;

case 'q':printf("quit option chosen\n");break;

default:printf("unknown option chosen\n");break;

Page 52: C  -  Programming  ppt

More About switch

Only integral constants may be tested If no condition matches, the default is executed If no default, nothing is done (not an error) The break is important

switch(f) { case 2:

switch(i) { case 2 * j:

switch(i) { case 3: printf("i = 3\n"); case 2: printf("i = 2\n"); case 1: printf("i = 1\n");}

i = 3i = 2i = 1

Page 53: C  -  Programming  ppt

A switch Example

printf("On the ");switch(i) { case 1: printf("1st"); break; case 2: printf("2nd"); break; case 3: printf("3rd"); break; default: printf("%ith", i); break;}printf(" day of Christmas my true love sent to me ");switch(i) { case 12: printf("twelve lords a leaping, "); case 11: printf("eleven ladies dancing, "); case 10: printf("ten pipers piping, "); case 9: printf("nine drummers drumming, "); case 8: printf("eight maids a milking, "); case 7: printf("seven swans a swimming, "); case 6: printf("six geese a laying, "); case 5: printf("five gold rings, "); case 4: printf("four calling birds, "); case 3: printf("three French hens, "); case 2: printf("two turtle doves and "); case 1: printf("a partridge in a pear tree\n");}

Page 54: C  -  Programming  ppt

The simplest C loop is the while Parentheses must surround the condition One statement forms the body of the loop Braces must be added if more statements are to

be executed

while(j > 0)printf("j = %i\n", j--);

j = 5j = 4j = 3j = 2j = 1

j = 5j = 4j = 3j = 2j = 1while(j > 0) {

printf("j = %i\n", j);j--;

while(j > 0) {printf("j = %i\n", j);j--;

Page 55: C  -  Programming  ppt

(Another) Semicolon Warning!

A semicolon placed after the condition forms a body that does nothing

while(j > 0);printf("j = %i\n", j--);

program disappears into an infinite loop

• Sometimes an empty loop body is required

while(scanf("%i", &j) != 1)while((c = getchar()) != '\n')

placing semicolon on the line below

makes the intention obvious

Page 56: C  -  Programming  ppt

while, Not Until!

Remember to get the condition the right way around!

printf("start\n");while(j == 0)

printf("j = %i\n", j--);printf("end\n");

user probably intends “until j is

equal to zero”, however this is NOT

the way to write itstartend

Page 57: C  -  Programming  ppt

do while guarantees execution at least once

printf("start\n");do

printf("j = %i\n", j--);while(j > 0);printf("stop\n");

startj = 5j = 4j = 3j = 2j = 1stop

int j = -10;

printf("start\n");do {

} while(j > 0);printf("stop\n");

startj = -10stop

Page 58: C  -  Programming  ppt

for encapsulates the essential elements of a loop into one statement

for(initial-part; while-condition; update-part)body;

for(j = 5; j > 0; j--)printf("j = %i\n", j);

for(j = 5; j > 0; j--) {printf("j = %i ", j);printf("%s\n", ((j%2)==0)?"even":"odd");

j = 5 oddj = 4 evenj = 3 oddj = 2 evenj = 1 odd

Page 59: C  -  Programming  ppt

for Is Not Until Either!

Remember to get the for condition the right way around (it is really a while condition)

printf("start\n");for(j = 5; j == 0; j--)

printf("j = %i\n", j);printf("end\n");

the way to write it either!

Page 60: C  -  Programming  ppt

Stepping With for

Unlike some languages, the for loop is not restricted to stepping up or down by 1

#include <math.h>

double angle;

for(angle = 0.0; angle < 3.14159; angle += 0.2)printf("sine of %.1lf is %.2lf\n",

angle, sin(angle));

Page 61: C  -  Programming  ppt

Extending the for Loop

The initial and update parts may contain multiple comma separated statements

int i, j, k;

for(i = 0, j = 5, k = -1; i < 10; i++, j++, k--)

The initial, condition and update parts may contain no statements at all!

for(; i < 10; i++, j++, k--)for(; i < 10; i++, j++, k--)

for(;i < 10;)for(;i < 10;)

for(;;)for(;;)

use of a while loop would be clearer here!

creates an infinite loop

Page 62: C  -  Programming  ppt

The break keyword forces immediate exit from the nearest enclosing loop

Use in moderation!

for(;;) {printf("type an int: ");if(scanf("%i", &j) == 1)

break;while((c = getchar()) != '\n')

;}printf("j = %i\n", j);

;}printf("j = %i\n", j); type an int: an int

type an int: notype an int: 16j = 16

type an int: an inttype an int: notype an int: 16j = 16

if scanf returns 1, jump out of the loop

Page 63: C  -  Programming  ppt

The continue keyword forces the next iteration of the nearest enclosing loop

for(j = 1; j <= 10; j++) {if(j % 3 == 0)

continue;printf("j = %i\n", j);

j = 1j = 2j = 4j = 5j = 7j = 8j = 10

if j is exactly divisible by 3, skip

Page 64: C  -  Programming  ppt

if (then) else - watch the semicolons switch can test integer values while, do while, for - watch the semicolons

again break continue

Page 65: C  -  Programming  ppt

Rules of functions Examples - writing a function, calling a function Function prototypes Visibility Call by value The stack auto, static and register

Page 66: C  -  Programming  ppt

A function may accept as many parameters as it needs, or no parameters (like main)

A function may return either one or no values Variables declared inside a function are only

available to that function, unless explicitly passed to another function

Page 67: C  -  Programming  ppt

Writing a Function - Example

int print_table(double start, double end, double step){

double d;int lines = 1;

printf("Celsius\tFarenheit\n");for(d = start; d <= end; d += step, lines++)

printf("%.1lf\t%.1lf\n", d, d * 1.8 + 32);

return lines;}

accept 3 doubles when called

this is the TYPE of the value handed back

this is the ACTUAL value handed back

Page 68: C  -  Programming  ppt

Calling a Function - Example

int print_table(double, double, double);

int how_many;double end = 100.0;

how_many = print_table(1.0, end, 3);print_table(end, 200, 15);

IMPORTANT: this tells the compiler how print_table works

the compiler knows these should be doubles and

converts them automatically

here the function’s return value is ignored - this is ok, if you don’t want it, you don’t have to use it

Page 69: C  -  Programming  ppt

Calling a Function - Disaster!

now the compiler does not know how the function works

the compiler does NOT convert these ints to

doubles. The function picks up doubles

Page 70: C  -  Programming  ppt

The (optional) line

is known as a prototype If the compiler meets a call to an unknown

function it “guesses”– Guess 1: the function returns an int, even if it doesn’t

– Guess 2: you have passed the correct number of parameters and made sure they are all of the correct type, even if you haven’t

The prototype provides the compiler with important information about the return type and parameters

Page 71: C  -  Programming  ppt

Prototyping is Not Optional

To achieve working programs the compiler is best given a prototype for each function called

When calling a Standard Library function, #include the file specified in the help page(s) - this file will contain the prototype

When calling one of your own functions, write a prototype by hand

Page 72: C  -  Programming  ppt

Writing Prototypes

int print_table(double, double, double);int print_table(double, double, double);

Function header:

The function prototype may optionally include variable names (which are ignored)

int print_table(double start, double end, double step);int print_table(double start, double end, double step);

int print_table(double x, double y, double z);int print_table(double x, double y, double z);

Page 73: C  -  Programming  ppt

Take Care With Semicolons

The prototype has a semicolon

The function header has an open brace

Don’t confuse the compiler by adding a semicolon into the function header!

int print_table(double start, double end, double step);{

Page 74: C  -  Programming  ppt

Example Prototypes

/* no parameters, int return value */int get_integer(void);

/* no parameters, double return value */double get_double(void);

/* no parameters, no return value */void clear_screen(void);

/* three int parameters, int return value */int day_of_year(int day, int month, int year);

/* three int parameters, long int return value */long day_since_1_jan_1970(int, int, int);

/* parameter checking DISABLED, double return value */double k_and_r_function();

/* short int parameter, (default) int return value */transfer(short int s);

Page 75: C  -  Programming  ppt

Example Calls

int i;double d;long l;short int s = 5;

i = get_integer();

d = get_double();

clear_screen();

i = day_of_year(16, 7, 1969);

l = day_since_1_jan_1970(1, 4, 1983);

d = k_and_r_function();d = k_and_r_function(19.7);d = k_and_r_function("hello world");

i = transfer(s);

the compiler cannot tell which of these (if any) is correct - neither can we

without resorting to documentation!

no mention of “void” when calling these

Page 76: C  -  Programming  ppt

Rules of Visibility

C is a block structured language, variables may only be used in functions declaring them

int i = 5, j, k = 2;float f = 2.8F, g;

void func(int v){

double d, e = 0.0, f;

i++; g--;f = 0.0;

}func’s “f” is used,

compiler does not know about “d”

“i” and “g” not available here

Page 77: C  -  Programming  ppt

Call by Value

When a function is called the parameters are copied - “call by value”

The function is unable to change any variable passed as a parameter

In the next chapter pointers are discussed which allow “call by reference”

We have already had a sneak preview of this mechanism with scanf

Page 78: C  -  Programming  ppt

Call by Value - Example

void change(int v);

int var = 5;

change(var);

printf("main: var = %i\n", var);

void change(int v){

v *= 100;printf("change: v = %i\n", v);

}change: v = 500main: var = 5

change: v = 500main: var = 5

the function was not able to alter “var”

the function is able to alter “v”

Page 79: C  -  Programming  ppt

C and the Stack

C uses a stack to store local variables (i.e. those declared in functions), it is also used when passing parameters to functions

The calling function pushes the parameters The function is called The called function picks up the parameters The called function pushes its local variables When finished, the called function pops its local

variables and jumps back to the calling function The calling function pops the parameters The return value is handled

Page 80: C  -  Programming  ppt

Stack Example

double power(int, int);

int x = 2;double d;

d = power(x, 5);printf("%lf\n", d);

double power(int n, int p){

double result = n;

while(--p > 0)result *= n;

return result;}

power: result32.0

Page 81: C  -  Programming  ppt

C stores local variables on the stack Global variables may be declared. These are not

stack based, but are placed in the data segment Special keywords exist to specify where local

variables are stored:

auto - place on the stack (default)

static - place in the data segment

register - place in a CPU register

Data may also be placed on the heap, this will be discussed in a later chapter

Page 82: C  -  Programming  ppt

Local variables are automatically allocated on entry into, and automatically deallocated on exit from, a function

These variables are therefore called “automatic” Initial value: random Initialisation: recommended

int table(void){

int lines = 13;auto int columns;

auto keyword redundant

Page 83: C  -  Programming  ppt

The static keyword instructs the compiler to place a variable into the data segment

The data segment is permanent (static) A value left in a static in one call to a function

will still be there at the next call Initial value: 0 Initialisation: unnecessary if you like zeros

int running_total(void){

static int rows;

permanently allocated, but local to this

Page 84: C  -  Programming  ppt

The register keyword tells the compiler to place a variable into a CPU register (you cannot specify which)

If a register is unavailable the request will be ignored

Largely redundant with optimising compilers Initial value: random Initialisation: recommended

void speedy_function(void){

register int i;

for(i = 0; i < 10000; i++)

Page 85: C  -  Programming  ppt

Global Variables

Global variables are created by placing the declaration outside all functions

They are placed in the data segment Initial value: 0 Initialisation: unnecessary if you like zeros

variable “d” is global and available to all functions defined

Page 86: C  -  Programming  ppt

Writing and calling functions The need for function prototypes Visibility C is “call by value” Local variables are stack based, this can be

changed with the static and register keywords

Global variables may be created, they are stored in the data segment

Page 87: C  -  Programming  ppt

Declaring pointers The “&” operator The “*” operator Initialising pointers Type mismatches Call by reference Pointers to pointers

Page 88: C  -  Programming  ppt

Pointers - Why?

Using pointers allows us to:– Achieve call by reference (i.e. write functions which change

their parameters)

– Handle arrays efficiently

– Handle structures (records) efficiently

– Create linked lists, trees, graphs etc.

– Put data onto the heap

– Create tables of functions for handling Windows events, signals etc.

Already been using pointers with scanf Care must be taken when using pointers since

there are no safety features

Page 89: C  -  Programming  ppt

Declaring Pointers

Pointers are declared by using “*” Declare an integer:

int i;int i;

Declare a pointer to an integer:

int *p;int *p;

There is some debate as to the best position of the “*”

int* p;int* p;

Page 90: C  -  Programming  ppt

Example Pointer Declarations

int *pi; /* pi is a pointer to an int */

long int *p; /* p is a pointer to a long int */

float* pf; /* pf is a pointer to a float */

char c, d, *pc; /* c and d are a char pc is a pointer to char */

double* pd, e, f; /* pd is pointer to a double e and f are double */

char* start; /* start is a pointer to a char */

char* end; /* end is a pointer to a char */

Page 91: C  -  Programming  ppt

The “&” Operator

The “&”, “address of” operator, generates the address of a variable

All variables have addresses except register variables

char g = 'z';

char c = 'a';char *p;

p = &c;p = &g;

'a'0x11320x1132

'z'0x91A20x91A2

Page 92: C  -  Programming  ppt

Pointers may only point to variables of the same type as the pointer has been declared to point to

A pointer to an int may only point to an int– not to char, short int or long int, certainly not to float,

double or long double

A pointer to a double may only point to a double– not to float or long double, certainly not to char or any of

the integers

int *p; /* p is a pointer to an int */long large = 27L; /* large is a long int,

initialised with 27 */

p = &large; /* ERROR */

Page 93: C  -  Programming  ppt

The “*” Operator

The “*”, “points to” operator, finds the value at the end of a pointer

p = &c;printf("%c\n", *p);

p = &g;printf("%c\n", *p);

return 0;} a

print “what p points to”

Page 94: C  -  Programming  ppt

Writing Down Pointers

It is not only possible to read the values at the end of a pointer as with:

It is possible to write over the value at the end of a pointer:

p = &c;*p = 'b';printf("%c\n", *p);

make what p points to equal to ‘b’

Page 95: C  -  Programming  ppt

Initialisation Warning!

The following code contains a horrible error:

short i = 13;short *p;

*p = 23;printf("%hi\n", *p);

Page 96: C  -  Programming  ppt

Initialise Pointers!

Pointers are best initialised! A pointer may be declared and initialised in a

single step

short i = 13;short *p = &i;

This does NOT mean “make what p points to equal to the address of i”

It DOES mean “declare p as a pointer to a short int, make p equal to the address of i”

short *p = &i;short *p = &i; short *p = &i;short *p = &i;

short *p = &i;short *p = &i;

Page 97: C  -  Programming  ppt

A special invalid pointer value exists #defined in various header files, called NULL

When assigned to a pointer, or when found in a pointer, it indicates the pointer is invalid

short i = 13;short *p = NULL;

if(p == NULL)printf("the pointer is invalid!\n");

elseprintf("the pointer points to %hi\n", *p);

Page 98: C  -  Programming  ppt

A World of Difference!

There is a great deal of difference between:

int i = 10, j = 14;int *p = &i;int *q = &j;

100x15A00x15A0

0x15A40x15A4

Page 99: C  -  Programming  ppt

Fill in the Gaps

int i = 10, j = 14, k;int *p = &i;int *q = &j;

p = &k;

Page 100: C  -  Programming  ppt

Type Mismatch

The compiler will not allow type mismatches when assigning to pointers, or to where pointers point

p = *q;*p = q;

cannot write 0x15A4 into i cannot write

Page 101: C  -  Programming  ppt

Call by Value - Reminder

Page 102: C  -  Programming  ppt

Call by Reference

void change(int* p);

change(&var);

void change(int* p){

*p *= 100;printf("change: *p = %i\n", *p);

change: *p = 500main: var = 500

prototype “forces” us to pass a pointer

Page 103: C  -  Programming  ppt

Pointers to Pointers

C allows pointers to any type It is possible to declare a pointer to a pointer

int i = 16;int *p = &i;int **pp;

pp = &p;printf("%i\n", **pp);

pp is a “pointer to” a “pointer to an int”

Page 104: C  -  Programming  ppt

int i = 10, j = 7, k;int *p = &i;int *q = &j;int *pp = &p;

*pp = &k;

i = *q***pp;

i = *q/**pp; /* headache? */;

Page 105: C  -  Programming  ppt

Arrays in C

Declaring arrays Accessing elements Passing arrays into functions Using pointers to access arrays Strings The null terminator

Page 106: C  -  Programming  ppt

Declaring Arrays

An array is a collection of data items (called elements) all of the same type

It is declared using a type, a variable name and a CONSTANT placed in square brackets

C always allocates the array in a single block of memory

The size of the array, once declared, is fixed forever - there is no equivalent of, for instance, the “redim” command in BASIC

Page 107: C  -  Programming  ppt

#define SIZE 10int a[5]; /* a is an array of 5 ints */long int big[100]; /* big is 400 bytes! */double d[100]; /* but d is 800 bytes! */long double v[SIZE]; /* 10 long doubles, 100 bytes */

int a[5] = { 10, 20, 30, 40, 50 };double d[100] = { 1.5, 2.7 };short primes[] = { 1, 2, 3, 5, 7, 11, 13 };long n[50] = { 0 };

int i = 7;const int c = 5;

int a[i];double d[c];short primes[];

all five elements initialised

first two elements initialised,

remaining ones set to zero

compiler fixes size at 7 elements

quickest way of settingALL elements to zero

Page 108: C  -  Programming  ppt

Accessing Elements

The elements are accessed via an integer which ranges from 0..size-1

There is no bounds checking

int a[6];int i = 7;

a[0] = 59;a[5] = -10;a[i/2] = 2;

a[6] = 0;a[-1] = 5;

Page 109: C  -  Programming  ppt

Array Names

There is a special and unusual property of array names in C

The name of an array is a pointer to the start of the array, i.e. the zeroth element, thus

a == &a[0]

int a[10];int *p;

float f[5]float *fp;

p = a; /* p = &a[0] */

fp = f; /* fp = &f[0] */

Page 110: C  -  Programming  ppt

Passing Arrays to Functions

When an array is passed to a function a pointer to the zeroth element is passed across

The function may alter any element The corresponding parameter may be declared as

a pointer, or by using the following special syntax

int add_elements(int a[], int size){

int add_elements(int *p, int size){

Page 111: C  -  Programming  ppt

void sum(long [], int);

long primes[6] = { 1, 2,3, 5, 7, 11 };

sum(primes, 6);

printf("%li\n", primes[0]);

void sum(long a[], int sz){

int i;long total = 0;

for(i = 0; i < sz; i++)total += a[i];

a[0] = total;}

the total is written over element zero

provides bounds checking

Page 112: C  -  Programming  ppt

Using Pointers

Pointers may be used to access array elements rather than using constructs involving “[ ]”

Pointers in C are automatically scaled by the size of the object pointed to when involved in arithmetic

long v[6] = { 1,2, 3,4,5,6 };

p = v;printf("%ld\n", *p);p++;printf("%ld\n", *p);p += 4;printf("%ld\n", *p);

1000 1 2 3 4 5 6

Page 113: C  -  Programming  ppt

Pointers Go Backwards Too

Scaling not only happens when addition is done, it happens with subtraction too

p = v + 5;printf("%ld\n", *p);p--;printf("%ld\n", *p);p -= 2;printf("%ld\n", *p);

1020 1 2 3 4 5 6

Page 114: C  -  Programming  ppt

Pointers May be Subtracted

When two pointers into the same array are subtracted C scales again, giving the number of array elements separating them

double d[7] = { 1.1, 2.2,3.3, 4.4, 5.5, 6.6, 7.7 };

double *p1;double *p2;

p1 = d + 1;p2 = d + 6;

printf("%i\n", p2 - p1);

1.1 2.2 3.3 4.4 5.5 6.6 7.7

2016 2032 20482024 2040

Page 115: C  -  Programming  ppt

Using Pointers - Example

long sum(long*, int);

printf("%li\n", sum(primes, 6));

long sum(long *p, int sz){

long *end = p + sz;long total = 0;

while(p < end)total += *p++;

return total;}

Page 116: C  -  Programming  ppt

*p++ means:*p++ find the value at the end of the pointer*p++ increment the POINTER to point to the

next element(*p)++ means:

(*p)++ find the value at the end of the pointer(*p)++ increment the VALUE AT THE END OF THE POINTER (the pointer never moves)

*++p means:*++p increment the pointer*++p find the value at the end of the pointer

Page 117: C  -  Programming  ppt

Which Notation?

An axiom of C states a[i] is equivalent to *(a + i)

short a[8] = { 10, 20, 30, 40, 50, 60, 70, 80 };short *p = a;

printf("%i\n", a[3]);printf("%i\n", *(a + 3));printf("%i\n", *(p + 3));printf("%i\n", p[3]);printf("%i\n", 3[a]);

10 20 30 40 50 60 70 80

1000 1004 1008 10121002 1006 1010 1014

Page 118: C  -  Programming  ppt

C has no native string type, instead we use arrays of char

A special character, called a “null”, marks the end (don’t confuse this with the NULL pointer )

This may be written as ‘\0’ (zero not capital ‘o’) This is the only character whose ASCII value is

zero Depending on how arrays of characters are built,

we may need to add the null by hand, or the compiler may add it for us

Page 119: C  -  Programming  ppt

char first_name[5] = { 'J', 'o', 'h', 'n', '\0' };

char last_name[6] = "Minor";

char other[] = "Tony Blurt";

char characters[7] = "No null";

'J' 'o' 'h' 'n' 0first_name

'M' 'i' 'n' 'o' 'r'last_name 0

'T' 'o' 'n' 'y' 32other 'B' 'l' 'u' 'r' 't' 0

'N' 'o' 32 'n' 'u'characters 'l' 'l'

this special case specifically excludes the null terminator

Page 120: C  -  Programming  ppt

Printing Strings

Strings may be printed by hand Alternatively printf supports “%s”

char other[] = "Tony Blurt";char other[] = "Tony Blurt";

p = other;while(*p != '\0')

printf("%c", *p++);printf("\n");

while(other[i] != '\0')printf("%c", other[i++]);

printf("\n");

printf("%s\n", other);printf("%s\n", other);

Page 121: C  -  Programming  ppt

Null Really Does Mark the End!

printf("%s\n", other);

other[4] = '\0';

return 0;} Tony Blurt

Tony BlurtTony

even though the rest of the data is still there, printf will NOT move past the null terminator

Page 122: C  -  Programming  ppt

Assigning to Strings

Strings may be initialised with “=”, but not assigned to with “=”

Remember the name of an array is a CONSTANT pointer to the zeroth element

#include <stdio.h>#include <string.h>

char who[] = "Tony Blurt";

who = "John Minor";

strcpy(who, "John Minor");

Page 123: C  -  Programming  ppt

Pointing to Strings

To save us declaring many character arrays to store strings, the compiler can store them directly in the data segment

We need only declare a pointer The compiler may recycle some of these strings,

therefore we must NOT alter any of the characters

char *p = "Data segment!!";char *q = "nt!!";

'D' 'a' 't' 'a' 32 's' 'e' 'g' 'm' 'e' 'n' 't' '!' '!' 0

0xF100 0xF10A

Page 124: C  -  Programming  ppt

char *p = "a string in the data segment\n";

"a second string in the data segment\n";

printf("a third string in the data segment\n");

printf("%s", p);

this utterly pointless statement causes the compiler to store the characters, unfortunately we forget to save the address

a third string in the data segmenta string in the data segmenta string in the data segment

Page 125: C  -  Programming  ppt

Multidimensional Arrays

C does not support multidimensional arrays However, C does support arrays of any type

including arrays of arrays

float rainfall[12][365];float rainfall[12][365]; “rainfall” is an array of 12 arrays of 365 float

short exam_marks[500][10];short exam_marks[500][10]; “exam_marks” is an array of 500 arrays of 10 short int

const int brighton = 7;int day_of_year = 238;

rainfall[brighton][day_of_year] = 0.0F;

Page 126: C  -  Programming  ppt

int i;int a[10];

for(i = 0; i <= 10; i++) {printf("%d\n", i);a[i] = 0;

How many times does the following program loop?

Page 127: C  -  Programming  ppt

Arrays are declared with a type, a name, “[ ]” and a CONSTANT

Access to elements by array name, “[ ]” and an integer

Arrays passed into functions by pointer Pointer arithmetic Strings - arrays of characters with a null

terminator Sometimes compiler stores null for us (when

double quotes are used) otherwise we have to store it ourselves

Page 128: C  -  Programming  ppt

Structures in C

Concepts Creating a structure template Using the template to create an instance Initializing an instance Accessing an instance’s members Passing instances to functions Linked lists

Page 129: C  -  Programming  ppt

A structure is a collection of one of more variables grouped together under a single name for convenient handling

The variables in a structure are called members and may have any type, including arrays or other structures

The steps are:– set-up a template (blueprint) to tell the compiler how to build

the structure

– Use the template to create as many instances of the structure as desired

– Access the members of an instance as desired

Page 130: C  -  Programming  ppt

Setting up the Template

Structure templates are created by using the struct keyword

struct Book{

char title[80];char author[80];float price;char isbn[20];

struct Date{

int day;int month;int year;

struct Library_member{

char name[80];char address[200];long member_number;float fines[10];struct Date dob;struct Date enrolled;

struct Library_book{

struct Book b;struct Date due;struct Library_member *who;

Page 131: C  -  Programming  ppt

Creating Instances

Having created the template, an instance (or instances) of the structure may be declared

} today, tomorrow;

struct Date next_monday;

struct Date next_week[7];

an array of 7 date instances

instances must be declared before the ‘;’ ...

... or “struct Date” has to be repeated

Page 132: C  -  Programming  ppt

Initialising Instances

Structure instances may be initialised using braces (as with arrays)

int primes[7] = { 1, 2, 3, 5, 7, 11, 13 };

struct Date bug_day = { 1, 1, 2000 };

struct Book k_and_r = {"The C Programming Language 2nd edition","Brian W. Kernighan and Dennis M. Ritchie",31.95,"0-13-110362-8"

}; struct Book{

Page 133: C  -  Programming  ppt

Structures Within Structures

struct Library_member m = {"Arthur Dent","16 New Bypass",42,{ 0.10, 2.58, 0.13, 1.10 },{ 18, 9, 1959 },{ 1, 4, 1978 }

initialises first 4 elements of array “fines”, remainder are initialised to 0.0

initialises day, month and year of “dob”

initialises day, month and year of “enrolled”

Page 134: C  -  Programming  ppt

Accessing Members

Members are accessed using the instance name, “.” and the member name

printf("name = %s\n", m.name);printf("membership number = %li\n", m.member_number);

printf("fines: ");for(i = 0; i < 10 && m.fines[i] > 0.0; i++)

printf("£%.2f ", m.fines[i]);

printf("\njoined %i/%i/%i\n", m.enrolled.day,m.enrolled.month, m.enrolled.year);

struct Library_member m;struct Library_member m;

Page 135: C  -  Programming  ppt

Unusual Properties

Structures have some very “un-C-like” properties, certainly when considering how arrays are handled

Arrays Structures

Name is pointer to the structure itselfzeroth element

Passed to functions by pointer value or pointer

Returned from functions no way by value or pointer

May be assigned with “=” no way yes

Page 136: C  -  Programming  ppt

Instances may be Assigned

Two structure instances may be assigned to one another via “=”

All the members of the instance are copied (including arrays or other structures)

struct Library_member m = {"Arthur Dent",.....

};struct Library_member tmp;

copies array “name”, array “address”, long integer “member_number”, array “fines”, Date structure “dob” and Date structure “enrolled”

Page 137: C  -  Programming  ppt

Passing Instances to Functions

An instance of a structure may be passed to a function by value or by pointer

Pass by value becomes less and less efficient as the structure size increases

Pass by pointer remains efficient regardless of the structure size

void by_value(struct Library_member);void by_reference(struct Library_member *);

by_value(m);by_reference(&m);

compiler writes a pointer (4 bytes?) onto the stack

compiler writes 300+ bytes onto the stack

Page 138: C  -  Programming  ppt

Pointers to Structures

Passing pointers to structure instances is more efficient

Dealing with an instance at the end of a pointer is not so straightforward!

void member_display(struct Library_member *p){

printf("name = %s\n", (*p).name);printf("membership number = %li\n", (*p).member_number);

printf("fines: ");for(i = 0; i < 10 && (*p).fines[i] > 0.0; i++)

printf("£%.2f ", (*p).fines[i]);

printf("\njoined %i/%i/%i\n", (*p).enrolled.day,(*p).enrolled.month, (*p).enrolled.year);

Page 139: C  -  Programming  ppt

Why (*p).name ?

The messy syntax is needed because “.” has higher precedence than “*”, thus:

means “what p.name points to” (a problem because there is no structure instance “p”)

As Kernighan and Ritchie foresaw pointers and structures being used frequently they invented a new operator

p->name = (*p).name

Page 140: C  -  Programming  ppt

Using p->name

Now dealing with the instance at the end of the pointer is more straightforward

printf("name = %s\n", p->name);printf("address = %s\n", p->address);printf("membership number = %li\n", p->member_number);

printf("fines: ");for(i = 0; i < 10 && p->fines[i] > 0.0; i++)

printf("£%.2f ", p->fines[i]);

printf("\njoined %i/%i/%i\n", p->enrolled.day,p->enrolled.month, p->enrolled.year);

Page 141: C  -  Programming  ppt

Pass by Reference - Warning

Although pass by reference is more efficient, the function can alter the structure (perhaps inadvertently)

Use a pointer to a constant structure instead

printf("fines: ");for(i = 0; i < 10 && p->fines[i] = 0.0; i++)

printf("£%.2f ", p->fines[i]);}

void member_display(const struct Library_member *p){

function alters the library member instance

Page 142: C  -  Programming  ppt

Returning Structure Instances

Structure instances may be returned by value from functions

This can be as inefficient as with pass by value Sometimes it is convenient!

struct Complex add(struct Complex a, struct Complex b){

struct Complex result = a;

result.real_part += b.real_part;result.imag_part += b.imag_part;

return result;} struct Complex c1 = { 1.0, 1.1 };

struct Complex c2 = { 2.0, 2.1 };struct Complex c3;

c3 = add(c1, c2); /* c3 = c1 + c2 */

struct Complex c1 = { 1.0, 1.1 };struct Complex c2 = { 2.0, 2.1 };struct Complex c3;

Page 143: C  -  Programming  ppt

Linked Lists

A linked list node containing a single forward pointer may be declared as follows

struct Node {int data; /* or whatever */struct Node *next_in_line;

pointer to next Node structure

A linked list node containing a forward and a backward pointer may be declared as follows

struct Node {int data;struct Node *next_in_line;struct Node *previous_in_line;

};pointer to previous Node structure

Page 144: C  -  Programming  ppt

struct Node {char name[10];struct Node *next_in_line;

struct Node a1 = { "John", NULL };struct Node a2 = { "Harriet", &a1 },struct Node a3 = { "Claire", &a2 }struct Node a4 = { "Tony", &a3 };

0x1020 0x102E 0x1032 NULL

Page 145: C  -  Programming  ppt

Printing the List

The list may be printed with the following code:

struct Node * current = &a4;

while(current != NULL) {printf("%s\n", current->name);current = current->next_in_line;

Page 146: C  -  Programming  ppt

Creating structure templates using struct Creating and initialising instances Accessing members Passing instances to functions by value and by

reference A new operator: “->” Return by value Linked lists

Page 147: C  -  Programming  ppt

Reading C Declarations

Introduction SOAC Examples typedef Examples revisited

Page 148: C  -  Programming  ppt

Introduction

Up until now we have seen straightforward declarations:

void member_display(const struct Library_member *p);void member_display(const struct Library_member *p);

However, they can become much worse:

int *p[15];float (*pfa)[23];long (*f)(char, int);double *(*(*n)(void))[5];

long sum;int* p;

Plus a few trickier ones:

Page 149: C  -  Programming  ppt

Find the variable being declared Spiral Outwards Anti Clockwise On meeting: say:

* pointer to

[ ] array of

( ) function taking .... and returning

Remember to read “struct S”, “union U” or “enum E” all at once

Remember to read adjacent collections of [ ] [ ] all at once

Page 150: C  -  Programming  ppt

What is “int * p[15]” ?

int * p [15] ;

p is an array of 15 pointers to integers

Page 151: C  -  Programming  ppt

What is “double (*p)[38]” ?

double (* p ) [38];

p is a pointer to an array of 38 doubles

Page 152: C  -  Programming  ppt

What is “short **ab[5][10]” ?

short * * ab [5][10] ;

ab is an array of 5 arrays of 10 arrays of pointers to pointers to short int

Page 153: C  -  Programming  ppt

What is “long * f(int, float)” ?

long * f (int, float) ;

f is a function taking an int and a float returning a pointer to a long int

Page 154: C  -  Programming  ppt

What is “int (*pf)(void)” ?

int ( * pf ) (void) ;

pf is a pointer to a function taking no parameters and returning an int

Page 155: C  -  Programming  ppt

What is “struct Book (*fpa[8])(void)” ?

struct Book ( * fpa[8] ) (void) ;

fpa is an array of 8 pointers to functions, taking no parameters, returning Book structures

Page 156: C  -  Programming  ppt

What is “char (*(*fprp)(void))[6]” ?

char ( * ( * fprp ) (void) ) [6] ;

fprp is a pointer to a function taking no parameters returning a pointer to an array of 6 char

Page 157: C  -  Programming  ppt

What is “int * (*(*ptf)(int))(char)” ?

int * ( * ( * ptf ) (int) ) (char) ;

ptf is a pointer to a function, taking an integer, returning a pointer to a function, taking a char, returning a pointer to an int

Page 158: C  -  Programming  ppt

It doesn’t have to be this difficult! The declaration can be broken into simpler steps

by using typedef To tackle typedef, pretend it isn’t there and read

the declaration as for a variable When finished remember that a type has been

declared, not a variable

Page 159: C  -  Programming  ppt

Example 1 Revisited

Simplify “int * p[15]”

typedef int * pti ;

pti is a pointer to an int

p is an array of 15 pointer to int

Page 160: C  -  Programming  ppt

Example 3 Revisited

Simplify “short **ab[5][10]”

typedef short * * pt_pt_s ;

ab is an array of 10 arrays of 5 pointers to pointers to short

typedef pt_pt_s ao5[5];

ao5 ab[10];

ao5 is an array of 5 pointers to pointers to short

pt_pt_s is a pointer to a pointer to a short

Page 161: C  -  Programming  ppt

Example 5 Revisited

Simplify “int (*pf)(void)”

typedef int fri(void); fri * pf ;

fri is a function, taking no parameters, returning an int

pf is a pointer to a function, taking no parameters,

returning an int

Page 162: C  -  Programming  ppt

Example 6 Revisited

Simplify “struct Book (*fpa[8])(void)”

typedef struct Book f(void);

f is a function, taking no parameters, returning a

Book structure

typedef f * fp ;

fp is a pointer to a function, taking no parameters,

returning a Book structure

fpa is an array of 8 pointers to functions, taking no parameters, returning a

Page 163: C  -  Programming  ppt

Example 7 Revisited

Simplify “char (*(*fprp)(void))[6]”

typedef char ( * pta6c ) [6] ;

pta6c is a pointer to an array of 6 char

typedef pta6c f(void);

f is a function, taking no parameters, returning a pointer to an array of 6

fprp is a pointer to a function, taking no

parameters, returning a pointer to an array of 6

Page 164: C  -  Programming  ppt

Example 8 Revisited

Simplify “int * (*(*ptf)(int))(char)”

typedef pti f(char);

f is a function, taking a char, returning a pointer

typedef f * ptfri ;

ptfri is a pointer to a function, taking a char,

returning a pointer to an int

ptfri ( * ptf )(int) ;

ptf is a pointer to a function, taking int, returning a pointer to a function, taking a

char, returning a pointer to an int

Page 165: C  -  Programming  ppt

Don’t Panic! SOAC - Spiral Outwards Anti Clockwise To simplify, use typedef(s)

Page 166: C  -  Programming  ppt

Handling Files in C

Streams stdin, stdout, stderr Opening files When things go wrong - perror Copying files Accessing the command line Dealing with binary files

Page 167: C  -  Programming  ppt

File handling is not built into the C language itself It is provided by The Standard Library (via a set

of routines invariably beginning with “f”) Covered by The Standard, the routines will

always be there and work the same way, regardless of hardware/operating system

Files are presented as a sequence of characters It is easy to move forwards reading/writing

characters, it is less easy (though far from impossible) to go backwards

Page 168: C  -  Programming  ppt

Before a file can be read or written, a data structure known as a stream must be associated with it

A stream is usually a pointer to a structure (although it isn’t necessary to know this)

There are three streams opened by every C program, stdin, stdout and stderr

stdin (standard input) is connected to the keyboard and may be read from

stdout (standard output) and stderr (standard error) are connected to the screen and may be written to

Page 169: C  -  Programming  ppt

What is a Stream?

Although implementations vary, a stream creates a buffer between the program running in memory and the file on the disk

This reduces the program’s need to access slow hardware devices

Characters are silently read a block at a time into the buffer, or written a block at a time to the file

a b c d ef gh i j k l

output stream

a b c de f g hi j

input stream

Page 170: C  -  Programming  ppt

Why stdout and stderr?

There are two output streams because of redirection, supported by Unix, DOS, OS/2 etc.

printf("written to stdout\n");fprintf(stderr, "written to stderr\n");

C:> outprogwritten to stderrwritten to stdoutC:> outprog > file.txtwritten to stderrC:> type file.txtwritten to stdout

output written to stderr first because it is unbuffered

Page 171: C  -  Programming  ppt

stdin is Line Buffered

Characters typed at the keyboard are buffered until Enter/Return is pressed

while((ch = getchar()) != EOF)printf("read '%c'\n", ch);

printf("EOF\n");

C:> inprogabcread 'a'read 'b'read 'c'read ''dread 'd'read ''^ZEOFC:>

C:> inprogabcread 'a'read 'b'read 'c'read ''dread 'd'read ''^ZEOFC:>declared as an int, even though

we are dealing with characters

Page 172: C  -  Programming  ppt

Opening Files

Files are opened and streams created with the fopen function

FILE* fopen(const char* name, const char* mode);FILE* fopen(const char* name, const char* mode);

FILE* in;FILE* out;FILE* append;

in = fopen("autoexec.bat", "r");out = fopen("autoexec.bak", "w");append = fopen("config.sys", "a");

streams, you’ll need one for each

file you want open

Page 173: C  -  Programming  ppt

if((in = fopen("autoexec.bat", "r")) == NULL) {fprintf(stderr, "open of autoexec.bat failed ");perror("because");return 1;

Dealing with Errors

fopen may fail for one of many reasons, how to tell which?

void perror(const char* message);void perror(const char* message);

open of autoexec.bat failed because: No such file or directoryopen of autoexec.bat failed because: No such file or directory

Page 174: C  -  Programming  ppt

File Access Problem

Can you see why the following will ALWAYS fail, despite the file existing and being fully accessible?

if((in = fopen("C:\autoexec.bat", "r")) == NULL) {fprintf(stderr, "open of autoexec.bat failed ");perror("because");return 1;

C:> dir C:\autoexec.bat Volume in drive C is MS-DOS_62 Directory of C:\

autoexec bat 805 29/07/90 8:15 1 file(s) 805 bytes 1,264,183,808 bytes freeC:> myprogopen of autoexec.bat failed because: No such file or directory

Page 175: C  -  Programming  ppt

Displaying a File

char in_name[80];FILE *in_stream;int ch;

printf("Display file: ");scanf("%79s", in_name);

if((in_stream = fopen(in_name, "r")) == NULL) {fprintf(stderr, "open of %s for reading failed ", in_name);perror("because");return 1;

while((ch = fgetc(in_stream)) != EOF)putchar(ch);

fclose(in_stream);

Page 176: C  -  Programming  ppt

Example - Copying Files#include <stdio.h>

char in_name[80], out_name[80];FILE *in_stream, *out_stream;int ch;

printf("Source file: "); scanf("%79s", in_name);if((in_stream = fopen(in_name, "r")) == NULL) {

fprintf(stderr, "open of %s for reading failed ", in_name);perror("because");return 1;

printf("Destination file: "); scanf("%79s", out_name);if((out_stream = fopen(out_name, "w")) == NULL) {

fprintf(stderr, "open of %s for writing failed ", out_name);perror("because");return 1;

while((ch = fgetc(in_stream)) != EOF)fputc(ch, out_stream);

fclose(in_stream);fclose(out_stream);

Page 177: C  -  Programming  ppt

Convenience Problem

Although our copy file program works, it is not as convenient as the “real thing”

C:> copyprogSource file: \autoexec.batDestination file: \autoexec.bakC:> dir C:\autoexec.* Volume in drive C is MS-DOS_62 Directory of C:\

autoexec bak 805 31/12/99 12:34autoexec bat 805 29/07/90 8:15 2 file(s) 1610 bytes 1,264,183,003 bytes freeC:> copyprog \autoexec.bat \autoexec.000Source file:

program still prompts despite begin given file names on the command line

Page 178: C  -  Programming  ppt

Accessing the Command Line

The command line may be accessed via two parameters to main, by convention these are called “argc” and “argv”

The first is a count of the number of words - including the program name itself

The second is an array of pointers to the words

int main(int argc, char *argv[])int main(int argc, char *argv[])

c o p y p r o g . e x e \0

\ a u t o e x e c . b a t \0

\ a u t o e x e c . 0 0 0 \0

Page 179: C  -  Programming  ppt

int main(int argc, char *argv[]){

for(j = 0; j < argc; j++)printf("argv[%i] = \"%s\"\n", j, argv[j]);

C:> argprog one two threeargv[0] = "C:\cct\course\cprog\files\slideprog\argprog.exe"argv[1] = "one"argv[2] = "two"argv[3] = "three"

Page 180: C  -  Programming  ppt

Useful Routines

File reading routines:

int fscanf(FILE* stream, const char* format, ...);int fgetc(FILE* stream);char* fgets(char* buffer, int size, FILE* stream);

File writing routines:

int fprintf(FILE* stream, const char* format, ...);int fputc(int ch, FILE* stream);int fputs(const char* buffer, FILE* stream);

Page 181: C  -  Programming  ppt

long l1, l2;int j, ch;double d;float f;char buf[200];

in = fopen("in.txt", "r") .... out = fopen("out.txt", "w") ....

fscanf(in, "%lf|%li:%li/%i", &d, &l1, &l2, &j);fprintf(out, "%li:%i:%.2lf\n", l1, j, d);

fgets(buf, sizeof(buf), in);fputs(buf, out);

example input

28.325|9000000:68000/1328.325|9000000:68000/13

write that line to the output file (null terminator provided by fgets tells fputs how long the line was)

read next line, or next 199 characters,

whichever is less

ignore next character in input file (newline?)

9000000:13:28.339000000:13:28.33

Page 182: C  -  Programming  ppt

Binary Files

The Standard Library also allows binary files to be manipulated– “b” must be added into the fopen options

– Character translation is disabled

– Random access becomes easier

– Finding the end of file can become more difficult

– Data is read and written in blocks

size_t fread(void* p, size_t size, size_t n, FILE* stream);size_t fwrite(const void* p, size_t size, size_t n, FILE* stream);

int fseek(FILE* stream, long offset, int whence);long ftell(FILE* stream);void rewind(FILE* stream);

int fgetpos(FILE* stream, fpos_t* pos);int fsetpos(FILE* stream, const fpos_t* pos);

Page 183: C  -  Programming  ppt

double d;long double lda[35];fpos_t where;

in = fopen("binary.dat", "rb");out = fopen("binnew.dat", "wb");

fread(&d, sizeof(d), 1, in);

fgetpos(in, &where);fread(lda, sizeof(lda), 1, in);

fsetpos(in, &where);fread(lda, sizeof(long double), 35, in);

fwrite(lda, sizeof(long double), 20, out);

fseek(in, 0L, SEEK_END);

read one chunk of 8 bytes

read one chunk of 350 bytes

read 35 chunks of 10 bytes

remember current position in file

return to previous position

write 20 long doubles from ldamove to end of binary.dat

Page 184: C  -  Programming  ppt

Streams stdin, stdout, stderr fopen opening text files functions: perror, fprintf, fscanf, fgetc, fputc

variables: argc, argv “b” option to fopen to open binary files functions: fread, fwrite, fseek, ftell

Page 185: C  -  Programming  ppt

Miscellaneous Things

Unions Enumerated types The Preprocessor Working with multiple .c files

Page 186: C  -  Programming  ppt

A union is a variable which, at different times, may hold objects of different types and sizes

short s;long l;double d;char c;

s.s = 10;s.l = 10L;s.d = 10.01;s.c = '1';

u.s = 10;u.l = 10L;u.d = 10.01;u.c = '1';

Page 187: C  -  Programming  ppt

Remembering

It is up to the programmer to remember what type a union currently holds

Unions are most often used in structures where a member records the type currently stored

struct preprocessor_const{

char* name;int stored;union{

long lval;double dval;char* sval;

#define N_SIZE 10#define PI 3.1416

struct preprocessor_const s[10000];

s[0].name = "N_SIZE";s[0].u.lval = 10L;s[0].stored = STORED_LONG;

s[1].name = "PI"; s[1].u.dval = 3.1416;s[1].stored = STORED_DOUBLE;

Page 188: C  -  Programming  ppt

Enumerated Types

Enumerated types provide an automated mechanism for generating named constants

enum day { sun, mon, tue,wed, thu, fri, sat };

enum day today = sun;

if(today == mon)....

#define sun 0#define mon 1#define tue 2#define wed 3#define thu 4#define fri 5#define sat 6

int today = sun;

Page 189: C  -  Programming  ppt

Using Different Constants

The constants used may be specified

enum day { sun = 5, mon, tue, wed, thu, fri, sat };

enum direction { north = 0, east = 90, south = 180,west = 270 };

What you see is all you get! There are no successor or predecessor functions

Page 190: C  -  Programming  ppt

The Preprocessor

Preprocessor commands start with ‘#’ which may optionally be surrounded by spaces and tabs

The preprocessor allows us to:

– include files

– define, test and compare constants

– write macros

Page 191: C  -  Programming  ppt

Including Files

The #include directive causes the preprocessor to “edit in” the entire contents of another file

#define JAN 1#define FEB 2#define MAR 3

#define PI 3.1416

double my_global;

#include "mydefs.h"

double angle = 2 * PI;printf("%s", month[FEB]);

double angle = 2 * 3.1416;printf("%s", month[2]);

Page 192: C  -  Programming  ppt

Full pathnames may be used, although this is not recommended

#include "C:\cct\course\cprog\misc\slideprog\header.h"#include "C:\cct\course\cprog\misc\slideprog\header.h"

The “I” directive to your local compiler allows code to be moved around much more easily

#include "header.h"#include "header.h"

cc -I c:\cct\course\cprog\misc\slideprog myprog.ccc -I c:\cct\course\cprog\misc\slideprog myprog.c

Page 193: C  -  Programming  ppt

Constants may be created, tested and removed

#if !defined(SUN)#define SUN 0#endif

#if SUN == MON#undef SUN#endif

if “SUN” is not defined, then begin

define “SUN” as zero

#if SUN > SAT && SUN > MON#if SUN > SAT && SUN > MON

#if WED > 0 || SUN < 3#if WED > 0 || SUN < 3

#if TUE#if TUE if “TUE” is defined with a non zero value

if “WED” is greater than zero or “SUN” is less than 3

if “SUN” is greater than “SAT” and “SUN” is greater than “MON”

if “SUN” and “MON” are equal, then begin

remove definition of “SUN”

Page 194: C  -  Programming  ppt

Avoid Temptation!

The following attempt to write Pascal at the C compiler will ultimately lead to tears

#define begin {#define end ;}#define if if(#define then )#define integer int

if i > 0 then begini = 17

if( i > 0 ) {i = 17

Page 195: C  -  Programming  ppt

Preprocessor Macros

The preprocessor supports a macro facility which should be used with care

#define MAX(A,B) A > B ? A : B#define MIN(X,Y) ((X) < (Y) ? (X) : (Y))

int i = 10, j = 12, k;

k = MAX(i, j); printf("k = %i\n", k);k = MAX(j, i) * 2; printf("k = %i\n", k);k = MIN(i, j) * 3; printf("k = %i\n", k);k = MIN(i--, j++); printf("i = %i\n", i);

k = MAX(i, j); printf("k = %i\n", k);k = MAX(j, i) * 2; printf("k = %i\n", k);k = MIN(i, j) * 3; printf("k = %i\n", k);k = MIN(i--, j++); printf("i = %i\n", i); k = 12

k = 12k = 30i = 8

k = 12k = 12k = 30i = 8

Page 196: C  -  Programming  ppt

A Debugging Aid

Several extra features make the preprocessor an indespensible debugging tool

#define GOT_HERE printf("reached %i in %s\n", \_ _LINE_ _, _ _FILE_ _)

#define SHOW(E, FMT) printf(#E " = " FMT "\n", E)

printf("i = %x\n", i);printf("i = %x\n", i);

printf("reached %i in %s\n", 17, "mysource.c");printf("reached %i in %s\n", 17, "mysource.c");

GOT_HERE;SHOW(i, "%x");SHOW(f/29.5, "%lf");

printf("f/29.5 = %lf\n", f/29.5);printf("f/29.5 = %lf\n", f/29.5);

Page 197: C  -  Programming  ppt

Working With Large Projects

Large projects may potentially involve many hundreds of source files (modules)

Global variables and functions in one module may be accessed in other modules

Global variables and functions may be specifically hidden inside a module

Maintaining consistency between files can be a problem

Page 198: C  -  Programming  ppt

Data Sharing Example

extern float step;

void print_table(double, float);

step = 0.15F;

print_table(0.0, 5.5F);

float step;

void print_table(double start, float stop){

printf("Celsius\tFarenheit\n");for(;start < stop; start += step)

printf("%.1lf\t%.1lf\n", start, start * 1.8 + 32);

Page 199: C  -  Programming  ppt

Data Hiding Example

When static is placed before a global variable, or function, the item is locked into the module

static int entries[S_SIZE];static int current;

void push(int value){

entries[current++] = value}

int pop(void){

return entries[--current];}

static void print(void){}

void push(int value);int pop(void);void print(void);extern int entries[];

push(10); push(15);printf("%i\n", pop());

entries[3] = 77;

Page 200: C  -  Programming  ppt

double step;

void print_table(double start, double stop){

Page 201: C  -  Programming  ppt

Use Header Files

Maintain consistency between modules by using header files

NEVER place an extern declaration in a module NEVER place a prototype of a non static (i.e.

sharable) function in a module

Page 202: C  -  Programming  ppt

Getting it Right

extern double step;

void print_table(double, double);

#include "project.h"

#include <stdio.h>#include "project.h"

Page 203: C  -  Programming  ppt

Be as Lazy as Possible

Get the preprocessor to declare the variables too!

#if defined(MAIN)#define EXTERN#else#define EXTERN extern#endif

EXTERN double step;EXTERN long current;EXTERN short res;

#define MAIN#include "globals.h"

#include "globals.h"#include "globals.h" #include "globals.h"#include "globals.h"

main.cfirst.c second.c

Page 204: C  -  Programming  ppt

A union may store values of different types at different times

enum provides an automated way of setting up constants

The preprocessor allows constants and macros to be created

Data and functions may be shared between modules

static stops sharing of data and functions Use the preprocessor in large, multi module

Page 205: C  -  Programming  ppt

C and the Heap

What is the Heap? Dynamic arrays The calloc/malloc/realloc and free routines Dynamic arrays of arrays Dynamic data structures

Page 206: C  -  Programming  ppt

What is the Heap?

An executing program is divided into four parts: Stack: provides storage for local variables, alters

size as the program executes Data segment: global variables and strings stored

here. Fixed size. Code segment: functions main, printf, scanf

etc. stored here. Read only. Fixed size Heap: otherwise known as “dynamic memory”

the heap is available for us to use and may alter size as the program executes

Page 207: C  -  Programming  ppt

How Much Memory?

With simple operating systems like MS-DOS there may only be around 64k available (depending on memory model and extended memory device drivers)

With complex operating systems using virtual memory like Unix, NT, OS/2, etc. it can be much larger, e.g. 2GB

In the future (or now with NT on the DEC Alpha) this will be a very large amount (17 thousand million GB)

Page 208: C  -  Programming  ppt

Dynamic Arrays

Arrays in C have a fundamental problem - their size must be fixed when the program is written

There is no way to increase (or decrease) the size of an array once the program is compiled

Dynamic arrays are different, their size is fixed at run time and may be changed as often as required

Only a pointer is required

Page 209: C  -  Programming  ppt

Using Dynamic Arrays

The following steps create a dynamic array: Declare a pointer corresponding to the desired

type of the array elements Initialise the pointer via calloc or malloc using

the total storage required for all the elements of the array

Check the pointer against NULL Increase or decrease the number of elements by

calling the realloc function Release the storage by calling free

Page 210: C  -  Programming  ppt

calloc/malloc Example

#include <stdio.h>#include <stdlib.h>

unsigned i, s;double *p;

printf("How many doubles? ");scanf("%u", &s);

if((p = calloc(s, sizeof(double))) == NULL) {fprintf(stderr, "Cannot allocate %u bytes "

"for %u doubles\n", s * sizeof(double), s);return 1;

}for(i = 0; i < s; i++)

here we access the “s” doubles from 0..s-1

if((p = malloc(s * sizeof(double))) == NULL) {if((p = malloc(s * sizeof(double))) == NULL) {

all of the allocated memory is freed

Page 211: C  -  Programming  ppt

realloc Exampledouble *p;double *p2;

printf("%u doubles currently, how many now? ", s);scanf("%u", &s);

p2 = realloc(p, s * sizeof(double));

if(p2 == NULL) {fprintf(stderr, "Could not increase/decrease array "

"to contain %u doubles\n", s);free(p);return 1;

double *p;double *p2;

calculate new array size and allocate

pointer “p” is invalid at this point, so a new value is assigned to it

pointer “p” is still valid at this point

Page 212: C  -  Programming  ppt

realloc can do it all

The routines malloc and free are almost redundant since realloc can do it all

There is some merit in calloc since the memory it allocates is cleared to zero

p = malloc(s * sizeof(double));p = malloc(s * sizeof(double));

p = realloc(NULL, s * sizeof(double));p = realloc(NULL, s * sizeof(double));

free(p);free(p);

realloc(p, 0);realloc(p, 0);

Page 213: C  -  Programming  ppt

Allocating Arrays of Arrays

Care must be taken over the type of the pointer used when dealing with arrays of arrays

p = calloc(s, sizeof(float));

float **rain;

rain = calloc(s, 365 * sizeof(float));

float (*rainfall)[365];

rainfall = calloc(s, 365 * sizeof(float));

rainfall[s-1][18] = 4.3F;

Page 214: C  -  Programming  ppt

Dynamic Data Structures

It is possible to allocate structures in dynamic memory too

struct Node {int data; struct Node *next_in_line;

struct Node* new_node(int value){

struct Node* p;

if((p = malloc(sizeof(struct Node))) == NULL) {fprintf(stderr, "ran out of dynamic memory\n");exit(9);

}p->data = value; p->next_in_line = NULL;

Page 215: C  -  Programming  ppt

Linking the List

struct Node *first_node, *second_node, *third_node, *current;

first_node = new_node(-100);

second_node = new_node(0);

first_node->next_in_line = second_node;

third_node = new_node(10);

second_node->next_in_line = third_node;

current = first_node;while(current != NULL) {

printf("%i\n", current->data);current = current->next_in_line;

Page 216: C  -  Programming  ppt

The heap and stack grow towards one another Potentially a large amount of heap storage is

available given the right operating system The routines malloc, calloc, realloc and free

manipulate heap storage Only realloc is really necessary Allocating dynamic arrays Allocating dynamic arrays of arrays Allocating dynamic structures

36853207 C Programming Ppt

Programming in C/C++ 2006 Lecture 1 - cs.vu.nlnsilvis/C++/2006/lecture1-2006-1up.pdf · Programming in C/C++ / Lecture 1 / 6-02-2006 5 C++ programming methodologies procedural programming

Linear Programming Model 2 MBA PPT

Ppt La10 Java Programming 02

Extreme Programming Ppt

C# Programming IV-7 - sheepsqueezers.comsheepsqueezers.com/media/presentations/dotNetLectureSeries_CSharp... · Programming I: Concepts of OOP Beginning C# Programming II: C# Programming

Windows programming ppt

Evolutionary Programming Ppt

C programming ppt slides, PDF on arrays to the basic data type (int, ... 7 to idNum[0], idNum[1], ... C programming ppt slides, PDF on arrays Author:

Ppt programming by alyssa marie paral

Introduction to Linear Programming MBA PPT

Advanced Programming - Chapter 6.ppt

Module 1-ppt System programming

Collaborative programming ppt

C programming language - modular programming

Unit-1 Programming Fundamentals PPT

Dynamic Programming Final Ppt

Programming Language (C) - Columbia Universitynaliniv/teaching/3101/intro.pdfProgramming Language (C) Nalini Vasudevan Columbia University Why C Programming? Why C Programming? •

C++ - Intermediate C++ Programming

C-Programming-Embedded c

Strategic Planning Programming 2011-10-14.Ppt

PPT on Linear Programming

9781133626381 PPT ch08.ppt - Philadelphia University 8 Array… · – Learn about multidimensional arrays C++ Programming: From Problem Analysis to Program Design, Sixth Edition

Programming in C & C++

Introduction to Programming C programming

programming elements-unit -1.ppt

SCSA1202 PROGRAMMING WITH C AND C++ UNIT1 BASICS OF C PROGRAMMING 9Hrs · 2020. 10. 3. · SCSA1202 PROGRAMMING WITH C AND C++ UNIT1 BASICS OF C PROGRAMMING 9Hrs Features of C - Structure

Ppt La10 Java Programming 05

Linear Programming ppt

Extreme & pair programming Slides ppt

Programming Language Final PPT

ENG1410 C Programming: Topic #2 “C Programming: Variables

Programming ppt files (final)

PPT Progress Report Programming

Linear Programming - Final Ppt

c language

Mar 17, 2019

440 likes | 655 Views

C Language. Brief history In 1972, Dennis Ritchie designed C and it was used on PDP-11 mini-computers In 1974, Unix was rewritten in C C++ and C Advantages and disadvantages. A short example. #include &lt;stdio.h&gt; main ( ) { printf (“Is anybody out there?<br>”);

Share Presentation

  • header file
  • int itemsread 0
  • define minimum wage 5

alder

Presentation Transcript

C Language • Brief history • In 1972, Dennis Ritchie designed C and it was used on PDP-11 mini-computers • In 1974, Unix was rewritten in C • C++ and C • Advantages and disadvantages

A short example • #include <stdio.h> • main ( ) • { • printf (“Is anybody out there?\n”); • printf (“Hello world!\n”); • }

/* Another example-read items, compute their average */ • #include <stdio.h> • main ( ) • { • int ItemsRead = 0; • double ThisItem, Sum = 0.0; • printf (“Enter as many items as you want\n”); • printf (“Terminate with non-double or EOF marker\n”); • while (scanf (“%lf”, &ThisItem ) ==1 ) • { • ItemsRead ++; • Sum += ThisItem; • } • printf( “The average of %d items was %f\n”, ItemsRead, Sum / ItemsRead ); • return 0; • }

Simple C • 1. Create a c program • Any line or screen editor will do. Vi editor is also a good choice. For simple ones, one can use cat > fileName as well. • 2. Compile the program • cc fileName.c will create a executable file called a.out regardless of the fileName.

Compile with a style • To create a complied file with the same name: • Use ccfileName.c –o fileName • Will create a file with the fileName instead of a.out

Compiling Problems • It is not as straightforward as the Code Warrior you did in C++ course. • However, you will get used to it once you do more. • Unix debugger dbx is available for debugging.

Memory leak in C • Memory leaks (in which malloc() memory is never released with corresponding free() calls) and buffer overruns (writing past memory that has been allocated for an array, for example) are some of the common problems and can be difficult to detect.

Example • #include <stdlib.h> • #include <stdio.h> • #include "memwatch.h" • int main(void) • { • char *ptr1; • char *ptr2; • ptr1 = malloc(512); • ptr2 = malloc(512); • ptr2 = ptr1; • free(ptr2); free(ptr1); • }

What is the problem with that program? • The code in Listing 1 allocates two 512-byte blocks of memory, and then the pointer to the first block is set to the second block. As a result, the address of the second block is lost, and there is a memory leak.

Debug Tools • There are various ways to track down user-space and kernel problems using debug tools on Linux. Build and debug your source code with these tools and techniques: • Memory tools: MEMWATCH and YAMD • strace • GNU debugger (gdb) • Magic key sequence

Compiling Process • 1. cc command translate the source file to an equivalent assembly program. • 2. Once an equivalent assembly language is generated, another program called assembler is called to convert the program into binary file or machine code file. • 3. Finally, linker is called to combine the binary file with the library to create a executable file.

cc versus gcc • gcc – the GNU C Compiler, it was written by Richard Stallman and it is now maintained by Cyguns solutions. gcc exists for practically all major operating systems and processor architectures and is widely used in embedded systems. • 1. It is the complier we are using in Linux. • 2. When you invoke cc, you are invoking gcc

gcc interpretation of filename Suffixes • .c --- C source code which must be pre- • processed before compilation. • .i --- C source code has been pre-processed. • .cc, .cxx, .cpp, .C --- C++ source file as in .c • .ii --- C++ source that has been pre-proce… • .h --- C header file • .s --- Assembly code • .S --- Assembly code which must be pre-processed

Compiling C++ Programs • To compile and link C++ programs, you should invoke the complier as g++ rather than gcc. This is especially important at link time because it force the linker to link in certain libraries required by C++ programs.

Basic Rules in C • The basic unit of a C program is a character. • A-Z, a-z, 0-9, white space: blanks, newlines, tabs, … and the following 29 characters: • ! # % ^ & * ( ) _ - + = [ ] { } | \ ; : “ ‘ < > • , . / ? ~ • White space is important for readability.

Comments in C • 1. C comments begins with a /* and end with */ and there should be no space between the asterisk and the slash. • 2. No nest in comment in C. • Common error: • /* 1 */ /* This comment ends early on the next line. • /* 2 */ * This is not in the comment ! • /* 3 */ * Nether is this;

Identifiers and Keywords in C • 1. A name may use A-Z, a-z, 0-9, _ • Begin with a digit is prohibited. • 2. The length cannot exceed 31 chars and in • some situations 6 is the limit. • 3. Similar to the UNIX, c is case sensitive. • 4. Avoid using the 32 keywords. • They are:

Keywords in C • auto, break, case, char, const, continue, • default, do, double, else, enum, extern • float, for, goto, if, int, long, register, return • short, signed, sizeof, static, struct, switch • typedef, union, unsigned, void, volatile, • while

Pre-Processor in C • #include <stdio.h> • #define Minimum Wage 5.75 • #---the first non-white-space character line begins with # will be treated as pre-processor • < ***> inside indicates the *** file doe not reside in the current directory, (it resides in the system directory) • .h --- h refer to the header file similar to C++

Pointers in C • Pointer is a variable to store an address of another object. • That object is accessed by dereferencing the • Pointer. • Pointer is one of the most important concept in C language

How to define a pointer? • int *p; • int x = 8; • int *p = &x; /* p points at x */ • ++*p will change x to 9 while • *P++ will make the pointer points to a different number in memory.

Pointer in C • You can give a pointer any name you like, such as: • int *p, int *ptr, int *Ptr, int *xPointer • However, we recommend use *xptr or xPtr to point x and *yPtr to point y. • * --- is called indirection operator or dereferencing operator.

Initializing Pointer • Pointer should be initialized either when they are declared or in an assignment statement. • int *xPtr, *yPtr, *zeroPtr; • int x = 8, y = 9, zero = 0; • xPtr = &x; • yPtr = & y; • zeroPtr = NULL or zeroPtr = 0; • NULL is a symbolic constant defined in the <stdio.h> header file (and in several other header files)

What we care is p points to the variable by store the address in it. The computer will reserve a address for p. However, we don’t care where it will store it. address p 8 p ++*p will make 8 becomes 9 and *p++ will make p points to another address

Program Example • #include <stdio.h> • Void • Swap (int * const X, int * const Y) • { • int Temp; • Temp = *X; • *X = *Y; • *Y = Temp; • } • main (void) • { • int A = 5, B = 7; • Swap (&A, &B); • printf (“%/d %/d\n” , A, B); /* Must pass the address */ • return 0; • }

Input from c Programs scanf • #include <stdio> • main (void) • { • int x; • double y; • printf (“Enter an integer and a real: “); • scanf ( “%d %lf” , &x , &y); • Print (“You entered %d and %f\n” , x, y); • }

Example • #include <stdio.h> • int main ( ) { printf(“\”So what? \“ said she.\n”); return 0; }

Input in c • #include <stdio.h> • int main( void ) • { • int intvar; • printf("The address of intvar is %p.\n", &intvar); printf("\nEnter an integer value: "); • scanf("%d", &intvar); printf("The value you entered was %d.\n", intvar); • return 0; • }

Notice the problem when you run the program • 1. When you input a legal integer. • 2. When you input a serious of characters. • 3. When you input a number that is too big to the computer.

  • More by User

C-language

If you want to learn C-language come to my blog spot it will help you./nhttp://bscitinfo.blogspot.com/

178 views • 8 slides

C Language

C Language. 219212 Programming Languages Ms. Raviporn Yongchaitrakul ID: 47541396. ABSTRACT. The C programming language was devised in the early 1970s as a system implementation language for the nascent Unix operating system . It is derived from language BCPL

499 views • 16 slides

C++ Language Presentation

C++ Language Presentation

C++ Language Presentation. By Pichai Sodsai 49541170 Software &amp; Knowledge Engineering. C++ Language Background. C++ was written by Bjarne Stroustrup at Bell Labs during 1983-1985. C++ is an extension of C.

264 views • 15 slides

The C Language

The C Language

int i;main (){for(; i [&quot;]&lt; i ;++ i ){-- i ;}&quot;];read('-'-'-', i +++&quot;hell o, world! &quot;,'/'/'/'));}read( j,i,p ){write(j/ p+p,i --- j,i / i );} -- Dishonorable mention, Obfuscated C Code Contest, 1984. (Author requested anonymity .). The C Language. Assembler Code. C/C++ Code.

556 views • 40 slides

C Programming language

C Programming language

C Programming language. &quot; ‘white book’ or ‘K&amp;R’ &quot;. C Language Programming History. 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.

288 views • 11 slides

C Language

C Language. Pointers. Overview of Pointers. A variable that contains the address of another variable Uses concept of indirection Use a complicated syntax, particularly pointers to functions and pointers to pointers Useful for: Complex data structures (linked lists, trees)

498 views • 20 slides

C Language: Functions

C Language: Functions

C Language: Functions. B. Ramamurthy Ch.4 in Kernighan and Ritchie C textbook. Topics. Purpose of functions Function design Function definition Function call. Functions. Functions are modular units that perform a specific operation

271 views • 9 slides

The C Language

The C Language. Topics to Cover…. ISR’s High Level Languages Compilers vs. Interpreters The C Language 1 st C Program C Style C Preprocessor printf Function eZ430X Header Files 2 nd C Program. Interrupt Service Routine. Interrupt Service Routines. Well-written ISRs:

447 views • 33 slides

C# Language Report

C# Language Report

C# Language Report. By Trevor Adams. Language History. Developed by Microsoft Principal Software Architect Anders Hejlsberg C# 1.0 – mid 2000 C# 2.0 – 2005 C# 3.0 – Currently Under Development. Implementation. Hybrid Implementation .Net Framework Preprocessor Unsafe Code.

360 views • 18 slides

C Language

C Language. Variables, Data Types and Arithmetic Expressions. Topics. identifiers data types constants, variables expressions, statements operators conversions printf( ) formats. C Identifiers. Programmer's name for some C element, such as a variable or function

668 views • 34 slides

The C Language

The C Language. B. Ramamurthy University at Buffalo [email protected]. Introduction. About C language: “.. features economy of expression..”; written for Unix Operating system (1978) The C Language since then has taken a life of it own and has become the foundation for many modern languages.

385 views • 32 slides

C Programming Language

C Programming Language

C Programming Language. Lecture 2 09.10.2008. Lecture 2: Outline. Variables, Data Types, and Arithmetic Expressions [K- ch.4] Working with Variables Understanding Data Types and Constants The Basic Integer Type int The Floating Number Type float The Extended Precision Type double

427 views • 34 slides

The C Language

The C Language. Prof. Stephen A. Edwards. The C Language. Currently, the most commonly-used language for embedded systems “High-level assembly” Very portable: compilers exist for virtually every processor Easy-to-understand compilation Produces efficient code Fairly concise. C History.

733 views • 65 slides

C# Language

C# Language

C# Language. MIS 324 Professor Sandvig. Overview. Why learn C#? C# Basics Variables Data types Operators Control Structures. Why Learn C#?. Modern language Microsoft introduced in 2000 More user-friendly than older languages Managed code Memory allocation Garbage collection

225 views • 21 slides

C  Language

C Language. Brief history In 1972, Dennis Ritchie designed C and it was used on PDP-11 mini-computers In 1974, Unix was rewritten in C C++ and C Advantages and disadvantages. A short example. #include &lt;stdio.h&gt; main ( ) { printf (“Is anybody out there? ”);

305 views • 30 slides

C Language

C Language. By Sra Sontisirikit 49541212. Background of C language. C is high level language create in 1972 By Brian W . C . Kernighan &amp; Dennis M . Ritchie Based on two languages : BCPL and B. Brian Kernighan. Dennis Ritchie. Goals and Purpose. Straightforward language

106 views • 9 slides

C# Language

C# Language. Panithan Chandrapatya 47541263. Agenda. C# History C# Goals C# Fixes C# Contribution C# Features C# Success C# Example. C# History. C# was submitted to European Computer Manufacturers Association (ECMA) standards group in mid-2000 by Microsoft Corporation.

99 views • 9 slides

C Language  Tutorial

C Language Tutorial

Here we offer online c tutorial for students who want to spend time learning a c programming language, while we all know if you're going to program world first you need to learn c language because c is the programming language used in all other programming languages if you would like to learn then visit here. For more details please click here

230 views • 3 slides

IMAGES

  1. PPT

    ppt presentation on c language

  2. PPT

    ppt presentation on c language

  3. C language ppt

    ppt presentation on c language

  4. PPT

    ppt presentation on c language

  5. PPT

    ppt presentation on c language

  6. PPT

    ppt presentation on c language

VIDEO

  1. Ppt tutorial #creative #presentation #tutorials

  2. How to make PPT using ChatGPT & Free AI Tools on mobile phone & PC Free AI PPT Maker Slidesgo |Hindi

  3. Part C Powerpoint Presentation

  4. Part C PowerPoint Presentation

  5. PART C POWERPOINT PRESENTATION STUDENT NUMBER 19984383 Copy1

COMMENTS

  1. C language ppt

    C language ppt. 1. Presented By : Gaurav Juneja. 2. Introduction C is a general purpose language which is very closely associated with UNIX for which it was developed in Bell Laboratories. Most of the programs of UNIX are written and run with the help of 'C'. Many of the important ideas of 'c' stem are from BCPL by Martin Richards. In 1972 ...

  2. Presentation on C programming language

    Mar 2, 2021 • 2 likes • 993 views Arunima Education Foundation Follow The presentation on C programming languages illustrates and explains the concept of Computer programming language. The base language used is C programming with its features, advantages, disadvantages and characteristics of a good program.

  3. C Slides

    Cp Sc 1110 - Programming in C 4th Edition Slides and Handouts: Chapter: Slides: Handouts: 01 Introduction to C: Slides: Handouts: 02 Your First Program

  4. Introduction To C Programming

    Home > PowerPoint Slides > Introduction To C Programming Published in: C, C++ 25,579 Views what is C? How it is useful and how to write a simple C program and the C mechanism. Devi / Chennai 6 years of teaching experience Qualification: B.Tech/B.E. ( Saveetha Engineering College, Chennai - 2017)

  5. Free PPT Slides for C, C++

    PowerPoint Presentation Slides Search our vast collection of PowerPoint presentations. PPTs for C, C++ by: Anshul Logical And Arithmetic Operator C, C++ (6 Slides) 11 Views by: Abhilash Operators And Its Types C, C++, Java Script, Python Programming (40 Slides) 469 Views by: Uma The C Programming Language (C Functions) C, C++ (10 Slides) 550 Views

  6. C Language Overview

    C Language Overview - PowerPoint Slides - LearnPick India C Language Overview Home > PowerPoint Slides > C Language Overview Published in: C, C++ 13,134 Views Advantages of C Writing First C Program C Tokens Ashish / Gwalior 17 years of teaching experience Qualification: M.Tech. (Software Systems)

  7. Introduction To C Language Using Powerpoint Presentation ...

    Introduction to C language powerpoint presentation ‎@Computing Coder 0:00 Intro0:13 what is a program0:21 what is algorithm0:27 what is flowchart0:41 what ...

  8. Basics of C programming

    C language ppt. C language ppt Ğäùråv Júñêj ... Presentation on C++ Programming Language satvirsandhu9 ...

  9. Basics of "C" Programming

    Special Symbols Operators Character & String. 3 1. Keywords Keywords are the reserved words whose meaning has already been explained to the C compiler. C has 32 keywords. These keywords combined with a formal syntax form a C programming language. Rules to be followed for all programs written in C: All keywords are lower-cased.

  10. Introduction To C Language Using Powerpoint Presentation ...

    Introduction to C language powerpoint presentation ‎@Computing Coder 0:00 Intro0:11 Data types in C0:55 Operators in C1:20 Hierarchy of Operators 1:28 Ass...

  11. GitHub

    Module 1 Introduction Introduction to components of a Computer System Introduction to Algorithm and Flowchart Fundamentals of C Programming Keywords, Identifiers, Constants and Variables Data types in C Operators in C Basic Input and Output Operations Expressions and Precedence of Operators In-built Functions Module 2 Control Structures

  12. Introduction to C Programming Language PPT and Google Slides

    Introduction To C Programming Language Presentation Slide C is a high-level programming language that was originally developed in the early 1970s for system programming and has since become widely used for a variety of applications.

  13. PDF C Programming ppt slides and PDF for Functions, Arrays and ...

    rules for C / C++ variable names are followed and must be unique. 2. Parameter list - Many functions use arguments, the value passed to the function when it is called. A function needs to know the data type of each argument. Argument type is provided in the function header by the parameter list. Parameter list acts as a placeholder. www.tenouk ...

  14. C

    Features of C. C can be thought of as a "high level assembler" Designed for maximum processor speed Safety a definite second! THE system programming language (Reasonably) portable Has a "write only" reputation

  15. INTRODUCTION TO C PROGRAMMING

    Jul 2, 2010 • 1,038 likes • 211,305 views Abhishek Dwivedi Follow This C tutorial covers every topic in C with the programming exercises. This is the most extensive tutorial on C you will get your hands on. I hope you will love the presentation. All the best. Happy learning. Feedbacks are most welcome. Send your feedbacks to [email protected].

  16. PPT

    C Features • Middle-level language • Can access bit level • Machine independent • Case sensitive • Type language (weak type) • Variable must be declared a type • Allow automatic type conversion • No boolean data type (0: false, non-zero: true) • No run-time error checking • Programmer's responsibility: array boundary

  17. PPT

    PPT - C Language PowerPoint Presentation, free download - ID:2185379 Presentation Download 1 / 16 Download Presentation >> C Language Jul 22, 2014 170 likes | 495 Views C Language. 219212 Programming Languages Ms. Raviporn Yongchaitrakul ID: 47541396. ABSTRACT.

  18. PPT

    PPT - C programming language PowerPoint Presentation, free download - ID:4189213 1 / 18 Download Presentation >> C programming language Sep 10, 2014 1.47k likes | 2.68k Views C programming language. Md. Hafizur Rahman, MSc in DUET. Introduction.

  19. Introduction to c programming language

    2. Intro C is the famous programming language designed to develop system application program. 3. Intro It is known as the starting of every programming language all the basics of a program language starts from C language. C is known as general purpose procedural programming language. 4.

  20. Structures In C

    The C programming language (While loop) C, C++. 86 Views. The C Programming Language - Chapter 4 (part 1) C, C++. 77 Views. Introduction To Programming Languages ... 16,992 Views. Upload PPTs . If you have your own PowerPoint Presentations which you think can benefit others, please upload on LearnPick. For each approved PPT you will get 50 ...

  21. PPT

    Simple C • 1. Create a c program • Any line or screen editor will do. Vi editor is also a good choice. For simple ones, one can use cat > fileName as well. • 2. Compile the program • cc fileName.c will create a executable file called a.out regardless of the fileName.

  22. Structure in C

    Structure initialization • Syntax: struct structure_name structure_variable= {value1, value2, … , valueN}; • There is a one-to-one correspondence between the members and their initializing values. • Note: C does not allow the initialization of individual structure members within the structure definition template. 8.

  23. POINTERS IN C

    POINTERS IN C Home > PowerPoint Slides > POINTERS IN C Published in: C, C++ 28,374 Views This PPT includes Introduction to pointers, Pointer using Arrays, Function Pointer, Pointers to Structures.. Praveen R / Chennai 5 years of teaching experience Qualification: MCA