PDF -The Basics of C Programming - University of Connecticut - C Programming
Wait Loading...


PDF :1 PDF :2 PDF :3 PDF :4 PDF :5 PDF :6 PDF :7 PDF :8 PDF :9 PDF :10


Like and share and download

C Programming

The Basics of C Programming - University of Connecticut

kciti edu wp content uploads 2017 07 cprogramming About The Tutorial C is a general purpose, procedural, imperative computer programming language developed in 1972 by Dennis M Ritchie at the Bell Telephone Laboratories to develop the UNIX operating system C is the most widely used computer language

Related PDF

About The Tutorial - kciti college

kciti edu wp content uploads 2017 07 cprogramming About The Tutorial C is a general purpose, procedural, imperative computer programming language developed in 1972 by Dennis M Ritchie at the Bell Telephone Laboratories to develop the UNIX operating system C is the most widely used computer language It keeps fluctuating at number
PDF

C Programming for Arduino - Lagout

doc lagout programmation C C Programming for C Programming for Arduino Learn how to program and use Arduino boards with a series of engaging examples, illustrating each core concept Julien Bayle
PDF

C Programming Tutorial - Mark Burgess

markburgess CTutorial C Tut 4 02 pdf you have come to C in the hope of finding a powerful language for writing everyday computer programs, then you will not be disappointed C is ideally suited to modern computers and modern programming This book is a tutorial Its aim is to teach C to a beginner, but with enough of the details so as not be outgrown as the years go by It presumes
PDF

An Introduction to the C Programming Language and Software Design

eng utah edu ~bigham ctext pdf The first is to introduce the C program ming language C is a practical and still current software tool; it remains one of the most popular programming languages in existence, particularly in areas such as embedded systems C facilitates writing code that is very efficient and powerful and, given the ubiquity of C compilers, can be easily
PDF

C Programs with Solutions - SKIET

skiet downloads cprogrammingquestion pdf book will be useful for students of BE, MCA, BCA, MSc, and BSc, which have C program ming language as a part of the course The first chapter deals with the fundamental concepts of C language The second chapter focuses on introduction C programming The third chapter provides with detailed program on next level to the basic C program
PDF

Essential C - Stanford University

cslibrary stanford edu 101 EssentialC pdf progammers have the time and skill to make it work in C In any case, C is a very popular and influential language This is mainly because of C's clean (if minimal) style, it's lack of annoying or regrettable constructs, and the relative ease of writing a C compiler Other Resources • The C Programming Language , 2nd ed , by Kernighan and
PDF

C programming I - University of Wisconsin–Madison

biostat wisc edu ~kbroman teaching statprog Suggested books • Kernighan, Ritchie (1988) The C Programming Language, 2nd edition Prentice Hall • Plauger (1992) The Standard C Library Prentice Hall
PDF

C Programming: Absolute Beginner's Guide

ptgmedia pearsoncmg images 9780789751980 samplepages C Programming Greg Perry and Dean Miller 800 East 96th Street Indianapolis, Indiana 46240 Third Edition 00 9780789751980 fm indd i 7 17 13 12 29 PM
PDF

C Programming Tutorial - unfedu

unf edu ~wkloster 2220 ppts cprogramming This chapter describes the basic details about C programming language, how it emerged, what are strengths of C and why we should use C T he C programming language is a general purpose, high level language that was originally developed by Dennis M Ritchie to develop the UNIX operating system at Bell Labs
PDF

The Basics of C Programming - University of Connecticut


PDF

C Programming

Introduction to C Programming

PDF C Programming Tutorial unf edu ~wkloster 2220 cprogramming tutorial pdf PDF C Programming Tutorial phy ntnu edu tw ~cchen pdf ctutor pdf PDF C Programming Tutorial Mark Burgessmarkburgess CTutorial C

  1. c programming examples pdf
  2. easy way to learn c programming language pdf
  3. practical c programming pdf
  4. c programming exercises pdf
  5. learn c programming step by step pdf
  6. c programming tutorial
  7. c programming language pdf for beginners
  8. c programming book pdf free download

c++ programs class 11

Chapter 11 structs (C++ records)

application such as a C++ program that uses the String class is a client 11 Give an example of how the keyword inline is used to declare as inline a method Chapter 11, Bit Operations, discusses the logical C++ operators that work on

  1. Applications Programming in C++
  2. Practical C++ Programming
  3. simplifying the analysis of c++ programs
  4. Class
  5. Practical C++ Programming Teacher's Guide
  6. The C++ Language Tutorial
  7. Learn C++ Programming Language
  8. A Complete Guide to Programming in C++
  9. Chapter 11 structs
  10. C++ records

C++ Programs Collection

Chapter 11 structs (C++ records)

, the Wikibooks Java Programming and C Programming, C++ Exercises for collection, while C++ relies mainly on the RAII (Resource Acquisition Is  It is one of the simplest programs that can be written in C++, but it already contains the fundamental components that every C++

  1. C++ Programming
  2. collection of open
  3. The C++ Language Tutorial
  4. Guidelines for C++ Program Style
  5. C++ Programming HOW-TO
  6. Introduction to C++
  7. Programming
  8. oriented class library for C++ programs
  9. Quantifying Behavioral Differences Between C and C++ Programs
  10. Accelerated C++ Practical Programming by Example

C Programs

Model Checking C Programs with MSVL

PDF C Programs with Solutions skiet downloads cprogrammingquestion pdf PDF C Programming kciti kciti edu wp content uploads cprogramming tutorial pdf PDF Dr Estell's C Programs and Examples Last modifiedweb ipac caltech edu staff fmasci

  1. basic c programs for beginners pdf
  2. learn c programming step by step pdf
  3. c programs pdf
  4. c programming lecture notes
  5. c programming language pdf for beginners
  6. c programming book pdf free download
  7. practical c programming pdf
  8. easy way to learn c programming language pdf

C++ Project Class 12

Mini Project Report - Northwestern University

centercomp biology projects for class 12 pdf Biology Projects for Class 12 CBSE High School Students The Biology Project, an interactive online resource for learning biology developed at The University of Arizona The Biology Project is fun, richly illustrated, and tested on 1000s of students It

c++ project on library management by kc

1 periodic table in c++ 2 class result analysis 3 library

Library management system is a project which aims in developing a computerized system to maintain all the daily work of library This project has many features Nov 15, 2011 You can build library management system on your own Do not submit project with

  1. Library Management System
  2. The Library Management System
  3. KEY ACADMIC PROJECTS Library Management
  4. C++ Project
  5. library management system by adebesin tobi tosin
  6. Open source library management system
  7. Online Library Management System
  8. Chapter 3 Survey of open source library management systems
  9. Improving Design of Library Management System using Design
  10. periodic table in c++ 2

c question and answerr

C Interview Question Answer

PDF C Language Questions and Answers Techtud techtud C 20Language 20100 20Questions 20Answers pdf PDF C Programs with Solutions skiet downloads cprogrammingquestion pdf PDF C Programming Question And Answer The Right

  1. c interview question with answer pdf
  2. tough c interview questions
  3. c pointers interview questions and answers pdf
  4. c++ question and answer pdf
  5. function in c programming questions and answers
  6. c programming basic questions pdf
  7. c programming final exam questions and answers
  8. c interview questions tutorialspoint

C.S. Lewis - Crestinism Pur Si Simplu

Mai presus de simplul creştinism - islam chat

C. S. Lewis - Manuel Lasanta

CS Lewis The Great Divorce - Download Book frees for kindle to

PDF Till We Have Faces Cs Lewisapi wl2 stage ovdal dk till we have faces cs lewis pdf PDF C S Lewis At The Bbc Messages Of Hope In The Darkness Of Warcluster rifiniti c s lewis at the bbc messages of hope in the darkness

Home back Next

Description

C Programming An Introduction About C As a programming language,

C is rather like Pascal or Fortran

Values are stored in variables

Programs are structured by defining and calling functions

Program flow is controlled using loops,

if statements and function calls

Input and output can be directed to the terminal or to files

Related data can be stored together in arrays or structures

Of the three languages,

C allows the most precise control of input and output

C is also rather more terse than Fortran or Pascal

This can result in short efficient programs,

where the programmer has made wise use of C's range of powerful operators

It also allows the programmer to produce programs which are impossible to understand

Programmers who are familiar with the use of pointers (or indirect addressing,

to use the correct term) will welcome the ease of use compared with some other languages

Undisciplined use of pointers can lead to errors which are very hard to trace

This course only deals with the simplest applications of pointers

It is hoped that newcomers will find C a useful and friendly language

Care must be taken in using C

Many of the extra facilities which it offers can lead to extra types of programming error

You will have to learn to deal with these to successfully make the transition to being a C programmer

Common C Until recently there was one dominant form of the C language

This was the native UNIX form,

which for historical reasons is known as either Bell Labs C,

after the most popular compiler,

after the authors of the most popular textbook on the language

It is now often called "Classic C"

ANSI C The American National Standards Institute defined a standard for C,

eliminating much uncertainty about the exact syntax of the language

This newcomer,

proclaims itself the standard version of the language

As such it will inevitably overtake,

and eventually replace common C

ANSI C does incorporate a few improvements over the old common C

The main difference is in the grammar of the language

The form of function declarations has been changed making them rather more like Pascal procedures

This course introduces ANSI C since it is supported by the SUN workstation compilers

Most C programming texts are now available in ANSI editions

A Simple Program The following program is written in the C programming language

printf("Programming in C is easy

A NOTE ABOUT C PROGRAMS In C,

lowercase and uppercase characters are very important

! All commands in C must be lowercase

The C programs starting point is identified by the word main()

This informs the computer as to where the program actually starts

The brackets that follow the keyword main indicate that there are no arguments supplied to this program (this will be examined later on)

The two braces,

signify the begin and end segments of the program

The purpose of the statment include

is to allow the use of the printf statement to provide program output

Text to be displayed by printf() must be enclosed in double quotes

The program has only one statement printf("Programming in C is easy

printf() is actually a function (procedure) in C that is used for printing variables and text

Where text appears in double quotes "",

it is printed without modification

There are some exceptions however

This has to do with the \ and % characters

These characters are modifier's,

and for the present the \ followed by the n character represents a newline character

Thus the program prints Programming in C is easy

and the cursor is set to the beginning of the next line

As we shall see later on,

what follows the \ character will determine what is printed,

Another important thing to remember is that all C statements are terminated by a semi-colon

Summary of major points: •

program execution begins at main()

keywords are written in lower-case statements are terminated with a semi-colon text strings are enclosed in double quotes C is case sensitive,

use lower-case and try not to capitalise variable names \n means position the cursor on the beginning of the next line printf() can be used to display text to the screen The curly braces {} define the beginning and end of a program block

# EXERCISE C1: What will the following program output

? #include main() { printf("Programming in C is easy

And so is Pascal

And this program

? #include main() { printf("The black dog was big

printf("The cow jumped over the moon

The cow jumped over the moon

Another thing about programming in C is that it is not necessary to repeatedly call the printf routine,

so try and work out what the following program displays,

VARIABLES C provides the programmer with FOUR basic data types

User defined variables must be declared before they can be used in a program

Get into the habit of declaring variables using lowercase characters

Remember that C is case sensitive,

so even though the two variables listed below have the same name,

they are considered different variables in C

The declaration of variables is done after the opening brace of main(),

printf("The sum of 500 and 15 is %d\n",

It is possible to declare variables elsewhere in a program,

but lets start simply and then get into variations later on

The basic format for declaring variables is data_type

where data_type is one of the four basic types,

The program declares the variable sum to be of type INTEGER (int)

The variable sum is then assigned the value of 500 + 15 by using the assignment operator,

Now lets look more closely at the printf() statement

It has two arguments,

Lets look at the first argument,

"The sum of 500 and 15 is %d\n"

The % sign is a special character in C

It is used to display the value of variables

When the program is executed,

C starts printing the text until it finds a % character

If it finds one,

it looks up for the next argument (in this case sum),

The d'character that follows the % indicates that a decimal integer is expected

the next argument to the printf() routine is looked up (in this case the variable sum,

The \n is then executed which prints the newline character

The output of the program is thus,

The sum of 500 and 15 is 515 _

Some of the formatters for printf are,

Cursor \n \t \r \f \v

Control Formatters newline tab carriage return form feed vertical tab

Variable Formatters %d decimal integer %c character %s string or character array %f float %e double

The following program prints out two integer values separated by a TAB It does this by using the \t cursor control formatter #include main() {

} Program output looks like 10 15 _

# EXERCISE C2: What is the output of the following program

printf("The sum of %d and %d is %d\n",

@ The sum of 35 and 18 is 53 _

Note that the program declares three variables,

This could've been done by three separate declarations,

COMMENTS The addition of comments inside programs is desirable

These may be added to C programs by enclosing them as follows,

Note that the /* opens the comment field and */ closes the comment field

Comments may span multiple lines

Comments may not be nested one inside another

/* this comment is inside */ wrong */

In the above example,

the first occurrence of */ closes the comment statement for the entire line,

meaning that the text wrong is interpreted as a C statement or variable,

What Comments Are Used For • • • •

documentation of variables and their usage explaining difficult sections of code describes the program,

Basic Structure of C Programs C programs are essentially constructed in the following manner,

as a number of well defined sections

/* HEADER SECTION */ /* Contains name,

revision number*/ /* INCLUDE SECTION /* contains #include statements

Adhering to a well defined structured layout will make your programs • • • •

easy to read easy to modify consistent in format self documenting

MORE ABOUT VARIABLES Variables must begin with a character or underscore,

and may be followed by any combination of characters,

The following is a list of valid variable names,

summary exit_flag i Jerry7 Number_of_moves _valid_flag

You should ensure that you use meaningful names for your variables

The reasons for this are,

meaningful names for variables are self documenting (see what they do at a glance) they are easier to understand there is no correlation with the amount of space used in the

EXE file makes programs easier to read

# EXERCISE C3: Why are the variables in the following list invalid,

value$sum exit flag 3lotsofmoney char @ value$sum contains a $ exit flag contains a space 3lotsofmoney begins with a digit char is a reserved keyword

VARIABLE NAMES AND PREFIXES WHEN WRITING WINDOWS OR OS/2 PROGRAMS During the development of OS/2,

it became common to add prefix letters to variable names to indicate the data type of variables

This enabled programmers to identify the data type of the variable without looking at its declaration,

thus they could easily check to see if they were performing the correct operations on the data type and hopefully,

Prefix b c'clr f h hwnd id l'msg P rc s'ul us sz psz

Purpose or Type a byte value count or size a variable that holds a color bitfields or flags a handle a window handle an identity a long integer a message a Pointer return value short integer unsigned long integer unsigned short integer a null terminated string variable a pointer to a null terminated string variable

DATA TYPES AND CONSTANTS The four basic data types are •

INTEGER These are whole numbers,

Unsigned integers (positive values only) are supported

In addition,

there are short and long integers

The keyword used to define integers is,

An example of an integer value is 32

An example of declaring an integer variable called sum is,

FLOATING POINT These are numbers which contain fractional parts,

The keyword used to define float variables is,

An example of a float value is 34

An example of declaring a float variable called money is,

DOUBLE These are exponetional numbers,

The keyword used to define double variables is,

An example of a double value is 3

An example of declaring a double variable called big is,

CHARACTER These are single characters

The keyword used to define character variables is,

An example of a character value is the letter A

An example of declaring a character variable called letter is,

Note the assignment of the character A to the variable letter is done by enclosing the value in single quotes

Remember the golden rule: Single character

Sample program illustrating each data type #include < stdio

printf("value printf("value printf("value printf("value

integer value */ float value */ character value */ a double value */

Sample program output value of sum = 10 value of money = 2

010000e+06

INITIALISING DATA VARIABLES AT DECLARATION TIME Unlike PASCAL,

in C variables may be initialised with a value when they are declared

Consider the following declaration,

which declares an integer variable count which is initialised to 10

SIMPLE ASSIGNMENT OF VALUES TO VARIABLES The = operator is used to assign values to data variables

Consider the following statement,

which assigns the value 32 an integer variable count,

and the letter A to the character variable letter count = 32

THE VALUE OF VARIABLES AT DECLARATION TIME Lets examine what the default value a variable is assigned when its declared

To do this,

lets consider the following program,

and letter which is a character

Neither variable is pre-initialised

The value of each variable is printed out using a printf() statement

Sample program output Count = 26494 Letter = f

It can be seen from the sample output that the values which each of the variables take on at declaration time are no-zero

and programmers must ensure that variables are assigned values before using them

If the program was run again,

the output could well have different values for each of the variables

We can never assume that variables declare in the manner above will take on a specific value

Some compilers may issue warnings related to the use of variables,

and Turbo C from Borland issues the following warning,

possible use of 'count' before definition in function main

RADIX CHANGING Data numbers may be expressed in any base by simply altering the modifier,

This is achieved by the letter which follows the % sign related to the printf argument

#include main() /* Prints the same value in Decimal,

Hex and Octal */ { int number = 100

printf("In decimal the number is %d\n",

printf("In hex the number is %x\n",

printf("In octal the number is %o\n",

/* what about %X\n as an argument

Sample program output In decimal the number is 100 In hex the number is 64 In octal the number is 144

Note how the variable number is initialised to zero at the time of its declaration

DEFINING VARIABLES IN OCTAL AND HEXADECIMAL Often,

when writing systems programs,

the programmer needs to use a different number base rather than the default decimal

Integer constants can be defined in octal or hex by using the associated prefix,

to define an integer as an octal constant use %o int

To define an integer as a hex constant use %0x

MORE ABOUT FLOAT AND DOUBLE VARIABLES C displays both float and double variables to six decimal places

This does NOT refer to the precision (accuracy) of which the number is actually stored,

only how many decimal places printf() uses to display these variable types

The following program illustrates how the different data types are declared and displayed,

printf("Integer variable is %d\n",

printf("Float variable is %f\n",

printf("Double variable is %e\n",

} Sample program output Integer variable is 100 Character variable is Z Float variable is 23

000000e23

To change the number of decimal places printed out for float or double variables,

modify the %f or %e to include a precision value,

In this case,

and the output now looks like Sample program output Integer variable is 100 Character variable is Z Float variable is 23

000000e23

SPECIAL NOTE ABOUT DATA TYPE CONVERSION Consider the following program,

printf("The value of %d divided by %d is %f\n",value1,value2,answer )

} Sample program output The value of 12 divided by 5 is 2

Even though the above declaration seems to work,

it is not always 100% reliable

Note how answer does not contain a proper fractional part (ie,

To ensure that the correct result always occurs,

the data type of value1 and value2 should be converted to a float type before assigning to the float variable answer

The following change illustrates how this can be done,

answer = (float)value1 / (float)value2

DIFFERENT TYPES OF INTEGERS A normal integer is limited in range to +-32767

This value differs from computer to computer

It is possible in C to specify that an integer be stored in four memory locations instead of the normal two

This increases the effective range and allows very large integers to be stored

The way in which this is done is as follows,

To display a long integer,

printf("A larger number is %l\n",

Short integers are also available,

Unsigned integers (positive values only) can also be defined

The size occupied by integers varies upon the machine hardware

ANSI C (American National Standards Institute) has tried to standardise upon the size of data types,

and hence the number range of each type

The following information is from the on-line help of the Turbo C compiler,

Type: int Integer data type Variables of type int are one word in length

They can be signed (default) or unsigned,

which means they have a range of

Type modifiers: signed,

long A type modifier alters the meaning of the base type to yield a new type

Each of the above

can be applied to the base type int

The modifiers signed and unsigned can be applied to the base type char

In addition,

When the base type is ommitted from a declaration,

Examples: long unsigned char signed int unsigned long int

PREPROCESSOR STATEMENTS The define statement is used to make programs more readable

Consider the following examples,

#define on line */ #define #define #define #define #define

FALSE NULL AND OR EQUALS

0 0 & | ==

Note that preprocessor statements begin with a # symbol,

and are NOT terminated by a semi-colon

Traditionally,

preprocessor statements are listed at the beginning of the source file

Preprocessor statements are handled by the compiler (or preprocessor) before the program is actually compiled

All # statements are processed first,

and the symbols (like TRUE) which occur in the C program are replaced by their value (like 1)

Once this substitution has taken place by the preprocessor,

In general,

preprocessor constants are written in UPPERCASE

Click here for more information of preprocessor statements,

# Exercise C4: Use pre-processor statements to replace the following constants 0

312 W 37

@ Use pre-processor statements to replace the following constants 0

W 37 #define smallvalue #define letter #define smallint

312 'W' 37

LITERAL SUBSTITUTION OF SYMBOLIC CONSTANTS USING #define Lets now examine a few examples of using these symbolic constants in our programs

Consider the following program which defines a constant called TAX_RATE

2f is %

The pre-processor first replaces all symbolic constants before the program is compiled,

so after preprocessing the file (and before its compiled),

#include #define TAX_RATE main() {

2f is %

YOU CANNOT ASSIGN VALUES TO THE SYMBOLIC CONSTANTS Considering the above program as an example,

look at the changes we have made below

We have added a statement which tries to change the TAX_RATE to a new value

TAX_RATE = 0

2f is %

This is illegal

You cannot re-assign a new value to a symbolic constant

ITS LITERAL SUBSTITUTION,

SO BEWARE OF ERRORS As shown above,

the preprocessor performs literal substitution of symbolic constants

Lets modify the previous program slightly,

and introduce an error to highlight a problem

#include #define TAX_RATE main() {

tax = (balance * TAX_RATE )+ 10

2f is %

In this case,

the error that has been introduced is that the #define is terminated with a semi-colon

The preprocessor performs the substitution and the offending line (which is flagged as an error by the compiler) looks like tax = (balance * 0

However,

you do not see the output of the preprocessor

If you are using TURBO C,

you will only see tax = (balance * TAX_RATE )+ 10

and this actually looks okay (but its not

! after substitution takes place)

MAKING PROGRAMS EASY TO MAINTAIN BY USING #define The whole point of using #define in your programs is to make them easier to read and modify

Considering the above programs as examples,

what changes would you need to make if the TAX_RATE was changed to 20%

Obviously,

where the #define statement which declares the symbolic constant and its value occurs

You would change it to read #define TAX_RATE = 0

Without the use of symbolic constants,

you would hard code the value 0

and this might occur several times (or tens of times)

This would make changes difficult,

because you would need to search and replace every occurrence in the program

However,

what would happen if you actually used the value 0

allow the use of symbolic constants in programs in general,

symbols are written in uppercase are not terminated with a semi-colon generally occur at the beginning of the file each occurrence of the symbol is replaced by its value makes programs readable and easy to maintain

HEADER FILES Header files contain definitions of functions and variables which can be incorporated into any C program by using the pre-processor #include statement

Standard header files are provided with each compiler,

printing and reading of variables

To use any of the standard functions,

the appropriate header file should be included

This is done at the beginning of the C source file

For example,

to use the function printf() in a program,

should be at the beginning of the source file,

because the definition for printf() is found in the file stdio

h All header files have the extension

h and generally reside in the /include subdirectory

h" The use of angle brackets informs the compiler to search the compilers include directory for the specified file

The use of the double quotes "" around the filename inform the compiler to search in the current directory for the specified file

Practise Exercise 1: Defining Variables 1

Declare an integer called sum 2

Declare a character called letter 3

Define a constant called TRUE which has a value of 1 4

Declare a variable called money which can be used to hold currency 5

Declare a variable called arctan which will hold scientific notation values (+e) 6

Declare an integer variable called total and initialise it to zero

Declare a variable called loop,

which can hold an integer value

Define a constant called GST with a value of

Answers to Practise Exercise 1: Defining Variables 1

Declare an integer called sum int sum

Declare a character called letter char letter

Define a constant called TRUE which has a value of 1 #define TRUE 1

Declare a variable called money which can be used to hold currency float money

Declare a variable called arctan which will hold scientific notation values (+e) double arctan

Declare an integer variable called total and initialise it to zero

Declare a variable called loop,

which can hold an integer value

Define a constant called GST with a value of

ARITHMETIC OPERATORS The symbols of the arithmetic operators are:Operation Operator Comment Value of Sum before Value of sum after Multiply * sum = sum * 2

leaving the result in the variable sum sum = loop + count

Note: If the modulus % sign is needed to be displayed as part of a text string,

ie %% #include main() { int sum = 50

printf("The %% of %d by 10 is %f\n",

# EXERCISE C5: What does the following change do to the printed output of the previous program

? printf("The %% of %d by 10 is %

#include main() { int sum = 50

printf("The %% of %d by 10 is %

The % of 50 by 10 is 0

Practise Exercise 2: Assignments 1

Assign the value of the variable number1 to the variable total 2

Assign the sum of the two variables loop_count and petrol_cost to the variable sum 3

Divide the variable total by the value 10 and leave the result in the variable discount 4

Assign the character W to the char variable letter 5

Assign the decimal result of dividing the integer variable sum by 3 into the float variable costing

Use type casting to ensure that the remainder is also held by the float variable

Answers: Practise Exercise 2: Assignments 1

Assign the value of the variable number1 to the variable total total = number1

Assign the sum of the two variables loop_count and petrol_cost to the variable sum sum = loop_count + petrol_cost

Divide the variable total by the value 10 and leave the result in the variable discount discount = total / 10

Assign the character W to the char variable letter letter = 'W'

Assign the decimal result of dividing the integer variable sum by 3 into the float variable costing

Use type casting to ensure that the remainder is also held by the float variable

PRE/POST INCREMENT/DECREMENT OPERATORS PRE means do the operation first followed by any assignment operation

POST means do the operation after any assignment operation

Consider the following statements ++count

means add one to count */ /* POST Increment,

In the above example,

because the value of count is not assigned to any variable,

the effects of the PRE/POST operation are not clearly visible

Lets examine what happens when we use the operator along with an assignment operation

Consider the following program,

If the operator precedes (is on the left hand side) of the variable,

the operation is performed first,

so the statement loop = ++count

really means increment count first,

then assign the new value of count to loop

Which way do you write it

? Where the increment/decrement operation is used to adjust the value of a variable,

and is not involved in an assignment operation,

The answer is,

It does seem that there is a preference amongst C programmers to use the post form

Something to watch out for Whilst we are on the subject,

do not get into the habit of using a space(s) between the variable name and the pre/post operator

Try to be explicit in binding the operator tightly by leaving no gap

GOOD FORM Perhaps we should say programming style or readability

The most common complaints we would have about beginning C programmers can be summarised as,

they have poor layout their programs are hard to read

Your programs will be quicker to write and easier to debug if you get into the habit of actually formatting the layout correctly as you write it

For instance,

look at the program below #include main() { int sum,loop,kettle,job

printf("Whoknows=%c,Kettle=%d\n",whoknows,kettle)

It is our contention that the program is hard to read,

will be difficult to debug for errors by an inexperienced programmer

It also contains a few deliberate mistakes

lets rewrite the program using good form

Kettle = %d\n",

We have also corrected the mistakes

The major differences are •

the { and } braces directly line up underneath each other This allows us to check ident levels and ensure that statements belong to the correct block of code

This becomes vital as programs become more complex 23

spaces are inserted for readability We as humans write sentences using spaces between words

This helps our comprehension of what we read (if you dont believe me,

try reading the following sentence

wishihadadollarforeverytimeimadeamistake

The insertion of spaces will also help us identify mistakes quicker

good indentation Indent levels (tab stops) are clearly used to block statements,

here we clearly see and identify functions,

and the statements which belong to each { } program body

Programs to help you There are a number of shareware programs available in the public domain which will assist you in the areas of available to [registered users only] • • • • • •

checking for code correctness converting between tabs and spaces formatting the layout with indentation etc building a tree representation of program flow generating cross references checking syntax

Please note that the above are all MSDOS based programs

Perhaps the most famous of all C program utilities is lint

KEYBOARD INPUT There is a function in C which allows the programmer to accept input from a keyboard

The following program illustrates the use of this function,

printf("The number you typed was %d\n",

An integer called number is defined

A prompt to enter in a number is then printed using the statement printf("Type in a number \n:")

The scanf routine,

The first ("%d") specifies what type of data type is expected (ie char,

The second argument (&number) specifies the variable into which the typed response will be placed

In this case the response will be placed into the memory location associated with the variable number

This explains the special significance of the & character (which means the address of)

Sample program illustrating use of scanf() to read integers,

characters and floats #include < stdio

printf("Please enter an integer value ")

printf("Please enter a character ")

/* the leading space before the %c ignores space characters in the scanf("

printf("Please enter a float variable ")

printf("\nThe printf("value printf("value printf("value

variables you entered were\n")

This program illustrates several important points

the c'language provides no error checking for user input

The user is expected to enter the correct data type

For instance,

if a user entered a character when an integer value was expected,

the program may enter an infinite loop or abort abnormally

its up to the programmer to validate data for correct type and range of values

Practise Exercise 3: printf() and scanf() 1

Use a printf statement to print out the value of the integer variable sum 2

Use a printf statement to print out the text string "Welcome",

Use a printf statement to print out the character variable letter 4

Use a printf statement to print out the float variable discount 5

Use a printf statement to print out the float variable dump using two decimal places

Use a scanf statement to read a decimal value from the keyboard,

into the integer variable sum 7

Use a scanf statement to read a float variable into the variable discount_rate 8

Use a scanf statement to read a single character from the keyboard into the variable operator

Skip leading blanks,

Answers: Practise Exercise 3: printf() and scanf() 1

Use a printf statement to print out the value of the integer variable sum printf("%d",

Use a printf statement to print out the text string "Welcome",

Use a printf statement to print out the character variable letter printf("%c",

Use a printf statement to print out the float variable discount printf("%f",

Use a printf statement to print out the float variable dump using two decimal places printf("%

Use a scanf statement to read a decimal value from the keyboard,

into the integer variable sum scanf("%d",

Use a scanf statement to read a float variable into the variable discount_rate scanf("%f",

Use a scanf statement to read a single character from the keyboard into the variable operator

Skip leading blanks,

THE RELATIONAL OPERATORS These allow the comparision of two or more variables

equal to not equal less than less than or equal to greater than greater than or equal to

In the next few screens,

these will be used in for loops and if statements

The operator

ITERATION,

FOR LOOPS The basic format of the for statement is,

re-evaulation ) program statement

printf("day:month:year = %d:%d:%d\n",

printf("day:month:year = %d:%d:%d\n",

Practise Exercise 11a: Pointers & Structures Determine the output of the following program

void editrecord( struct record * )

void editrecord( struct record *goods ) { strcpy( goods->name,

"Baked Beans" )

"Red Plum Jam")

Before call to editrecord() @

After return from editrecord() @

The final values of values,

C25: Examples on Pointer Usage Determine the output of the following program

static char product[]="Red Plum Jam"

Name = Baked Beans ID = 312 Price = 2

C26: Examples on Pointer Usage Determine the output of the following program

static char product[] = "Greggs Coffee"

void printrecord( struct sample * )

void printrecord( struct sample *goods ) { printf("Name = %s\n",

What are we trying to print out

What does it evaluate to

%d is an integer we want the value to be a variable integer type goods->id,

therefor we use *goods->id which evaluates to an integer type Name = Apple Pie ID = 123 Price = 1

Name = Greggs Coffee ID = 773 Price = 3

File Handling Example /* File handling example for PR101 */ /* processing an ASCII file of records */ /* Written by B

April 1994 */ /* /* /* /*

and print out all goods where the quantity on hand is less than or equal to the re-order level

#include #include #include #include

/* name of product float price

/* price of product int quantity

/* quantity on hand int reorder

void printrecord( struct goods )

int getrecord( struct goods * )

/* global data variables */ FILE *fopen(),

!= NULL ) fclose( input_file )

} /* prints a record */ void printrecord( struct goods record ) { printf("\nProduct name\t%s\n",

printf("Product quantity\t%d\n",

printf("Product reorder level\t%d\n",

returns 1 for success */ int getrecord( struct goods *record ) { int loop = 0,

/* skip to start of record */ while( (ch == '\n') || (ch == ' ') && (ch

!= EOF) ) ch = fgetc( input_file )

/* read product name */ while( (ch

!= EOF)) { buffer[loop++] = ch

/* skip to start of next field */ while( (ch == '\n') || (ch == ' ') && (ch

!= EOF) ) ch = fgetc( input_file )

/* read product price */ loop = 0

!= EOF)) { buffer[loop++] = ch

record->price = atof( buffer )

/* skip to start of next field */ while( (ch == '\n') || (ch == ' ') && (ch

!= EOF) ) ch = fgetc( input_file )

/* read product quantity */ loop = 0

!= EOF)) { buffer[loop++] = ch

record->quantity = atoi( buffer )

/* skip to start of next field */ while( (ch == '\n') || (ch == ' ') && (ch

!= EOF) ) ch = fgetc( input_file )

/* read product reorder level */

!= EOF)) { buffer[loop++] = ch

record->reorder = atoi( buffer )

} /* processes file for records */ void processfile( void ) { struct goods record

/* holds a record read from inputfile */ while(

! feof( input_file )) { if( getrecord( &record ) == 1 ) { if( record

quantity | data | |--------| | |--------| | pointer|---| pointer|

---> NULL

A structure which contains a data element and a pointer to the next node is created by,

This defines a new data structure called list (actually the definition of a node),

The first is an integer called value

The second is called next,

which is a pointer to another list structure (or node)

Suppose that we declare two structures to be of the same type as list,

The next pointer of structure n1 may be set to point to the n2 structure by /* assign address of first element in n2 to the pointer next of the n1 structure */ n1

which creates a link between the two structures

C Program to illustrate linked lists */ #include struct list {

Not only this,

In using linked list structures,

it is common to assign the value of 0 to the last pointer in the list,

to indicate that there are no more nodes in the list,

Traversing a linked list /* Program to illustrate traversing a list */ #include struct list { int value

struct list *list_pointer = &n1

list_pointer = list_pointer->next

This program uses a pointer called list_pointer to cycle through the linked list

Practise Exercise 12: Lists

Define a structure called node,

which contains an integer element called data,

and a pointer to a structure of type node called next_node

Declare three structures called node1,

Write C statements which will link the three nodes together,

with node1 at the head of the list,

and node3 at the tail of the list

Assign the value NULL to node3

next to signify the end of the list

Using a pointer list,

which has been initialised to the address of node1,

write C statements which will cycle through the list and print out the value of each nodes data field

Assuming that pointer list points to node2,

what does the following statement do

? list->next_node = (struct node *) NULL

Assuming the state of the list is that as in 3

write C statements which will insert a new node node1a between node1 and node2,

using the pointer list (which is currently pointing to node1)

Assume that a pointer new_node points to node node1a

Write a function called delete_node,

which accepts a pointer to a list,

and a pointer to the node to be deleted from the list,

*delnode )

Write a function called insert_node,

which accepts a pointer to a list,

a pointer to a new node to be inserted,

and a pointer to the node after which the insertion takes place,

eg void insert_node( struct node *head,

Answers

Practise Exercise 12: Lists 1

Define a structure called node,

which contains an integer element called data,

and a pointer to a structure of type node called next_node

Declare three structures called node1,

Write C statements which will link the three nodes together,

with node1 at the head of the list,

and node3 at the tail of the list

Assign the value NULL to node3

next to signify the end of the list

next_node = (struct node *) NULL

Using a pointer list,

which has been initialised to the address of node1,

write C statements which will cycle through the list and print out the value of each nodes data field

Assuming that pointer list points to node2,

what does the following statement do

? list->next_node = (struct node *) NULL

The statement writes a NULL into the next_node pointer,

thereby erasing node3 from the list

Assuming the state of the list is that as in 3

write C statements which will insert a new node node1a between node1 and node2,

using the pointer list (which is currently pointing to node1)

Assume that a pointer new_node points to node node1a

Write a function called delete_node,

which accepts a pointer to a list,

and a pointer to the node to be deleted from the list,

*delnode )

delete_node( struct node *head,

struct node *delnode ) struct node *list

!= delnode ) { list = list->node

Write a function called insert_node,

which accepts a pointer to a list,

a pointer to a new node to be inserted,

and a pointer to the node after which the insertion takes place,

eg void insert_node( struct node *head,

void insert_node( struct node *head,

struct node *prevnode ) { struct node *list

!= prevnode ) list = list->next

DYNAMIC MEMORY ALLOCATION (CALLOC,

SIZEOF,

FREE) It is desirable to dynamically allocate space for variables at runtime

It is wasteful when dealing with array type structures to allocate so much space when declared,

This practice may lead to memory contention or programs crashing

A far better way is to allocate space to clients when needed

The C programming language allows users to dynamically allocate and deallocate memory when required

The functions that accomplish this are calloc(),

which allocates memory to a variable,

which determines how much memory a specified variable occupies,

which deallocates the memory assigned to a variable back to the system

SIZEOF The sizeof() function returns the memory size of the requested variable

This call should be used in conjunction with the calloc() function call,

so that only the necessary memory is allocated,

Consider the following,

x now contains the information required by calloc() so that it can allocate enough memory to contain another structure of type date

CALLOC This function is used to allocate storage to a variable whilst the program is running

The function takes two arguments that specify the number of elements to be reserved,

and the size of each element (obtained from sizeof) in bytes

The function returns a character pointer (void in ANSI C) to the allocated storage,

which is initialized to zero's

date_pointer = (struct date *)

The (struct date *) is a type cast operator which converts the pointer returned from calloc to a character pointer to a structure of type date

The above function call will allocate size for ten such structures,

and date_pointer will point to the first in the chain

FREE When the variables are no longer required,

the space which was allocated to them by calloc should be returned to the system

This is done by,

Other C calls associated with memory are,

allocate a block of memory from the heap allocate a block of memory,

do not zero out zero a section of memory move bytes from one location to another

Other routines may be included in the particular version of the compiler you may have,

memccpy memchr memcmp memcpy memset character movedata

copies characters from one buffer to another returns a pointer to the 1st occurrence of a designated character searched for compares a specified number of characters copies a specified number of characters initialise a specified number of bytes with a given copies characters

EXAMPLE OF DYNAMIC ALLOCATION

struct node * initialise( void )

void freenodes( struct node * )

void readline( char buff[] ) { int ch,

struct node * initialise( void ) { return( (struct node *) calloc(1,

} /* free memory allocated for node */ void freenodes( struct node *headptr ) { struct node *temp

while( headptr ) { temp = headptr->next

} } /* insert a new node after nodeptr,

return 1 = success */ int insert( struct node *nodeptr ) { char buffer[20]

/* allocate a new node */ if( newptr == NULL ) { return 0

} else { /* fill in its data and add to the list */ newptr->next = nodeptr->next

} /* delete a node from list */ void delete( struct node *headptr,

struct node *nodeptr ) { struct node *deletepointer,

/* find the entry */ printf("\nEnter name to be deleted

while( deletepointer ) { if( strcmp( buffer,

deletepointer->data ) == 0 ) { /* delete node pointed to by delete pointer */ previouspointer->next = deletepointer->next

} else { /* goto next node in list */ deletepointer = deletepointer->next

previouspointer = previouspointer->next

? */ if( deletepointer == NULL ) printf("\n\007Error,

%s not found or list empty\n",

/* adjust nodeptr to the last node in list */ nodeptr = headptr

!= NULL ) nodeptr = nodeptr->next

} } /* print out the list */ void list( struct node *headptr ) { struct node *listpointer

if( listpointer == NULL ) printf("\nThe list is empty

else { while( listpointer ) { printf("Name : %20s\n",

listpointer = listpointer->next

} } } /* main menu system */ void menu( struct node *headp,

struct node *nodep ) { int menuchoice = 1

!= 4 ) { printf("1 insert a node\n")

switch( menuchoice ) { case 1 : if( insert( nodep ) == 0 ) printf("\n\007Insert failed

default : printf("\n\007Invalid option\n")

main() { struct node *headptr,

*nodeptr

Another Linked List Example /* linked list example */ #include #include #include #include #include #include /* function prototypes */ struct node * initnode( char *,

void printnode( struct node * )

void printlist( struct node * )

struct node * searchname( struct node *,

void deletenode( struct node * )

void insertnode( struct node * )

void deletelist( struct node * )

/* definition of a data node for holding student information */ struct node { char name[20]

/* head points to first node in list,

end points to last node in list */ /* initialise both to NULL,

meaning no nodes in list yet */

struct node *head = (struct node *) NULL

struct node *end = (struct node *) NULL

allocates memory for the node,

and returns */ /* a pointer to the new node

Must pass it the node details,

name and id */ struct node * initnode( char *name,

ptr = (struct node *) calloc( 1,

if( ptr == NULL ) /* error allocating node

? */ return (struct node *) NULL

else */ else { /* allocated node successfully */ strcpy( ptr->name,

/* fill in name details */ ptr->id = id

/* copy id details */ return ptr

/* return pointer to new node */ } } /* this prints the details of a node,

the name and id /* must pass it the address of the node you want to print out void printnode( struct node *ptr ) { printf("Name

->%s\n",

->%d\n",

If you /* pass it 'head',

then it prints out the entire list,

by cycling through /* each node and calling 'printnode' to print each node found void printlist( struct node *ptr ) { while( ptr

!= NULL ) /* continue whilst there are nodes left { printnode( ptr )

/* print out the current node ptr = ptr->next

/* goto the next node in the list } }

*/ */ */

You must allocate a node and /* then pass its address to this function void add( struct node