IS12 – Introduction to Programming Introductory Topics Date: January 15, 2003 Introduction to C



Download 24.02 Kb.
Date07.08.2017
Size24.02 Kb.

IS 12






IS12 – Introduction to Programming

Introductory Topics

Date: January 15, 2003
Introduction to C
The C language has been standardized by ANSI (American National Standards Institute). Eventually a world wide standard will develop as a result of ISO (International Standards Organization).

 

Two types of programming include





  • Structured programming

  • Object orientation programming
     

Structured Programming often called traditional programming is a procedure oriented language. These languages are action oriented.

 

Object Oriented Programming (OOP) is working with real-world objects. This type of software development models communication between objects. OOP encapsulates the data (attributes) and functions (behaviors) into packages called objects. Another feature is information hiding. These languages are object oriented. Programmers write classes or user-defined types. Each class contains data and functions that manipulate the data.  



Programmers focus on objects rather than functions. 

 

Software development costs are on the rise. Proven software development methods that can reduce software development costs include structured programming, top-down stepwise refinement, functionalization and object-oriented programming.



 

C and C++ are the programming languages for writing software for system, application, networking, and distributed client/server applications.




The history of C and C++


 

C++ was derived from C which was developed from previous languages BCPL and B.BCPL. These were developed by Martin Richards in 1967. This language was written in order to design operating systems software and compilers. (System software). Ken Thompson developed B language after BCPL and B to create early versions of UNIX at Bell Labs in 1970 on a DEC PDP-7. C was developed from B by Dennis Ritchie at Bell Labs in 1972. C was the development language of the UNIX operating system. Today, most software is written in this language. C is now available on all hardware platforms. C is hardware independent meaning that it is portable to all computer systems. Referred to as class C or Kernighan and Richie C. ANSI and ISO were responsible for standardizing C.

 

C has a collection of libraries to accommodate the programmer.


Basics of a typical C Environment


 

Most products have a development area (Interactive development environment IDE). This environment is used by programmers to create C and C++ programs. The IDE means that all of the tools needed to run a software program written in C are together in one area. The tools include the text editor, compiler, linker and debugger software. Be sure to consult the help screens for each of the main menus and submenus so as to become familiar with the IDE.

 

C programs go through the following phases: edit, preprocess, compile, link, load, and execute.



The edit phase allows you to enter and modify your C code. When you save your file, the system will automatically tag a c extension to the program. Use the file save menu to save the file onto your diskette. Use the mouse to active the menus

The preprocessor phase carries out special instructions called preprocessor directives that must be done prior to the compilation phase. This may involve including other files in the program that is being compiled.

The compilation phase will compile the program. Select the compile menu from the menu bar and select compile. This command will perform the translation of source code in to object code for the next phase. Compiling a source code program creates an object (same file name.obj) extension. Microsoft visual product use Build, Compile commands.

Errors here are referred to as compilation, syntax errors

The linking phase can be done automatically by the system during the run phase or you can select it from the compile menu. Linking the object file creates an executable (.exe) program that is a combination of all the files needed to run the program properly. (patching of holes). Microsoft visual product use Build, Build commands.

Getting everything together from all of the libraries into one file.

The loader program is responsible for loading the program to be executed into main memory.

The run command will perform the actual program logic. The type of errors that could occur here are run-time errors (divide by zero) and logic errors (indicated by incorrect output).


Printing Information using printf


/* First Program Sample */

#include

int main( )

{

printf( "Welcome to The University of Pittsburgh!\n" );



return 0;

}

Sample Output



Welcome to The University of Pittsburgh!

Press any key to continue



Comments


Comments begin with /* and end with */ You can also include comments on the instruction line in order to clarify information. You should document your programs with your name, date written, and objective of the program. Include additional comments where needed to clarify code/operationos. Comments are ignored by the compiler and do not perform any actions what so ever.

The Preprocessor directive #include indicates that the program will use the standard input and output header file. It is used when referring to library functions such as printf (print information on the screen) and scanf (obtain data from the user).

int main() is the main function building block. It must be coded as part of every C program.

The {


} must precede and succeed every function.

Scanf and printf (library function calls)


Input and output via scanf and printf

scanf (standard input) function is used to obtain input from the user via the keyboard.

printf (standard output) function is normally used to display information to the screen.

The \n escape character does not print. This escape sequence indicates cursor positioning to the next line. Other escape sequences are listed as \t horizontal tab; \r carriage return; \a alert is used to sound the system bell; \\ is used to print a backslash character; and the double quote character \" is used to print a double quote character. Example is

"\"a string of quotes\""

The statement ends with a ; - also referred to as a statement terminator. All statements end with a ;.

The return 0; is included at the end of every main function. It is a method to exit a function. The value zero indicates that the program terminated successfully.

Use indenting in your programs for readability


Printing using two printf commands

/* Uisng two printf commands */

#include

int main()

{

printf( "Welcome " );

printf( "to the University of Pittsburgh\n" );

return 0;

}

Variables


Variables represent values that are stored in memory. A variable must be defined before it can be used by the function/program. The variable is a storage location in which data is assigned. Since the data in the variable (memory location) may vary, it is called a variable. Each variable can be defined on separate lines as well. All variable names are made up by the programmer. Variables must follow a specific set of rules: All variables must be defined as a valid identifier. An identifier is a series of characters containing letters, digits, and underscores. The variable cannot begin with a digit, but it can start with an underscore. Variables are case sensitive so watch out for this. Use of variable names up to 31 characters will ensure portability features. Avoid usage of the _underscore character. Why? Make your variable names documentary as to what the data content will be. Code a variable dictionary as to what each variable represents. Declaration - indicates the data type (integer, float, char, etc of the variable:

Types include: char (single character), unsigned int (larger number up to 65,535), int (-32768 to 32767), long -2,147,483,648 to 2,147,483,647, float (scientific) -3.4* 10 ^ 38 to 3.4 ^ 38, double (also a float type) -1.7 * 10^308 to 1.7 * 10 ^ 308

The size of the variable is dependent on the system implementation ( int takes up two byes), (float takes up four byes) etc.

When the program is reexecuted, the old values contained in the variables are replaced with new data items. (Destructive Read In)

When scanf executes it prompts the user as to what type of data must be typed in. The scanf has two arguments, the format control string (type of data), and the coversion specifier. Program execution stops and waits for response by the user/programmer. Press enter when finished. The data will then be assigned to the variable that it represents. This type of program execution is often termed conversational or interactive computing Notice the usage of the & prior to each variable contained on the scanf function.

Usage in printf and scanf functions

Data types printf scanf

long double %Ff %Lf

double %f %lf

float %f %f

uns long int %lu %lu

long int %ld %ld

uns int %u %u

int %d %d

short %hd %hd

char %c %c


Sample program with scanf and printf

#include


int main()

{

int integer1, integer2, sum; /* declaration */


printf( "Enter first integer\n" ); /* prompt */

scanf( "%d", &integer1 ); /* read an integer */

printf( "Enter second integer\n" ); /* prompt */

scanf( "%d", &integer2 ); /* read an integer */

sum = integer1 + integer2; /* assignment of sum */

printf( "Sum is %d\n", sum ); /* print sum */


return 0; /* indicate that program ended successfully */

}

Assignment statement


Will assign the value from right to left. The assignment operator is one = sign. (Two equal signs do comparison x == c)

Calculations can also be output directly on the printf function


Arithmetic


Arithmetic Operations (binary operators) Precedence

( ) (highest order of precedence) * / % (left to right), + - (left to right) There is no symbol for exponentiation. We need to use the pow for power function.

Discussion of % (modulus) can only be used with int data types. A Syntax error occurs if not.

Rules of operator precedence

() are evaluated first

* / and % are evaluated next (left to right)

+ and – are evaluated last (left to right)

What happens if we want to add int to a float? C promotes smaller types to larger ones according to a set of rules. s.


Equality and Relational Operators


If statement implementation is discussed here. The if statement evaluates a condition and based on the condition it will execute true or false statements. The relationships can be formed by use of the following operators:

Equality Operators == !=

Relational Operators > < >= <=

Order of precedence:



< <= > >= == !=

Do not use spaces in between the operators. Do not reserve the signs in the statement Do not confuse the == (is equal to) and = (assignment) operators Be sure to use indentation on if in order to improve readability

#include

main()


{

int num1, num2;

printf( "Enter two integers, and I will tell you\n" );

printf( "the relationships they satisfy: " );

scanf( "%d%d", &num1, &num2 ); /* read two integers */

if ( num1 == num2 )

printf( "%d is equal to %d\n", num1, num2 );
if ( num1 != num2 )

printf( " %d is not equal to %d\n ", num1, num2 );


if ( num1 < num2 )

printf( "%d is less than %d\n", num1, num2 );


if ( num1 > num2 )

printf( "%d is greater than %d\n", num1, num2 );


if ( num1 <= num2 )

printf( "%d is less than or equal to %d\n", num1, num2 );


if ( num1 >= num2 )

printf( "%d is greater than or equal to %d\n", num1, num2 );


return 0; /* indicate program ended successfully */

}

Exercises for in class


  1. Write a program that will input six scores and then sum, average, and the largest and smallest number. Print out the numbers, as well as the sum, average, the largest and smallest number.



  1. Write aprogram to calculate the squares and cubes of numbers 1 through 5.

Reference used

Deitel, H., and Deitel, P. (2001). C How to Program, Third Edition. NJ: Prentice hall.
Download 24.02 Kb.

Share with your friends:




The database is protected by copyright ©ininet.org 2020
send message

    Main page