Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Slides:



Advertisements
Similar presentations
Programming Languages and Paradigms The C Programming Language.
Advertisements

What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Kernighan/Ritchie: Kelley/Pohl:
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 1: Types, Operators and Expressions.
Declaring Arrays Declare an array of 10 elements: int nums[10]; Best practice: #define SIZE 10 int nums[SIZE]; // cannot be int[SIZE] nums; C99: int nums[someVariable]
CSSE221: Software Dev. Honors Day 28 Announcements Announcements Simulation grades coming back Simulation grades coming back All C Projects due Friday.
CS1061 C Programming Lecture 10: Macros, Casting and Intro. to Standard Library A. O’Riordan, 2004.
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
Guide To UNIX Using Linux Third Edition
COP 3275 COMPUTER PROGRAMMING USING C Instructor: Diego Rivera-Gutierrez
Computer Science 210 Computer Organization Introduction to C.
CECS 121 EXAM 1. /* C Programming for the Absolute Beginner */ // by Michael Vine #include main() { printf(“\nC you later\n”); system(“pause”); }
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
UniMAP Sem2-08/09 DKT121: Fundamental of Computer Programming1 Introduction to C – Part 2.
Sales person receive RM200/week plus 9% of their gross sales for that week. Write an algorithms to calculate the sales person’s earning from the input.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
Functions Why we use functions C library functions Creating our own functions.
Chapter 2: Using Data.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
UniMAP Sem1-07/08EKT120: Computer Programming1 Week2.
/* C Programming for the Absolute Beginner */ // by Michael Vine #include main() { printf(“\nC you later\n”); system(“pause”); }
Computers and Programming CPC The 2 nd lecture Jiří Šebesta.
Introduction to C Programming Chapter 2 : Data Input, Processing and Output.
CECS 121 Test 1. Functions allow you to group program statements under one name C and C++ are case-sensitive so main(), MAIN(), and Main() are all different.
Dennis Ritchie 1972 AT & T Bell laboratories (American Telephone and Telegraph) USA 1www.gowreeswar.com.
Lecture 1 cis208 January 14 rd, Compiling %> gcc helloworld.c returns a.out %> gcc –o helloworld helloworld.c returns helloworld.
Lexical Elements, Operators, and the C Cystem. C overview recap functions –structured programming –return value is typed –arguments(parameters) pointers.
Introduction As programmers, we don’t want to have to implement functions for every possible task we encounter. The Standard C library contains functions.
UniMAP SemI-09/10EKT120: Computer Programming1 Week 5 – Functions (1)
(language, compilation and debugging) David 09/16/2011.
CECS 130 EXAM 1. To declare a constant (read only) value: const int x = 20; const float PI = 3.14; Can we do this? const int x;
CS 261 – Recitation 2 Fall 2013 Oregon State University School of Electrical Engineering and Computer Science.
C/C++ Basics. Basic Concepts Basic functions of each language: Input, output, math, decision, repetition Types of errors: Syntax errors, logic errors,
/* C Programming for the Absolute Beginner */ // by Michael Vine #include main() { printf(“\nC you later\n”); system(“pause”); }
Copyright © 2002, Department of Systems and Computer Engineering, Carleton University 1 INPUT STREAMS ifstream xin; // declares an input stream.
GUJARAT KNOWLEDGE VILLAGE Faculty Name:- Prof H.M.Patel Students Name:- SONI VISHAL THAKKER BHAVIN ZALA JAYDIP ZALA.
Pointers *, &, array similarities, functions, sizeof.
Types of C Variables:  The following are some types of C variables on the basis of constants values it has. For example: ○ An integer variable can hold.
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 C Basics Tarek Abdelzaher and Vikram Adve.
C LANGUAGE Characteristics of C · Small size
UNIMAP Sem2-07/08EKT120: Computer Programming1 Week 2 – Introduction to Programming.
C Building Block Chapter 2. Variables A variable is a space in the computer’s memory set aside for a certain kind of data and given a name for easy reference.
1 Midterm 1 Review. 2 Midterm 1 on Friday February 27 Closed book, closed notes No computer can be used 50 minutes 4 or 5 questions write full programs.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
SCP1103 Basic C Programming SEM1 2010/2011 Arithmetic Expressions Week 5.
Variables, Operators, and Expressions
Arithmetic Expressions
Computer Science 210 Computer Organization
INC 161 , CPE 100 Computer Programming
Functions, Part 2 of 2 Topics Functions That Return a Value
Programming Languages and Paradigms
INC 161 , CPE 100 Computer Programming
C Short Overview Lembit Jürimägi.
Programming Paradigms
Programming Languages and Paradigms
Data Type.
Computer Science 210 Computer Organization
Lexical Elements, Operators, and the C Cystem
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
C Stuff CS 2308.
Data Type.
Pointers Department of Computer Science-BGU יום רביעי 21 נובמבר 2018.
Lexical Elements, Operators, and the C Cystem
Outline Defining and using Pointers Operations on pointers
Data Type.
Programming Languages and Paradigms
Session 1 – Introduction to Computer and Algorithm (Part 2)‏
DATA TYPES There are four basic data types associated with variables:
Introduction to C Programming
COMP 2130 Intro Computer Systems Thompson Rivers University
Presentation transcript:

Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Contents Getting Started: the first program data input and result output compilation and execution Variables, expressions, types, functions Control program flow loops, conditional statements Arrays and pointers Standard C libraries Preprocessing Makefiles

Getting started: C Program structure Any C programm consists of functions variables Functions consist of statements ( a=b+c, function call, etc. ) Statements includes expressions built with operations ( for example, arithmetical expressoins with “+“, “-“, “\“,“*“ )

Getting Started: Input and Output of Data #include main() { int a, b, result; printf(“Input a,b:\t“); scanf(“%d,%d“,&a,&b); result=a+b; printf(“%d plus %d is equal to %d \n“, a,b,result); }

Getting Started: Compilation In order to execute the programm, compile it with  gcc filename The executable file a.out will be produced, start it with:  a.out

Operators and Expressions in C binary (-,+,*,/,%,&&,||) x+y; year % 4; b && true Unary (-,+,*,&) int a=+2; int *pointer_to_a = &a; int b=-a; int sum = * pointer_to_a + b; postfix and prefix operators (++,--) a=2; b=++a; c=a++;

Variables and their Types There are following main types in C : bool (1 byte) char (1 byte) int (4 bytes) long, short, signed, unsigned int (4, 8 bytes) float (4 bytes) double (8 bytes) void For example: bool b=true; long int a; char c =`a`; a = ; 971 Memory:... reserved for a

Types of Expressions and Casting The types of single variables schould be declared by programmer: float f_number = ; double d_number = ; int i_number=3; Many operations cause automatic conversions of operands, in order to bring them to common type: i_number+f_number; -> int -> float sizeof(f_number + d_number)==8 float -> double sizeof(f_number + (float)d_number)==4 double -> float

Functions The function definition in C: ret_type name (arg_type1 arg_name1,...,arg_typeN argnameN) {... } double parabola(double x) { //declare the new variable, that will be returned return x*x; } double f0 = parabola(0); double f1 = parabola(1);

Are functions computing arithmetic expressins powerfull enough ? Now let us try to define the well-known factorial function in C. This function can be specified as follows:

Flow control: Conditional Statement To test logical conditions and make decisions use conditional statement IF-ELSE: if (condition) {... Statemen_block1... }else {... Statemen_block1... } For example: int f(int n){ if ( n>0 ) return n*f(n-1); else return 1; }

Loops: While and For for (init; cond; post){... } for (i=1; i<=n; i++){ fac=fac*i; } while (cond){... } while (i<=n){ fac=fac*i; i=i+1; } int i = 1; int fac = 1; do{... }while (cond) do{ fac=fac*i; i=i+1; }while (i<=n)

Arrays: Vectors and Matrices float x[3]={1,3,5}; #include ; float vector_norm=sqrt(x[1]*x[1]+x[2]*x[2]+x[3]*x[3]); float matrix_trace = A[1][1]+A[2][2]+A[3][3]; float A[3][3]={{1,2,3}, {3,2,1}, {5,6,7}};

Arrays : Strings Strings can be represented in C as arrays of characters (type char): For example: Memory: o\0lehl char str[]=“hello“; int i=0; while(str[i]!=‘\0‘){ printf(“%c\n“, str[i]); i++; }

Arrays: Pointers o\0lehl char str[]=“hello“; int i=0; while(str[i]!=‘\0‘){ printf(“%c\n“, str[i]); i++; }...str

Arrays: Pointers while(*str!=‘\0‘){ printf(“%c\n“,*(str++)); } o\0lehl...str

Indirection and Address Operators (*, &): Examples int x=1, y=2, z[10]; int *ip=&x; y=*ip; *ip=0; ip= &z[3];

Indirection and Address Operators (*, &): Examples void swap (int a, int b) { int tmp=a; a=b; b=tmp; } swap(a,b); // wrong Swap(&a,&b); // correct

Multidimensional Arrays: Pointers to Pointers float A[3][3]={{1,2,3}, {3,2,1}, {5,6,7}}; A[2]...A[1]

Multidimensional arrays A[2]...A[1] for(i=0;i<3;i++){ for(j=0;j<3;j++){ printf(“%f “, y[i][j]); } printf(“\n“); }

Arrays: Dynamic Programming As another example, let us implement the factorial calculation in a more efficient way. The main idea is to reuse once calculated results. We store them in an array.

Arrays: Dynamic Programming #include // the computed f(n) // will be stored here int results[10]; main(){ int i; /* Array initialization: write 0 in each field */ for(i=0; i<10;i++){ results[i]=0; } factorial(3);factorial(4); factorial(10); } int factorial(int n){ int res=1; for(i=n; i>0; i--) { // has the result been // already computed ? if(results[i]==0){ res=res*i; results[i]=res;} else return results[i]; } return fac; }

Memory allocation C provides a number of functions to allocate memory to store data in “ stdlib.h“ void *malloc(unsigned int nbytes); void free(void *ap)

Memory allocation #include int *results; main(){ results=malloc(100*sizeof(integer)); factorial(3);factorial(44); factorial(100); free(results); }

Preprocessing File inclusion #include #include “filename“ Macro substitutions #define max(A,B) (A)>(B) ? (A):(B) #define CONSTANT = 25 Conditional inclusion #ifndef __HELPER_H__ #define __HELPER_H__... #endif

Standard libraries stdio.h standard input and output printf, scanf, fprintf, fscanf, fopen, flcose,... string.h string processing Strlen, strcpy, strcat, strcmp,...

Standard libraries stlib.h memory allocation, random numbers, type conversion atof, atoi, rand, alloc, malloc, free math.h mathematical functions sin, cos, sqrt, strcmp, remainder,...

Compilation with makefiles Makefiles consist of macro definitions rules of compilation dependences declaration

Compilation with makefiles CC=gcc CFLAGS = -Wall –pedantic OBJ = helper.o init.o boundary.o uvp.o main.o all: $(OBJ) $(CC) $(CFLAGS) –o sim $(OBJ) –lm clean: rm $(OBJ) helper.o : helper.h init.o : helper.h init.h....