Introduction to C Creating your first C program. Writing C Programs  The programmer uses a text editor to create or modify files containing C code. 

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Chapter 11 Introduction to Programming in C
11-2 Identify the parts of the “main” function, which include Preprocessor Directives main function header main function body which includes Declaration.
Lecture 2 Introduction to C Programming
Introduction to C Programming
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
Introduction to C Programming
Structure of a C program
C Programming Basics Lecture 5 Engineering H192 Winter 2005 Lecture 05
1 Lecture 2  Input-Process-Output  The Hello-world program  A Feet-to-inches program  Variables, expressions, assignments & initialization  printf()
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
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?
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
1 ICS103 Programming in C Lecture 2: Introduction to C (1)
Introduction to C Programming
CMSC 104, Version 9/011 Introduction to C Topics Compilation Using the gcc Compiler The Anatomy of a C Program 104 C Programming Standards and Indentation.
Introduction to C Topics Compilation Using the gcc Compiler
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
C Programming. Chapter – 1 Introduction Study Book for one month – 25% Learning rate Use Compiler for one month – 60%
Introduction to C/C++ Programming This lecture has major focus on programming, compilation.
By: Mr. Baha Hanene Chapter 3. Learning Outcomes We will cover the learning outcome 02 in this chapter i.e. Use basic data-types and input / output in.
Computer Science 210 Computer Organization Introduction to C.
CS 11 C track: lecture 1 Preliminaries Need a CS cluster account cgi-bin/sysadmin/account_request.cgi Need to know UNIX ITS.
C Programming Lecture 3. The Three Stages of Compiling a Program b The preprocessor is invoked The source code is modified b The compiler itself is invoked.
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
C Programming Tutorial – Part I CS Introduction to Operating Systems.
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
Creating your first C++ program
Programming With C.
CMSC 104, Version 9/011 Introduction to C Topics Compilation Using the gcc Compiler The Anatomy of a C Program 104 C Programming Standards and Indentation.
C STRUCTURES. A FIRST C PROGRAM  #include  void main ( void )  { float height, width, area, wood_length ;  scanf ( "%f", &height ) ;  scanf ( "%f",
1 Programming in C Hello World! Soon I will control the world! Soon I will control the world!
Algorithms  Problem: Write pseudocode for a program that keeps asking the user to input integers until the user enters zero, and then determines and outputs.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 5P. 1Winter Quarter C Programming Basics Lecture 5.
CSC141 Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture - 6.
Introduction to C 2008/09/29: Lecture 7 CMSC 104, Section 0101 John Y. Park 1.
CMSC 104, Lecture 111 Introduction to C Topics l Compilation l Using the gcc Compiler l The Anatomy of a C Program l 104 C Programming Standards and Indentation.
CMSC 1041 Introduction to C Creating your first C program.
Anatomy of the simplest C Program Sen Zhang SUNY Oneonta Oneonta, NEW YORK © 2004
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
Scott Marino MSMIS Kean University MSAS5104 Programming with Data Structures and Algorithms Week 1 Scott Marino.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
1 C Syntax and Semantics Dr. Sherif Mohamed Tawfik Lecture Two.
L071 Introduction to C Topics Compilation Using the gcc Compiler The Anatomy of a C Program Reading Sections
Chapter 1 slides1 What is C? A high-level language that is extremely useful for engineering computations. A computer language that has endured for almost.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
Introduction to C Topics Compilation Using the gcc Compiler
UMBC CMSC 104 – Section 01, Fall 2016
CSCE 206 Structured Programming in C
Computer Science 210 Computer Organization
A bit of C programming Lecture 3 Uli Raich.
Algorithms Problem: Write pseudocode for a program that keeps asking the user to input integers until the user enters zero, and then determines and outputs.
Introduction to C Topics Compilation Using the gcc Compiler
Introduction to C Topics Compilation Using the gcc Compiler
C Basics.
Introduction to C Programming
Computer Science 210 Computer Organization
Introduction to C Programming
Govt. Polytechnic,Dhangar
Introduction to C Topics Compilation Using the gcc Compiler
Creating your first C program
Introduction C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell.
2008/09/29: Lecture 7 CMSC 104, Section 0101 John Y. Park
C Programming Getting started Variables Basic C operators Conditionals
Introduction to C Topics Compilation Using the gcc Compiler
An Overview of C.
DATA TYPES There are four basic data types associated with variables:
Introduction to C Topics Compilation Using the gcc Compiler
Introduction to C Programming
Presentation transcript:

Introduction to C Creating your first C program

Writing C Programs  The programmer uses a text editor to create or modify files containing C code.  C code is also called source code  A file containing source code is called a source file  After a source file has been created, the programmer must invoke the C compiler.

Invoking the Compiler Example gcc pgm.c where pgm.c is the source file that contains a program

The Result : a.out  If there are no errors in pgm.c, this command produces an executable file, one that can be run or executed. Both the cc and the gcc compilers name the executable file a.out To execute the program, type./a.out at the Unix prompt.  Although we call this “compiling a program”, what actually happens is more complicated.

3 Stages of Compilation 1Preprocessor - modifies the source code Handles preprocessor directives Strips comments and whitespace from the code

3 Stages of Compilation 2Compiler - translates the modified source code into object code Parser - checks for errors Code Generator - makes the object code Optimizer - may change the code to be more efficient

3 Stages of Compilation 3Linker - combines the object code of our program with other object code to produce the executable file. The other object code can come from: The Run-Time Library - a collection of object code with an index so that the linker can find the appropriate code. other object files other libraries

Compilation Diagram Editor Compiler Preprocessor Parser Code Generator Optimizer Linker < Source File myprog.c Object File myprog.o Other Obj’s Run-time library Other libraries Executable file a.out

An algorithm for writing code Write the algorithm Write the code using vi (pico, emacs) Try to compile the code While there are still syntax errors Fix errors Try to compile the code Test the program Fix any semantic errors Compile the code Test the program

Incremental Approach to Writing Code  Tips about writing code.  Write your code in incomplete but working pieces.  For instance: For your project Don’t write the whole program at once. Just write enough that you display the prompt to the user on the screen. Get that part working first. Next write the part that gets the value from the user, and then just print it out.

Incremental Approach to Writing Code (continued) Get that working. Next change the code so that you use the value in a calculation and print out the answer. Get that working. Make program modifications: ○ perhaps additional instructions to the user ○ a displayed program description for the user ○ add more comments. Get the final version working.

Structure of a ‘C’ program pre-processor directives global declarations function prototypes main() { local variables to function main ; statements associated with function main ; } f1() { local variables to function 1 ; statements associated with function 1 ; } f2() { local variables to function f2 ; statements associated with function 2 ; }.

A Simple C Program /* Filename: hello.c Author: Brian Kernighan & Dennis Ritchie Date written: ?/?/1978 Description: This program prints the greeting “Hello, World!” */ #include main ( ) { printf (“Hello, World!\n”) ; }

Anatomy of a C Program program header comment preprocessor directives main ( ) { statement(s) }

The Program Header Comment  All comments must begin with the characters /* and end with the characters */  The program header comment always comes first  The program header comment should include the filename, author, date written and a description of the program

Preprocessor Directive  Lines that begin with a # are called preprocessor directives  The #include directive causes the preprocessor to include a copy of the standard input/output header file stdio.h at this point in the code.  This header file was included because it contains information about the printf ( ) function that’s used in this program.

main ( )  Every program has a function called main, where execution begins  The parenthesis following main indicate to the compiler that it is a function.

Left Brace  A left curly brace -- { -- begins the body of every function. A corresponding right curly brace must end the function.  The style is to place these braces on separate lines in column 1.

printf (“Hello, World!\n”) ;  This is the function printf ( ) being called with a single argument, namely the string “Hello, World!\n”  Even though a string may contain many characters, the string itself should be thought of as a single quantity.  Notice that this line ends with a semicolon. All statements in C end with a semicolon.

Right Brace  This right curly brace -- } --matches the left curly brace above.  It ends the function main ( ).

Common variable types int - stores integers ( to ) unsigned int – 0 to char – holds 1 byte of data (-127 to 128) unsigned char – holds 1 byte (0 to +255) long – usually double int (signed) unsigned long – positive double int float – floating point variable double – twice of a floating point variable Note: local, global and static variables

scanf scanf (“conversion specifier”,variable); scanf (“%d”,&i); Usual variable type Display: %c char single character %d (%i) int signed integer %f float or double signed decimal

printf printf (“%d”,i); Usual variable type Display %c char single character %d int %i signed integer %e (%E) float or double exponential format %f float or double signed decimal %g (%G) float or double use %f or %e as required %o int unsigned octal value %p pointer address stored in pointer %s array of char sequence of characters %u int unsigned decimal %x (%X) int unsigned hex value

Operators + addition - subtraction * multiplication / division % mod or remainder (e.g., 2%3 is 2), also called 'modulo' << left-shift (e.g., i<<j is i shifted to the left by j bits) >> right-shift & bitwise AND | bitwise OR ^ bitwise exclusive-OR && logical AND (returns 1 if both operands are non-zero; else 0) || logical OR (returns 1 if either operand is non-zero; else 0) < less than (e.g., i<j returns 1 if i is less than j) > greater than <= less than or equal >= greater than or equal == equals != does not equal

Operators (contd.) Increment and Decrement Operators ++ Increment operator -- Decrement Operator k++ or k-- (Post-increment/decrement) k = 5; x = k++; // sets x to 5, then increments k to 6 ++k or --k (Pre-increment/decrement) k = 5; x = ++k; // increments k to 6 and then sets x to the // resulting value, i.e., to 6

Example – total cost calculator #include main() { float cost =0.0; float tax = 0.08; float totalCost = 0.0; printf(“Enter the cost of the item:”); scanf(“%f”, &cost); totalCost = cost *tax + cost; printf(“Total cost is : %f\n”, totalCost); }

Exercises Extra Credit – Write a volume and surface area calculator

Functions and Prototypes Building blocks of code Group relevant and repetitive actions into functions Variables are usually local (they exist only inside the function) type FunctionName(type declared parameter list) { statements that make up the function }

Example function #include int add1(int); void main() { int x; x=5; x=add1(x); printf("%d“,x); } int add1(int i) { int y; y=i+1; return (y); } Returns an integer result Expects an integer parameter

Conditional clauses if (expression) statement else statement if (x==1) { printf(“Hello”); printf (“hi\n”); } else { printf(“World’); }

Conditional Loops while (expression) statement while (x<1000) x++; while (x<1000) { x++; y=y+10; }

Conditional Loops do statement while (expression) x = 0; do { x++; } while (x<1000);

Unconditional Loops for( initialization; expression; increment ) statement for (i=0;i<100;i++) { printf("Hi."); }

The switch statement The C switch allows multiple choice of a selection of items at one level of a conditional where it is a far neater way of writing multiple if statements switch (expression) { case item1: statement1; break; case item2: statement2; break; case itemn: statementn; break; default: statement; break; }

Arrays Declaration: int x[10]; double y[15]; x[5]=10; char c[15]; Note arrays start with 0 element

Pointers A pointer in C is the address of something The unary operator `&' is used to produce the address of an object int a, *b, c; // b is a pointer b = &a; // Store in b the address of a c = *b; // Store in c the value at // address b (i.e., a) Pointers to pointers Pointers to functions

Character Pointers & Arrays char *y; char x[100]; y = &x[0]; y = x; // Does the same as the line above *(y+1) gives x[1] *(y+i) gives x[i]

Structures User defined ‘data type’ struct emprec { char name[25]; int age; int pay; }; struct emprec employee; employee.age=32;

Nice to have Add plenty of comments /* */ or // Good layout. main(){printf("Hello World\n");} Use meaningful variable names Use brackets to avoid confusion a=( ) * ( ) / 2.0 Initialize your variables

Good Programming Practices  C programming standards are available on the Web  These standards include: Naming conventions Use of whitespace Use of Braces Comments

Examples of Comment Styles /* a comment */ /*** another comment ***/ /*****/ /*A comment can be written in this * fashion to set it off from the * surrounding code. */

More Comments /*******************************************\ * If you wish, you can put comments * * in a box. This is typically used for * * program header comments and for * * function header comments * \*******************************************/

Use of Whitespace  Use blank lines to separate major parts of a source file or function  Separate declarations from executable statements with a blank line  Preprocessor directives, main(), and the braces are in column 1

Use of Whitespace (continued)  All executable statements are indented one tab stop. How deep should my tabs be ?  Either 3 or 4 spaces. Choose whichever you like and use that same number consistently throughout your program.  2 spaces are not enough for good readability, more than 4 causes the indentation to be too deep.