Introduction to the C Programming Language
description
Transcript of Introduction to the C Programming Language
Introduction to the CProgramming Language
Michael GriffithsCorporate Information and Computing ServicesThe University of SheffieldEmail [email protected]
• Part 1– Introduction to C Programming– Structured Program Development and Program Control– Application development tools
• Part 2– Functions– Pointers and Arrays
• Part 3– Characters and Strings– Data Types Structures
• Part 4– File Processing– Further Topics
Course Outline
Outline
• Introduction• Structured program development• Application development tools• Compiling applications
Introduction
• Developed late 70’s• Used for development of UNIX• Powerful
– If used with discipline
• ANSI Standard C– C90 ANSI/ISO 9899: 1990– C11 ISO/IEC 9899:2011 (formerly C1X)
• the current standard for the C programming language, replaces the previous C standard, informally known as C99
Program Development
• Edit– Create program and store on system
• Preprocessor– Manipulate code prior to compilation
• Compiler– Create object code and store on system
• Linker– Link object code with libraries, create executable output
• Loader• Execution
– CPU executes each instruction
Program Structure
• Collection of – Source files– header files– Resource files
• Source file layout• Function layout
Source file layout• program.c
Pre-processsor directivesGlobal declarations
main(){ ……….}
function1(){ …………}
function2(){ ………….}
Function Layout
vartype function(vartypes )
{
local variables to function
statements associated with function
……..
……..
}
Hello World
/*Program1: Hello World*/
#include <stdio.h>
main(){
printf("Welcome to the White Rose Grid!\n");
/*Welcome banner on several lines*/printf("Welcome to the \n \t White Rose Grid!\n");
}
Features of Hello World
• Lots of comments– Enclosed by /* */
• Statements terminated with a ;• Preprocessor statement
– #include <stdio.h>• Enables functions to call standard input ouput functions (e.g. printf,
scanf)• Not terminated with a ;
• Printf uses escape sequence characterse.g. \n newline
\t tab character
Standard Conforming Hello World
/*Program1: Hello World*/
#include <stdio.h>
int main(void){
printf("Welcome to the White Rose Grid!\n");
/*Welcome banner on several lines*/printf("Welcome to the \n \t White Rose Grid!\n");
return 0;}
Minimalist GNU for Windows (MinGW)
• Provides minimalist development environment for native Microsoft Windows applications.
• Open Source programming tool set, suitable for the development of native MS-Windows applications.
• Compilers provide access to the functionality of the Microsoft C runtime and some language-specific runtimes.
• Primarily intended for use on the MS-Windows platform, but also available for cross-hosted use
• MinGW includes:– A port of the GNU Compiler Collection (GCC), including C, C++, ADA and Fortran
compilers;
– GNU Binutils for Windows (assembler, linker, archive manager)– MSYS, a contraction of "Minimal SYStem", is a Bourne Shell command line
interpreter system. Offered as an alternative to Microsoft's cmd.exe, provides a general purpose command line environment,
Minimalist GNU for Windows (MinGW)
• If you are a windows user MinGW can be downloaded fromhttps://sourceforge.net/projects/mingw/files/MinGW/You should install the latest version.
• Information about MinGW is herehttp://www.mingw.org/
Starting a MinGW Session
• The example sessions will require you to use the gnu c/c++ compilers.
• These compilers are available through the MinGW sys.Start MinGW, this will open a console window.It is advisable to:
• From The University of Sheffield Managed Windows– Change directory to the u drive by typing
cd u:\\– Make a directory for the course material by typing
mkdir ccourse – Move to this new directory by typing
cd course
• When you download the course material you should copy the zip archive of course examples to the ccourse folder you just created.
Compilation
• To compile the program myprog.c using the GNU C Compiler– gcc myprog.c –o myprog
• Example compile arith.c– Modify program arith.c to test the effect of the decrement
and increment operations– Modify program arith.c and test the assignment operations
Variable Types
Type Size (Bytes)
Lower Upper
int 4 -231 +231-1
float 4 -3.2X1032 3.2X1032
double 8 -1.7X10302 1.7X10302
char 1 - -
unsigned char 1 0 255
unsigned short int
2 0 65536
short int 2 -32768 32767
Variables• Other types using unsigned and long
– long double, long int, short int, unsigned short int
• Precision and range machine dependent• Variables of the same type are compared using the
comparison operator ==• Variable declaration using the assignment operator =
float myfloat;
float fanother=3.1415927;
Operators• Arithmetic operations
=, -, /, %, *• Assignment operations
=, +=. -=, *=, %=, /=, !• Increment and decrement (pre or post) operations
++, --• Logical operations
||, &&, !• Bitwise operations
|, &, ~• Comparison
<, <=, >, >=, ==, !=
Input and Output Using stdio.h
• printf– Provides formatted input and output– Input for printf is a format specification followed by a list of variable names
to be displayed– printf(“variable %d is %f\n”, myint, myfloat);
• scanf– Provided an input format and a list of variables– scanf(“%d”, &myint);– Note variable name has & in front
• Programarith.c is an example of the arithmetic operaions, printf and scanf.
Example of printf and scanf
• Example program arith.c– Worksheet problem 3, use the decrement (--) and increment operators(++)
to modify the variables sum and difference– Add a line requesting the user to input a floating point variable called f1 – Add a line to multiply the new variable f1 by the variable sum– Add a line to display the variable f1
/*Request input from the user*/printf("Enter the first integer\n"); scanf("%d", &i1); /*Read in the integer*/printf("Enter the second integer\n"); scanf("%d", &i2);
Escape characters Escape
SequenceDescription
\n Newline, position cursor at the start of a new line
\t Horizontal tab, move cursor to the next tab stop
\r Carriage return. Position cursor to the beginning of the current line; do not advance to the next line.
\a Alert, sound system warning beep
\\ Backslash, print a backslash character in a printf statement
\” Double quote print a double quote character in a printf statement.
Format Specifiers for printf and scanf
Data Type
Printf specifier Scanf specifier
long double %Lf %Lf
double %f %lf
float %f %f
unsigned long int %lu %lu
long int %ld %ld
unsigned int %u %u
int %d %d
short %hd %hd
char %c %c
Control
• Sequence Structures• Selection Structures
– if… else statements– switch structures
• Repetition Structures– for loops– while loops
Conditional Statements Using if…else
• The if statement allows decision making functionality to be added to applications.
• General form of the if statement is:
if(condition)statement;
Using else
• An alternative form of the if statement is if(condition)
statement;else
statement;
If the condition is true the first statement is executed if it is false the second statement is executed.
Repetition Using while
• Execute commands until the conditions enclosed by the while statement return false.
while(conditions){
statements;}
Simple if Example Demonstrating Syntax
int main(void){ float f1; printf("Enter a floating point number.\n"); scanf("%f",&f1); if(f1<0) printf("Please enter a value gerater 0\n"); else if (f1>100) printf("f1 is greater than 100\n"); else printf("The value is %f\n",f1); return 0;}
while
• Good practice to always use {} in a do while loop
while(conditions) { statements…;
Statements…;}
do … while
• Good practice to always use {} in a do while loop
do{ statements…;
Statements…;}while(conditions)
While example demonstrating a countdownint main (void){ int n; printf( "Enter the starting number\n"); scanf("%d".&n); while (n>0) { printf("%d, ",n); --n; } printf("FIRE!\n"); return 0;}
Try this code then modify it by introducing a second variable m initialised to 10. Use the && operator to add a test m<10 to the Condition in the while statement.
Example of while and if statement usage
while(files<=5) {
printf("Enter file location(1=Titania, 2=Maxima): "); scanf("%d", &result);
if(result==1) ntitania_files = ntitania_files+1; else if(result==2) nmaxima_files = nmaxima_files+1; else nother_files=nother_files+1;
files++; }/*End of while file processing loop*/
Increment counter
Continue counting untilMaximum number of files entered (5)
Use conditions to update variables
Request and get user input
Counter Controlled Repetition
• Components of a typical for loop structure
for(expression1; expression2; expression3)statement;
for(counter=1; counter<=10, counter++)
statement;
example
for loop example
• Example program for.c– Modify the program so that it performs a count down
main(){ int counter, nsteps=10; /* initialisation, repetition condition and increment */ /* are all included in the for structure header */ for(counter=1; counter<=nsteps; counter++)
printf("%d\n", counter); return 0;}
Multiple selection Structures Using Switch • Used for testing variable separately and selecting a
different actionswitch(file){
case 'm': case 'M':++nMaxima;
break;case 't': case 'T':
++nTitania;break;default: /*Catch all other characters*/
++nOther;break;
} /*End of file check switch */
Practical Examples – basic coding
• Inspect, Compile and run the following• Finding a root using the Newton-Raphson method
– While statement
• Finding a root by method of bisection– If statement, while statement– And simple one line function!
Application Development Tools• Minimal for Windows (MinGW)
– http://www.mingw.org/ • Bloodshed
– c++ open source for windows– Available on managed windows– http://www.bloodshed.net/
• Eclipse with the c development toolkit– Open source and available for windows and linux– Available on iceberg– http://www.eclipse.org/
• Salford (C and FORTRAN)– Obtain from IT centre, not open source, site license is available
• Microsoft visual c++
Starting a New Project in devshed
• From the menu select File and New Project• From the dialog that opens
– Set the name of the project to the same name as the course c file– Click the c-project– Select project type console application
• Add a source file to the project– From the menu select project and Add to Project– If there is a main.c remove that file from the project pane (normally on the left hand
side)– Before the return statement in the main function add the line– system(“PAUSE”);
Compilers
Language GNU Portland Intel
C gcc pgcc icc
C++ g++ pgCC icpc
Fortran 77 g77 pgf77
Fortran90/95 gfortran pgf90 ifort
Invoking the Compiler
• Compiling FORTRAN Programs– g77 –o mycode [options] mycode.f
• Compiling c/c++ Programs– gcc –o mycode [options] mycode.c
Compiler Options
Option Action-s remove any symbol and object relocation information from
the program. This is used to reduce the size of program and runtime overhead
-c Compile, do not link.
-o exefile Specifies a name for the resulting executable.
-g Produce debugging information (no optimization).
-Ilibrary_name (lower case L)
Link the given library into the program.
e.g. include math library by using option -lm
-ldirectory-name (upper case I)
Add directory to search path for include files
-O N Set optimisation level to N
-Dmacro[=defn] Define a macro
Summary
• Program Structure• Control Structures for C Programming• Compilers and development Environments