SlideShare a Scribd company logo
Introduction to C
Introduction to C









Basics
If Statement
Loops
Functions
Switch case
Pointers
Structures
File I/O
Introduction to C: Basics
//a simple program that has variables
#include <stdio.h>
int main()
{
int x; //(32 bits)
char y; //(8 bits)
float z; //(32 bits)
double t; //(64 bits)
printf(“hello world…n”);
int test; //wrong, The variable declaration must appear first
return 0;
}
Introduction to C: Basics
//reading input from console
#include <stdio.h>
int main()
{
int num1;
int num2;
printf( "Please enter two numbers: " );
scanf( "%d %d", &num1,&num2 );
printf( "You entered %d %d", num1, num2 );
return 0;
}
Introduction to C: if statement
#include <stdio.h>
int main()
{
int age;
/* Need a variable... */
printf( "Please enter your age" ); /* Asks for age */
scanf( "%d", &age );
/* The input is put in age */
if ( age < 100 )
{
/* If the age is less than 100 */
printf ("You are pretty young!n" ); /* Just to show you it works... */
}
else if ( age == 100 )
{
/* I use else just to show an example */
printf( "You are oldn" );
}
else
{
printf( "You are really oldn" ); /* Executed if no other statement is*/
}
return 0;
}
Introduction to C: Loops(for)
#include <stdio.h>
int main()
{
int x;
/* The loop goes while x < 10, and x increases by one every loop*/
for ( x = 0; x < 10; x++ )
{
/* Keep in mind that the loop condition checks
the conditional statement before it loops again.
consequently, when x equals 10 the loop breaks.
x is updated before the condition is checked. */
printf( "%dn", x );
}
return 0;
}
Introduction to C: Loops(while)
#include <stdio.h>
int main()
{
int x = 0; /* Don't forget to declare variables */
while ( x < 10 )
{ /* While x is less than 10 */
printf( "%dn", x );
x++; /* Update x so the condition can be met eventually */
}
return 0;
}
Introduction to C: Loops(do while)
#include <stdio.h>
int main()
{
int x;
x = 0;
do
{
/* "Hello, world!" is printed at least one time
even though the condition is false*/
printf( "%dn", x );
x++;
} while ( x != 10 );
return 0;
}
Introduction to C: Loops(break and
continue)
#include <stdio.h>
int main()
{
int x;
for(x=0;x<10;x++)
{
if(x==5)
{
break;
}
printf("%dn",x);
}
return 0;
}

0
1
2
3
4

#include <stdio.h>
int main()
{
int x;
for(x=0;x<10;x++)
{
if(x==5)
{
continue;
}
printf("%dn",x);
}
return 0;
}

0
1
2
3
4
6
7
8
9
Introduction to C: function
#include <stdio.h>
//function declaration
int mult ( int x, int y );
int main()
{
int x;
int y;
printf( "Please input two numbers to be multiplied: " );
scanf( "%d", &x );
scanf( "%d", &y );
printf( "The product of your two numbers is %dn", mult( x, y ) );
return 0;
}
//define the function body
//return value: int
//utility: return the multiplication of two integer values
//parameters: take two int parameters
int mult (int x, int y)
{
return x * y;
}
#include <stdio.h>
//function declaration, need to define the function body in other places
void playgame();
void loadgame();
void playmultiplayer();
int main()
{
int input;
printf( "1. Play gamen" );
printf( "2. Load gamen" );
printf( "3. Play multiplayern" );
printf( "4. Exitn" );
printf( "Selection: " );
scanf( "%d", &input );
switch ( input ) {
case 1:
/* Note the colon, not a semicolon */
playgame();
break;
//don't forget the break in each case
case 2:
loadgame();
break;
case 3:
playmultiplayer();
break;
case 4:
printf( "Thanks for playing!n" );
break;
default:
printf( "Bad input, quitting!n" );
break;
}
return 0;
}

switch
case
Introduction to C: pointer variables



Pointer variables are variables that store memory addresses.
Pointer Declaration:






Reference operator &:





int x, y = 5;
int *ptr;
/*ptr is a POINTER to an integer variable*/
ptr = &y;
/*assign ptr to the MEMORY ADDRESS of y.*/

Dereference operator *:



x = *ptr;
/*assign x to the int that is pointed to by ptr */
Introduction to C: pointer variables
Introduction to C: pointer variables
#include <stdio.h>
//swap two values
void swap(int* iPtrX,int* iPtrY);
void fakeswap(int x, int y);
int main()
{
int x = 10;
int y = 20;
int *p1 = &x;
int *p2 = &y;
printf("before swap: x=%d y=%dn",x,y);
swap(p1,p2);
printf("after swap: x=%d y=%dn",x,y);
printf("------------------------------n");
printf("before fakeswap: x=%d y=%dn",x,y);
fakeswap(x,y);
printf("after fakeswap: x=%d y=%d",x,y);
return 0;
}
void swap(int* iPtrX, int* iPtrY)
{
int temp;
temp = *iPtrX;
*iPtrX = *iPtrY;
*iPtrY = temp;
}
void fakeswap(int x,int y)
{
int temp;
temp = x;
x = y;
y = temp;
}
Introduction to C: struct
#include <stdio.h>
//group things together
struct database {
int id_number;
int age;
float salary;
};
int main()
{
struct database employee;
employee.age = 22;
employee.id_number = 1;
employee.salary = 12000.21;
}
//content in in.list
//foo 70
//bar 98
//biz 100
#include <stdio.h>

mode:
r - open for reading
w - open for writing (file need not exist)
a - open for appending (file need not exist)
r+ - open for reading and writing, start at beginning
w+ - open for reading and writing (overwrite file)
a+ - open for reading and writing (append if file
exists)

int main()
{
FILE *ifp, *ofp;
char *mode = "r";
char outputFilename[] = "out.list";
char username[9];
int score;
ifp = fopen("in.list", mode);
if (ifp == NULL) {
fprintf(stderr, "Can't open input file in.list!n");
exit(1);
}
ofp = fopen(outputFilename, "w");
if (ofp == NULL) {
fprintf(stderr, "Can't open output file %s!n", outputFilename);
exit(1);
}
while (fscanf(ifp, "%s %d", username, &score) == 2) {
fprintf(ofp, "%s %dn", username, score+10);
}
fclose(ifp);
fclose(ofp);
return 0;
}

File I/O

More Related Content

What's hot

C Programming Language Part 11
C Programming Language Part 11C Programming Language Part 11
C Programming Language Part 11
Rumman Ansari
 
C++ Programming - 1st Study
C++ Programming - 1st StudyC++ Programming - 1st Study
C++ Programming - 1st Study
Chris Ohk
 
C Programming Language Part 7
C Programming Language Part 7C Programming Language Part 7
C Programming Language Part 7
Rumman Ansari
 
C Programming Language Step by Step Part 2
C Programming Language Step by Step Part 2C Programming Language Step by Step Part 2
C Programming Language Step by Step Part 2
Rumman Ansari
 
C Programming Language Part 4
C Programming Language Part 4C Programming Language Part 4
C Programming Language Part 4
Rumman Ansari
 
Double linked list
Double linked listDouble linked list
Double linked list
Sayantan Sur
 
2. Базовый синтаксис Java
2. Базовый синтаксис Java2. Базовый синтаксис Java
2. Базовый синтаксис Java
DEVTYPE
 
Programa en C++ ( escriba 3 números y diga cual es el mayor))
Programa en C++ ( escriba 3 números y diga cual es el mayor))Programa en C++ ( escriba 3 números y diga cual es el mayor))
Programa en C++ ( escriba 3 números y diga cual es el mayor))Alex Penso Romero
 
C lab programs
C lab programsC lab programs
C lab programs
Dr. Prashant Vats
 
print even or odd number in c
print even or odd number in cprint even or odd number in c
print even or odd number in c
mohdshanu
 
Activity Recognition Through Complex Event Processing: First Findings
Activity Recognition Through Complex Event Processing: First Findings Activity Recognition Through Complex Event Processing: First Findings
Activity Recognition Through Complex Event Processing: First Findings
Sylvain Hallé
 
โปรแกรมย่อยและฟังชันก์มาตรฐาน
โปรแกรมย่อยและฟังชันก์มาตรฐานโปรแกรมย่อยและฟังชันก์มาตรฐาน
โปรแกรมย่อยและฟังชันก์มาตรฐานknang
 
Blocks+gcd入門
Blocks+gcd入門Blocks+gcd入門
Blocks+gcd入門
領一 和泉田
 
Circular queue
Circular queueCircular queue
Circular queue
ShobhaHiremath8
 

What's hot (19)

C Programming Language Part 11
C Programming Language Part 11C Programming Language Part 11
C Programming Language Part 11
 
C++ Programming - 1st Study
C++ Programming - 1st StudyC++ Programming - 1st Study
C++ Programming - 1st Study
 
C Programming Language Part 7
C Programming Language Part 7C Programming Language Part 7
C Programming Language Part 7
 
Vcs8
Vcs8Vcs8
Vcs8
 
week-16x
week-16xweek-16x
week-16x
 
week-10x
week-10xweek-10x
week-10x
 
C Programming Language Step by Step Part 2
C Programming Language Step by Step Part 2C Programming Language Step by Step Part 2
C Programming Language Step by Step Part 2
 
C Programming Language Part 4
C Programming Language Part 4C Programming Language Part 4
C Programming Language Part 4
 
Double linked list
Double linked listDouble linked list
Double linked list
 
2. Базовый синтаксис Java
2. Базовый синтаксис Java2. Базовый синтаксис Java
2. Базовый синтаксис Java
 
Programa en C++ ( escriba 3 números y diga cual es el mayor))
Programa en C++ ( escriba 3 números y diga cual es el mayor))Programa en C++ ( escriba 3 números y diga cual es el mayor))
Programa en C++ ( escriba 3 números y diga cual es el mayor))
 
C lab programs
C lab programsC lab programs
C lab programs
 
Vcs15
Vcs15Vcs15
Vcs15
 
week-1x
week-1xweek-1x
week-1x
 
print even or odd number in c
print even or odd number in cprint even or odd number in c
print even or odd number in c
 
Activity Recognition Through Complex Event Processing: First Findings
Activity Recognition Through Complex Event Processing: First Findings Activity Recognition Through Complex Event Processing: First Findings
Activity Recognition Through Complex Event Processing: First Findings
 
โปรแกรมย่อยและฟังชันก์มาตรฐาน
โปรแกรมย่อยและฟังชันก์มาตรฐานโปรแกรมย่อยและฟังชันก์มาตรฐาน
โปรแกรมย่อยและฟังชันก์มาตรฐาน
 
Blocks+gcd入門
Blocks+gcd入門Blocks+gcd入門
Blocks+gcd入門
 
Circular queue
Circular queueCircular queue
Circular queue
 

Similar to Intro to c programming

C lab programs
C lab programsC lab programs
C lab programs
Dr. Prashant Vats
 
C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptx
ssuser3cbb4c
 
7 functions
7  functions7  functions
7 functions
MomenMostafa
 
4 operators, expressions &amp; statements
4  operators, expressions &amp; statements4  operators, expressions &amp; statements
4 operators, expressions &amp; statements
MomenMostafa
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorJussi Pohjolainen
 
Cquestions
Cquestions Cquestions
Cquestions
mohamed sikander
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of c
Tushar B Kute
 
9.C Programming
9.C Programming9.C Programming
9.C Programming
Export Promotion Bureau
 
2 data and c
2 data and c2 data and c
2 data and c
MomenMostafa
 
Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4
Ismar Silveira
 
Program flowchart
Program flowchartProgram flowchart
Program flowchart
Sowri Rajan
 
C questions
C questionsC questions
C questions
mohamed sikander
 
C++ Programming - 4th Study
C++ Programming - 4th StudyC++ Programming - 4th Study
C++ Programming - 4th Study
Chris Ohk
 
Pointer basics
Pointer basicsPointer basics
Pointer basics
Mohammed Sikander
 
introduction to c programming and C History.pptx
introduction to c programming and C History.pptxintroduction to c programming and C History.pptx
introduction to c programming and C History.pptx
ManojKhadilkar1
 
深入淺出C語言
深入淺出C語言深入淺出C語言
深入淺出C語言
Simen Li
 
Unit 1- PROGRAMMING IN C OPERATORS LECTURER NOTES
Unit 1- PROGRAMMING IN C OPERATORS LECTURER NOTESUnit 1- PROGRAMMING IN C OPERATORS LECTURER NOTES
Unit 1- PROGRAMMING IN C OPERATORS LECTURER NOTES
LeahRachael
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
kinan keshkeh
 
Programming ppt files (final)
Programming ppt files (final)Programming ppt files (final)
Programming ppt files (final)
yap_raiza
 

Similar to Intro to c programming (20)

C lab programs
C lab programsC lab programs
C lab programs
 
C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptx
 
7 functions
7  functions7  functions
7 functions
 
4 operators, expressions &amp; statements
4  operators, expressions &amp; statements4  operators, expressions &amp; statements
4 operators, expressions &amp; statements
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
 
Cquestions
Cquestions Cquestions
Cquestions
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of c
 
9.C Programming
9.C Programming9.C Programming
9.C Programming
 
2 data and c
2 data and c2 data and c
2 data and c
 
Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4
 
Program flowchart
Program flowchartProgram flowchart
Program flowchart
 
C questions
C questionsC questions
C questions
 
C++ Programming - 4th Study
C++ Programming - 4th StudyC++ Programming - 4th Study
C++ Programming - 4th Study
 
Pointer basics
Pointer basicsPointer basics
Pointer basics
 
introduction to c programming and C History.pptx
introduction to c programming and C History.pptxintroduction to c programming and C History.pptx
introduction to c programming and C History.pptx
 
深入淺出C語言
深入淺出C語言深入淺出C語言
深入淺出C語言
 
Unit 1- PROGRAMMING IN C OPERATORS LECTURER NOTES
Unit 1- PROGRAMMING IN C OPERATORS LECTURER NOTESUnit 1- PROGRAMMING IN C OPERATORS LECTURER NOTES
Unit 1- PROGRAMMING IN C OPERATORS LECTURER NOTES
 
C++ programs
C++ programsC++ programs
C++ programs
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
 
Programming ppt files (final)
Programming ppt files (final)Programming ppt files (final)
Programming ppt files (final)
 

More from Prabhu Govind

Preprocessor in C
Preprocessor in CPreprocessor in C
Preprocessor in C
Prabhu Govind
 
Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in c
Prabhu Govind
 
File in c
File in cFile in c
File in c
Prabhu Govind
 
Pointers in C
Pointers in CPointers in C
Pointers in C
Prabhu Govind
 
Unions in c
Unions in cUnions in c
Unions in c
Prabhu Govind
 
Structure in c
Structure in cStructure in c
Structure in c
Prabhu Govind
 
Array & string
Array & stringArray & string
Array & string
Prabhu Govind
 
Recursive For S-Teacher
Recursive For S-TeacherRecursive For S-Teacher
Recursive For S-Teacher
Prabhu Govind
 
User defined Functions in C
User defined Functions in CUser defined Functions in C
User defined Functions in C
Prabhu Govind
 
Pre defined Functions in C
Pre defined Functions in CPre defined Functions in C
Pre defined Functions in C
Prabhu Govind
 
Looping in C
Looping in CLooping in C
Looping in C
Prabhu Govind
 
Branching in C
Branching in CBranching in C
Branching in C
Prabhu Govind
 
Types of operators in C
Types of operators in CTypes of operators in C
Types of operators in C
Prabhu Govind
 
Operators in C
Operators in COperators in C
Operators in C
Prabhu Govind
 
Statements in C
Statements in CStatements in C
Statements in C
Prabhu Govind
 
Data types in C
Data types in CData types in C
Data types in C
Prabhu Govind
 
Constants in C
Constants in CConstants in C
Constants in C
Prabhu Govind
 
Variables_c
Variables_cVariables_c
Variables_c
Prabhu Govind
 
Tokens_C
Tokens_CTokens_C
Tokens_C
Prabhu Govind
 

More from Prabhu Govind (20)

Preprocessor in C
Preprocessor in CPreprocessor in C
Preprocessor in C
 
Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in c
 
File in c
File in cFile in c
File in c
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Unions in c
Unions in cUnions in c
Unions in c
 
Structure in c
Structure in cStructure in c
Structure in c
 
Array & string
Array & stringArray & string
Array & string
 
Recursive For S-Teacher
Recursive For S-TeacherRecursive For S-Teacher
Recursive For S-Teacher
 
User defined Functions in C
User defined Functions in CUser defined Functions in C
User defined Functions in C
 
Pre defined Functions in C
Pre defined Functions in CPre defined Functions in C
Pre defined Functions in C
 
Looping in C
Looping in CLooping in C
Looping in C
 
Branching in C
Branching in CBranching in C
Branching in C
 
Types of operators in C
Types of operators in CTypes of operators in C
Types of operators in C
 
Operators in C
Operators in COperators in C
Operators in C
 
Statements in C
Statements in CStatements in C
Statements in C
 
Data types in C
Data types in CData types in C
Data types in C
 
Constants in C
Constants in CConstants in C
Constants in C
 
Variables_c
Variables_cVariables_c
Variables_c
 
Tokens_C
Tokens_CTokens_C
Tokens_C
 
Computer basics
Computer basicsComputer basics
Computer basics
 

Recently uploaded

Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 

Recently uploaded (20)

Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 

Intro to c programming

  • 2. Introduction to C         Basics If Statement Loops Functions Switch case Pointers Structures File I/O
  • 3.
  • 4. Introduction to C: Basics //a simple program that has variables #include <stdio.h> int main() { int x; //(32 bits) char y; //(8 bits) float z; //(32 bits) double t; //(64 bits) printf(“hello world…n”); int test; //wrong, The variable declaration must appear first return 0; }
  • 5. Introduction to C: Basics //reading input from console #include <stdio.h> int main() { int num1; int num2; printf( "Please enter two numbers: " ); scanf( "%d %d", &num1,&num2 ); printf( "You entered %d %d", num1, num2 ); return 0; }
  • 6. Introduction to C: if statement #include <stdio.h> int main() { int age; /* Need a variable... */ printf( "Please enter your age" ); /* Asks for age */ scanf( "%d", &age ); /* The input is put in age */ if ( age < 100 ) { /* If the age is less than 100 */ printf ("You are pretty young!n" ); /* Just to show you it works... */ } else if ( age == 100 ) { /* I use else just to show an example */ printf( "You are oldn" ); } else { printf( "You are really oldn" ); /* Executed if no other statement is*/ } return 0; }
  • 7. Introduction to C: Loops(for) #include <stdio.h> int main() { int x; /* The loop goes while x < 10, and x increases by one every loop*/ for ( x = 0; x < 10; x++ ) { /* Keep in mind that the loop condition checks the conditional statement before it loops again. consequently, when x equals 10 the loop breaks. x is updated before the condition is checked. */ printf( "%dn", x ); } return 0; }
  • 8. Introduction to C: Loops(while) #include <stdio.h> int main() { int x = 0; /* Don't forget to declare variables */ while ( x < 10 ) { /* While x is less than 10 */ printf( "%dn", x ); x++; /* Update x so the condition can be met eventually */ } return 0; }
  • 9. Introduction to C: Loops(do while) #include <stdio.h> int main() { int x; x = 0; do { /* "Hello, world!" is printed at least one time even though the condition is false*/ printf( "%dn", x ); x++; } while ( x != 10 ); return 0; }
  • 10. Introduction to C: Loops(break and continue) #include <stdio.h> int main() { int x; for(x=0;x<10;x++) { if(x==5) { break; } printf("%dn",x); } return 0; } 0 1 2 3 4 #include <stdio.h> int main() { int x; for(x=0;x<10;x++) { if(x==5) { continue; } printf("%dn",x); } return 0; } 0 1 2 3 4 6 7 8 9
  • 11. Introduction to C: function #include <stdio.h> //function declaration int mult ( int x, int y ); int main() { int x; int y; printf( "Please input two numbers to be multiplied: " ); scanf( "%d", &x ); scanf( "%d", &y ); printf( "The product of your two numbers is %dn", mult( x, y ) ); return 0; } //define the function body //return value: int //utility: return the multiplication of two integer values //parameters: take two int parameters int mult (int x, int y) { return x * y; }
  • 12. #include <stdio.h> //function declaration, need to define the function body in other places void playgame(); void loadgame(); void playmultiplayer(); int main() { int input; printf( "1. Play gamen" ); printf( "2. Load gamen" ); printf( "3. Play multiplayern" ); printf( "4. Exitn" ); printf( "Selection: " ); scanf( "%d", &input ); switch ( input ) { case 1: /* Note the colon, not a semicolon */ playgame(); break; //don't forget the break in each case case 2: loadgame(); break; case 3: playmultiplayer(); break; case 4: printf( "Thanks for playing!n" ); break; default: printf( "Bad input, quitting!n" ); break; } return 0; } switch case
  • 13. Introduction to C: pointer variables   Pointer variables are variables that store memory addresses. Pointer Declaration:     Reference operator &:    int x, y = 5; int *ptr; /*ptr is a POINTER to an integer variable*/ ptr = &y; /*assign ptr to the MEMORY ADDRESS of y.*/ Dereference operator *:   x = *ptr; /*assign x to the int that is pointed to by ptr */
  • 14. Introduction to C: pointer variables
  • 15. Introduction to C: pointer variables
  • 16. #include <stdio.h> //swap two values void swap(int* iPtrX,int* iPtrY); void fakeswap(int x, int y); int main() { int x = 10; int y = 20; int *p1 = &x; int *p2 = &y; printf("before swap: x=%d y=%dn",x,y); swap(p1,p2); printf("after swap: x=%d y=%dn",x,y); printf("------------------------------n"); printf("before fakeswap: x=%d y=%dn",x,y); fakeswap(x,y); printf("after fakeswap: x=%d y=%d",x,y); return 0; } void swap(int* iPtrX, int* iPtrY) { int temp; temp = *iPtrX; *iPtrX = *iPtrY; *iPtrY = temp; } void fakeswap(int x,int y) { int temp; temp = x; x = y; y = temp; }
  • 17. Introduction to C: struct #include <stdio.h> //group things together struct database { int id_number; int age; float salary; }; int main() { struct database employee; employee.age = 22; employee.id_number = 1; employee.salary = 12000.21; }
  • 18. //content in in.list //foo 70 //bar 98 //biz 100 #include <stdio.h> mode: r - open for reading w - open for writing (file need not exist) a - open for appending (file need not exist) r+ - open for reading and writing, start at beginning w+ - open for reading and writing (overwrite file) a+ - open for reading and writing (append if file exists) int main() { FILE *ifp, *ofp; char *mode = "r"; char outputFilename[] = "out.list"; char username[9]; int score; ifp = fopen("in.list", mode); if (ifp == NULL) { fprintf(stderr, "Can't open input file in.list!n"); exit(1); } ofp = fopen(outputFilename, "w"); if (ofp == NULL) { fprintf(stderr, "Can't open output file %s!n", outputFilename); exit(1); } while (fscanf(ifp, "%s %d", username, &score) == 2) { fprintf(ofp, "%s %dn", username, score+10); } fclose(ifp); fclose(ofp); return 0; } File I/O