<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-7720722570285165075</id><updated>2026-04-13T16:56:22.802+10:00</updated><category term="C source code"/><category term="Mini projects"/><category term="OpenGL graphics"/><category term="Cpp source code"/><category term="Modern OpenGL"/><category term="GLFW graphics"/><category term="C on Linux"/><category term="GTK"/><category term="WinBGI graphics"/><category term="Image processing"/><category term="OpenCV"/><category term="Others"/><category term="SDL graphics"/><category term="Shell programming"/><category term="Visual Cpp"/><category term="wxWidget"/><title type='text'>Code in code::blocks</title><subtitle type='html'>Download Mini project in c,c++,c# ,OpenGL,GLUT,GLFW,windows form application  source code</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://www.codeincodeblock.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default?redirect=false'/><link rel='alternate' type='text/html' href='http://www.codeincodeblock.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><link rel='next' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default?start-index=26&amp;max-results=25&amp;redirect=false'/><author><name>Dinesh Subedi</name><uri>http://www.blogger.com/profile/15921581026092958477</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfxMED05n-0aBIoi4kgT-8kSHfpuRf1bFosaVy-JI-vEwMtJr0sNUFF4S2oj2axSo9IfljCyuPc4hieJ0HsUEPnmw7-8Rj6UTcQjG0Mwv0tiPhTTz6ginzbCdi48YU2oQ/s151/CIMG5697.JPG'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>91</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-7720722570285165075.post-843100201611518379</id><published>2025-03-30T21:26:00.006+11:00</published><updated>2025-04-20T22:36:45.476+10:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C source code"/><category scheme="http://www.blogger.com/atom/ns#" term="Mini projects"/><title type='text'>Develop Tetris Game in C programming Without Graphics Library and Full Source Code</title><content type='html'>&lt;p style=&quot;text-align: justify;&quot;&gt;Tetrix game is created in C programming without using graphic library. We draw shapes only using # character and game is played on command window. User can play game using up, left, right, and down arrow key. The up key rotate Tetrimino (Shapes) in clockwise direction, left key move Tetrimino (Shapes) in left direction toward negative x-axis, right key move Tetrimino (Shapes) in right direction toward positive x-axis, and down key rotate Tetrimino (Shapes) in anticlockwise direction. By default, Tetrimino (Shapes) will move 1 unit downward toward negative y-axis in each frame of the game.&amp;nbsp; The score is calculated based on the number of rows filled with boxes.&amp;nbsp;&lt;/p&gt;&lt;p style=&quot;text-align: justify;&quot;&gt;The main objective of this project is to provide knowledge and technique about creating Tetris game in C programming, provide basic knowledge of linear algebra to rotate and translate shapes. User can use any graphics library to draw window, and shapes to make it similar to commercial games. However, the algorithm of the game is same in all Tetris game available in market.&amp;nbsp;&amp;nbsp;&lt;/p&gt;&lt;p&gt;In this article, I will explain the following items:&lt;/p&gt;&lt;p&gt;&lt;/p&gt;&lt;ul style=&quot;text-align: left;&quot;&gt;&lt;li&gt;Coordinate system of the game&lt;/li&gt;&lt;li&gt;Usage of linear algebra to rotate and translate shapes.&lt;/li&gt;&lt;li&gt;Data Structure used in the game&lt;/li&gt;&lt;li&gt;Collision detection and score checking Techniques&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;&lt;/p&gt;&lt;p&gt;&lt;br /&gt;&lt;/p&gt;&lt;p&gt;Also, Download the final version of the game &lt;a href=&quot;https://github.com/smokindinesh/Mini-Project-in-C/tree/master/Tetris&quot; target=&quot;_blank&quot;&gt;Download Project from GitHub&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;I have explained the game in following two articles:&lt;/p&gt;&lt;p&gt;&lt;a href=&quot;https://www.codeincodeblock.com/2025/03/part-1-teris-game-in-c-programming.html&quot; target=&quot;_blank&quot;&gt;Part 1: Tetriminos (Shapes), Coordinate System, Rotation and Translate&lt;/a&gt;&lt;/p&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;iframe allowfullscreen=&quot;&quot; class=&quot;BLOG_video_class&quot; height=&quot;266&quot; src=&quot;https://www.youtube.com/embed/RSWzkJUrLTw&quot; width=&quot;320&quot; youtube-src-id=&quot;RSWzkJUrLTw&quot;&gt;&lt;/iframe&gt;&lt;/div&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;&lt;/p&gt;&lt;p&gt;&lt;a href=&quot;https://www.codeincodeblock.com/2025/03/part-2-teris-game-in-c-programming-data.html&quot; target=&quot;_blank&quot;&gt;Part 2: Data Structure, Collision detection and Score checking Techniques&lt;/a&gt;&lt;/p&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;iframe allowfullscreen=&quot;&quot; class=&quot;BLOG_video_class&quot; height=&quot;266&quot; src=&quot;https://www.youtube.com/embed/tktCcjjfEfk&quot; width=&quot;320&quot; youtube-src-id=&quot;tktCcjjfEfk&quot;&gt;&lt;/iframe&gt;&lt;/div&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.codeincodeblock.com/feeds/843100201611518379/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.codeincodeblock.com/2025/03/develop-tetris-game-in-c-programming.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/843100201611518379'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/843100201611518379'/><link rel='alternate' type='text/html' href='http://www.codeincodeblock.com/2025/03/develop-tetris-game-in-c-programming.html' title='Develop Tetris Game in C programming Without Graphics Library and Full Source Code'/><author><name>Dinesh Subedi</name><uri>http://www.blogger.com/profile/15921581026092958477</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfxMED05n-0aBIoi4kgT-8kSHfpuRf1bFosaVy-JI-vEwMtJr0sNUFF4S2oj2axSo9IfljCyuPc4hieJ0HsUEPnmw7-8Rj6UTcQjG0Mwv0tiPhTTz6ginzbCdi48YU2oQ/s151/CIMG5697.JPG'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://img.youtube.com/vi/RSWzkJUrLTw/default.jpg" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7720722570285165075.post-5348748019556633503</id><published>2025-03-30T21:23:00.007+11:00</published><updated>2025-04-20T22:38:26.969+10:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C source code"/><category scheme="http://www.blogger.com/atom/ns#" term="Mini projects"/><title type='text'>Part 2: Tetris Game in C programming | Data Structure, Collision detection and Score checking Techniques</title><content type='html'>&lt;p style=&quot;text-align: left;&quot;&gt;&lt;a href=&quot;https://www.codeincodeblock.com/2025/03/part-1-teris-game-in-c-programming.html&quot;&gt;Previous Page&lt;/a&gt;&amp;nbsp;&lt;/p&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;iframe allowfullscreen=&quot;&quot; class=&quot;BLOG_video_class&quot; height=&quot;266&quot; src=&quot;https://www.youtube.com/embed/tktCcjjfEfk&quot; width=&quot;320&quot; youtube-src-id=&quot;tktCcjjfEfk&quot;&gt;&lt;/iframe&gt;&lt;/div&gt;&lt;br /&gt;&lt;h2 style=&quot;text-align: left;&quot;&gt;&lt;br /&gt;&lt;/h2&gt;&lt;h2 style=&quot;text-align: left;&quot;&gt;Data Structure&lt;/h2&gt;&lt;div&gt;&lt;div&gt;This is a 2D game where the primary object is a box. A combination of 4 boxes forms a Tetrimino (shape). Boxes are arranged on the Tetris board from the bottom upward.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Board Specifications&lt;/div&gt;&lt;div&gt;&lt;ul style=&quot;text-align: left;&quot;&gt;&lt;li&gt;The Tetris board has a size of 11 columns (x-axis) by 21 rows (y-axis).&lt;/li&gt;&lt;li&gt;Tetriminos are arranged on the board such that if an entire row is filled with boxes, the player earns points.&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;&lt;div&gt;Box Representation&lt;/div&gt;&lt;div&gt;&lt;ul style=&quot;text-align: left;&quot;&gt;&lt;li&gt;Each box is defined by 2D (x, y) coordinates, which determine where it is drawn.&lt;/li&gt;&lt;li&gt;To represent boxes and Tetriminos (shapes), the game uses three structure variables:&lt;/li&gt;&lt;ul&gt;&lt;li&gt;Point2D&lt;/li&gt;&lt;li&gt;Tetriminos&lt;/li&gt;&lt;li&gt;TetrisBox&lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt;&lt;/div&gt;&lt;/div&gt;&lt;span&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;/span&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;pre class=&quot;prettyprint&quot; style=&quot;text-align: left;&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
//Structure definition of x,y coordinate
struct Point2D {
    int x;
    int y;
};

//Structure definition to define each game board boxes
struct Tetriminos {
    struct Point2D body[4];
};

//Structure definition of individual Tetris Box
//Added on the Tetris board.
struct TetrisBox {
    struct Point2D box;
    int flag_T;
};

//Store four corner of the Tetris board
struct Point2D window[4];
//Store 7 shapes (Tetrimino)
struct Tetriminos tetrimino[7];

//Current Tetris shapes
struct Tetriminos current_T;

//Next Tetris shapes
struct Tetriminos next_T;

//Declare all box 11 * 21 = 231 within Tetris board
//double array matrix is created to represent board vertical boxes
//and horizontal boxes. The flag is to identify occupied box.
struct TetrisBox tetrisBoard[board_index_i_y][board_index_j_x];&lt;/code&gt;&lt;/pre&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;The Point2D has two integer variables x, and y to represent x, and y coordinates. Tetriminos structure has only one body array of size 4 Struct Point2D variable to represent Tetrimino (Shapes).&amp;nbsp;&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;The structure definition TetrisBox represent only one box added on the board. The struct Point2D box variable store the coordinates and int flag_T variable represent it is filled by Tetrimino. The flag_T = 0 means box is not filled, flag_T = 1 means box is filled by Tetrimion. If any Terimino is added on the board then it will fill the box. So, after collision we will compare the coordinates of Tetrimino and boxes of the board, if both equal then we will set flag_T to 1. This technique is also used to check collision with boxes.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;There are other variables such as struct Point2D currTranslateVec to represent translate vector, struct Point2D unitVec[4] to represent 4 units vectors toward positive and negative x and y axis, and struct Point2D currRotationVec[2] represent rotation vector clockwise and anticlockwise.&lt;/div&gt;&lt;pre class=&quot;prettyprint&quot; style=&quot;text-align: left;&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
//Current Translate vector
struct Point2D currTranslateVec = {0,11};

//Unit vector toward  x-axis and y-axis both positive and negative
//0= + y-axis, 1 = - y-axis, 2 = + x-axis, and 3 = - x-axis
struct Point2D unitVec[4] = {{0,1},{0,-1},{1,0},{-1,0}};

//Clockwise rotation vector, 0 = clockwise, 1 = anti-clock wise
struct Point2D currRotationVec[2] = {{1,-1},{-1,1}};

//Index to indicate direction of unit vector
int unitVecDir = 1;

//Variable to calculate score
int score=0;
&lt;/code&gt;&lt;/pre&gt;&lt;h2 style=&quot;text-align: left;&quot;&gt;Collision detection&lt;/h2&gt;&lt;div&gt;I have implemented collision detection based on following rules.&lt;/div&gt;&lt;div style=&quot;text-align: left;&quot;&gt;&lt;ul style=&quot;text-align: left;&quot;&gt;&lt;li&gt;Tetrimino reach bottom of the board -&amp;gt; Add it in Tetris board.&lt;/li&gt;&lt;li&gt;Tetrimino collided with box while moving toward negative y-axis (downward) -&amp;gt; Add it in Tetris board.&lt;/li&gt;&lt;li&gt;Tetrimino collided with box while moving toward negative or positive x-axis -&amp;gt; Do not add it in board but stop moving further toward x-axis.&lt;/li&gt;&lt;li&gt;Tetrimino moving outside the board (out of window) -&amp;gt; Stop moving further toward x-axis.&lt;/li&gt;&lt;li&gt;Tetrimino collided with box but one or all boxes are outside of the window (positive y-axis) -&amp;gt; Game over&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;&lt;h2 style=&quot;text-align: left;&quot;&gt;Scoring Techniques&lt;/h2&gt;&lt;div&gt;Player will score if player able to arrange boxes in a row completely. We will scan the value of flag_T of the boxes along row to check scoring. We have defined Tetris board by two-dimension array struct TetrisBox tetrisBoard[board_index_i_y][board_index_j_x].&amp;nbsp; First index is number of rows toward y-axis and second index is number of columns.&amp;nbsp; So, for each row we will multiply the value of flag_T, if value equal to 1 then it means that row is filled by boxes and player will win 10 points. As you know, if box is not filled the value of flag_T is 0. Any of the box in a row is empty then total product of flag_T will be 0.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;When player win the points after filing all boxes in a row, we have to delete that row. To achieve this, I have implemented following logic.&lt;/div&gt;&lt;div&gt;&lt;ol style=&quot;text-align: left;&quot;&gt;&lt;li&gt;Add boxes from higher index i.e bottom of the board which is represented by board_index_i_y variable. Its value is up to 20 to represent all 21 rows of the board. The value 0 represents top row and 20 represent bottom row.&lt;/li&gt;&lt;li style=&quot;text-align: justify;&quot;&gt;Check the product of the value of flag_T from bottom row. If value is 1 increase the score and unset the value of flag_T to 0. Shift the value of flag_T from top rows to one step down starting from that index. Again, start checking product from same index, and repeat this step until you reach top row.&lt;/li&gt;&lt;/ol&gt;&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;This is the end of the article. I hope you understood the coordinate system, data structure, collision detection techniques and scoring techniques used in this game. Please don&#39;t forget to download source code from the link provided in main page of this project, also do not forget to watch video. In video I have explain the source code in detail.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.codeincodeblock.com/feeds/5348748019556633503/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.codeincodeblock.com/2025/03/part-2-teris-game-in-c-programming-data.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/5348748019556633503'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/5348748019556633503'/><link rel='alternate' type='text/html' href='http://www.codeincodeblock.com/2025/03/part-2-teris-game-in-c-programming-data.html' title='Part 2: Tetris Game in C programming | Data Structure, Collision detection and Score checking Techniques'/><author><name>Dinesh Subedi</name><uri>http://www.blogger.com/profile/15921581026092958477</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfxMED05n-0aBIoi4kgT-8kSHfpuRf1bFosaVy-JI-vEwMtJr0sNUFF4S2oj2axSo9IfljCyuPc4hieJ0HsUEPnmw7-8Rj6UTcQjG0Mwv0tiPhTTz6ginzbCdi48YU2oQ/s151/CIMG5697.JPG'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://img.youtube.com/vi/tktCcjjfEfk/default.jpg" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7720722570285165075.post-8876930898698965084</id><published>2025-03-30T21:13:00.007+11:00</published><updated>2025-04-20T22:38:06.441+10:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C source code"/><category scheme="http://www.blogger.com/atom/ns#" term="Mini projects"/><title type='text'>Part 1: Tetris Game in C programming | Tetriminos (Shapes), Coordinate System, Rotation and Translation of Tetriminos (Shapes)</title><content type='html'>&lt;p style=&quot;text-align: left;&quot;&gt;&lt;a href=&quot;https://www.codeincodeblock.com/2025/03/develop-tetris-game-in-c-programming.html&quot;&gt;Previous Page&lt;/a&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;a href=&quot;https://www.codeincodeblock.com/2025/03/part-2-teris-game-in-c-programming-data.html&quot;&gt;Next Page&lt;/a&gt;&lt;/p&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;iframe allowfullscreen=&quot;&quot; class=&quot;BLOG_video_class&quot; height=&quot;266&quot; src=&quot;https://www.youtube.com/embed/RSWzkJUrLTw&quot; width=&quot;320&quot; youtube-src-id=&quot;RSWzkJUrLTw&quot;&gt;&lt;/iframe&gt;&lt;/div&gt;&lt;br /&gt;&lt;p style=&quot;text-align: left;&quot;&gt;&lt;br /&gt;&lt;/p&gt;&lt;h2 style=&quot;text-align: left;&quot;&gt;Tetriminos (Shapes)&lt;/h2&gt;&lt;p style=&quot;text-align: justify;&quot;&gt;In this Tetris game, I use 7 shapes. While some versions only include 5 shapes, I’ve added two extra ones: the J and S shapes, which are mirror opposites of the L and Z shapes, respectively.&lt;/p&gt;&lt;p style=&quot;text-align: justify;&quot;&gt;Each shape consists of 4 blocks, and each block is called a Mino (short for monomino). A group of 4 Minos forms a Tetrimino (also known as Tetromino or Tetramino). For consistency, I’ll use the term Tetrimino throughout this article.&lt;/p&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh81VYxDCvUhGMsOvdG9AmRV12hbJAU5TFq7IR0JXRRJ5EF9QcTD5mTgJQ95_axSHUayWIfzIzyk9Ei1l4BZ9_Rgu2yDXnNi3iaRi5UlYOuFJNcfKhNMsycQEuTGbULZlLFksgx4Eu2SCylD1lwQt3EDNTrW8rYsrZIeYffDoznw6ZCanLC5QGu_MTm4SM/s613/Shapes.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;310&quot; data-original-width=&quot;613&quot; height=&quot;203&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh81VYxDCvUhGMsOvdG9AmRV12hbJAU5TFq7IR0JXRRJ5EF9QcTD5mTgJQ95_axSHUayWIfzIzyk9Ei1l4BZ9_Rgu2yDXnNi3iaRi5UlYOuFJNcfKhNMsycQEuTGbULZlLFksgx4Eu2SCylD1lwQt3EDNTrW8rYsrZIeYffDoznw6ZCanLC5QGu_MTm4SM/w400-h203/Shapes.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;h2 style=&quot;text-align: left;&quot;&gt;Coordinate System&lt;/h2&gt;&lt;div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;To simplify game development, I’ve designed a gotoxy(x, y) function that relocates the coordinate system’s origin (0, 0) from the default top-left corner of the command window to a more convenient central position at (36, 12).&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;How It Works:&lt;/div&gt;&lt;div&gt;&lt;ol style=&quot;text-align: left;&quot;&gt;&lt;li&gt;Coordinate Transformation:&lt;/li&gt;&lt;/ol&gt;&lt;ul style=&quot;text-align: left;&quot;&gt;&lt;ul&gt;&lt;li&gt;The function offsets input coordinates:&lt;/li&gt;&lt;ul&gt;&lt;li&gt;x becomes x + 36&lt;/li&gt;&lt;li&gt;y becomes y - 12&lt;/li&gt;&lt;/ul&gt;&lt;li&gt;This allows negative coordinates (e.g., (-36, 12) maps to the original (0, 0)).&lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt;&lt;ol style=&quot;text-align: left;&quot;&gt;&lt;li&gt;Purpose:&lt;/li&gt;&lt;ul&gt;&lt;li&gt;Centering (0, 0) simplifies calculations for symmetric gameplay elements (e.g., rotating Tetriminos around the origin).&lt;/li&gt;&lt;li&gt;Negative coordinates enable intuitive positioning relative to the new origin.&lt;/li&gt;&lt;/ul&gt;&lt;/ol&gt;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;span&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;/span&gt;The final coordinate system of the game is represented on below image.&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjgRqY1lCvFTPbvjDZLGBm-tSqO3n4kkFWmQVVkZBJ9AEJjWUrqYffcY6ToeCbETb9eOHcC9jOOaGFlO3PsAAwQxAPkJ1URYhm8YLG4GbhFtkSZrQuAxTc3_-TkAVW4y4xGt32Uq-71Fn9l242Hm4LdsVIX66-SWdmeJ0jZ963TU1i-hCck-THCGMprUPQ/s857/CoordinateSystem.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;857&quot; data-original-width=&quot;810&quot; height=&quot;640&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjgRqY1lCvFTPbvjDZLGBm-tSqO3n4kkFWmQVVkZBJ9AEJjWUrqYffcY6ToeCbETb9eOHcC9jOOaGFlO3PsAAwQxAPkJ1URYhm8YLG4GbhFtkSZrQuAxTc3_-TkAVW4y4xGt32Uq-71Fn9l242Hm4LdsVIX66-SWdmeJ0jZ963TU1i-hCck-THCGMprUPQ/w605-h640/CoordinateSystem.png&quot; width=&quot;605&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;br /&gt;&lt;/div&gt;Tetris game board spans 11 units along x-axis (width) and 21 units along the y-axis (height). The center coordinate is (0,0) so the coordinates of four corner of the Tetris board are (5, 10), (5, -10), (-5, -10), and (-5, 10).&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;h2 style=&quot;text-align: left;&quot;&gt;Rotation and Translation&lt;/h2&gt;&lt;div&gt;To rotate and translate Tetrimino, we must use linear algebra. This is 2D game and we rotate Tetrimino only by 90 degrees clockwise or anticlockwise. So, the final formula of rotation and translation will be simple.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Translation formula is:&lt;/div&gt;&lt;blockquote&gt;&lt;div&gt;v = (x, y) , T = (x&#39;, y&#39;) then v&#39; = v + T = (x + x&#39;, y + y&#39;)&lt;/div&gt;&lt;/blockquote&gt;&lt;blockquote&gt;&lt;p&gt;so, v = (0,0) T = (0, 12) move to v&#39; = (0+0, 0+12) = (0,12)&lt;/p&gt;&lt;/blockquote&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Rotation formula by center of axis is:&lt;/div&gt;&lt;/div&gt;&lt;blockquote&gt;&lt;div&gt;v = (x, y), R = (cos Φ - sin Φ, sin Φ + cos Φ) then v&#39; = R . v&lt;/div&gt;&lt;/blockquote&gt;&lt;blockquote&gt;&lt;div&gt;&amp;nbsp;v&#39; = (x cos Φ - y sin Φ, x sin Φ + y cos Φ)&lt;/div&gt;&lt;/blockquote&gt;&lt;p&gt;we rotate Tetrimino only by 90 degrees so cos Φ = 0, and sin Φ = -1 so final rotation vector is&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;v&#39; = (y * -1, x * 1), anticlockwise&lt;/p&gt;&lt;/blockquote&gt;&lt;blockquote&gt;&lt;p&gt;v&#39; = (y * 1, x * -1), clockwise&lt;/p&gt;&lt;/blockquote&gt;&lt;blockquote&gt;&lt;p&gt;so (2,3), clockwise rotation is (3*1, 2*-1) = (3, -2)&lt;/p&gt;&lt;/blockquote&gt;&lt;blockquote&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;/blockquote&gt;&lt;p style=&quot;text-align: justify;&quot;&gt;Let&#39;s take a line shape Tetrimino as an example and discuss how we have implemented in game.&lt;/p&gt;&lt;p style=&quot;text-align: justify;&quot;&gt;We always draw Tetrimino at the center of axis so that while rotating it will rotate by its own center of body. Initial coordinates of line are (0, 2), (0, 1), (0, 0), and (0, -1).&lt;/p&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhPNhXSp4Y4YTbVE1iI8he3sHk1DVWYKsDumJZwSTPcSFiJZfefTFyOTrFmYFWbp9DQwM99fCmsRIBcf92k7P1C8EtJ8lVJedyzXj0KWQe_Sx6D5OZLzbCuAwnhV8oGLBbyLIqaedIa3RjAPnYwDw-MV2JRxu9KaI0THfuFgyyHwegBSViEcqHWBKlycXA/s855/CoordinateSystemLine.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;855&quot; data-original-width=&quot;807&quot; height=&quot;640&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhPNhXSp4Y4YTbVE1iI8he3sHk1DVWYKsDumJZwSTPcSFiJZfefTFyOTrFmYFWbp9DQwM99fCmsRIBcf92k7P1C8EtJ8lVJedyzXj0KWQe_Sx6D5OZLzbCuAwnhV8oGLBbyLIqaedIa3RjAPnYwDw-MV2JRxu9KaI0THfuFgyyHwegBSViEcqHWBKlycXA/w604-h640/CoordinateSystemLine.png&quot; width=&quot;604&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;p&gt;Coordinates after clockwise rotation are (-1,0), (0, 0), (1, 0), and (2, 0).&lt;/p&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfbwXi7CVpj3XqhV4uHmDve6XLmwjRxMHVstwGiQC3dSxzZ8YgvjMXQBG7Ic3ntv3YaZFUNsx7kAMafEJFpt4l1HvoBBbquLh4GJlILPt2AUwNok9eVUJRIGxPRYmTQau59g9H7QEe0iLlg_6f7mhQiAK3sRVHs74_HBghx_QKyxWqrhM-ouOe7ox0bQY/s855/CoordinateSystemLineRotate.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;855&quot; data-original-width=&quot;791&quot; height=&quot;640&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfbwXi7CVpj3XqhV4uHmDve6XLmwjRxMHVstwGiQC3dSxzZ8YgvjMXQBG7Ic3ntv3YaZFUNsx7kAMafEJFpt4l1HvoBBbquLh4GJlILPt2AUwNok9eVUJRIGxPRYmTQau59g9H7QEe0iLlg_6f7mhQiAK3sRVHs74_HBghx_QKyxWqrhM-ouOe7ox0bQY/w592-h640/CoordinateSystemLineRotate.png&quot; width=&quot;592&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;p&gt;Coordinates after translating by (-3, 7) are (-4,7), (-3, 7), (-2, 7), and (-1, 7).&lt;/p&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhjbMILimuNdGYOevym16wQ2Osngssq4HraJ2clvoU190Jle3ot3St5fishlg1-B_J1MJfIlChiPJ0ML25IngB9Z_YzbKPNlFIahey_u0ysUfdajOQiOX6E903OSpOUDvL_eQDHoJ2JrBY6kioAz0JmT_cRoKuyqJAB-9XFef87-LIWScscGnpC5l_xSSQ/s848/CoordinateSystemLineTranslate.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;848&quot; data-original-width=&quot;760&quot; height=&quot;640&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhjbMILimuNdGYOevym16wQ2Osngssq4HraJ2clvoU190Jle3ot3St5fishlg1-B_J1MJfIlChiPJ0ML25IngB9Z_YzbKPNlFIahey_u0ysUfdajOQiOX6E903OSpOUDvL_eQDHoJ2JrBY6kioAz0JmT_cRoKuyqJAB-9XFef87-LIWScscGnpC5l_xSSQ/w574-h640/CoordinateSystemLineTranslate.png&quot; width=&quot;574&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.codeincodeblock.com/feeds/8876930898698965084/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.codeincodeblock.com/2025/03/part-1-teris-game-in-c-programming.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/8876930898698965084'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/8876930898698965084'/><link rel='alternate' type='text/html' href='http://www.codeincodeblock.com/2025/03/part-1-teris-game-in-c-programming.html' title='Part 1: Tetris Game in C programming | Tetriminos (Shapes), Coordinate System, Rotation and Translation of Tetriminos (Shapes)'/><author><name>Dinesh Subedi</name><uri>http://www.blogger.com/profile/15921581026092958477</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfxMED05n-0aBIoi4kgT-8kSHfpuRf1bFosaVy-JI-vEwMtJr0sNUFF4S2oj2axSo9IfljCyuPc4hieJ0HsUEPnmw7-8Rj6UTcQjG0Mwv0tiPhTTz6ginzbCdi48YU2oQ/s151/CIMG5697.JPG'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://img.youtube.com/vi/RSWzkJUrLTw/default.jpg" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7720722570285165075.post-8333544803420912314</id><published>2025-02-02T10:42:00.008+11:00</published><updated>2025-03-31T19:00:13.255+11:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C source code"/><category scheme="http://www.blogger.com/atom/ns#" term="Mini projects"/><title type='text'>Part 2: Tic Tac Toe game in C programing | Source Code explanation</title><content type='html'>&lt;p&gt;&lt;a href=&quot;https://www.codeincodeblock.com/2025/02/part-1-tic-tac-toe-game-in-c-programing.html&quot; target=&quot;_blank&quot;&gt;Previous Page&lt;/a&gt;&lt;/p&gt;&lt;p&gt;&lt;span style=&quot;text-align: justify;&quot;&gt;Watch this tutorial in YouTube.&lt;/span&gt;&lt;/p&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;iframe allowfullscreen=&quot;&quot; class=&quot;BLOG_video_class&quot; height=&quot;266&quot; src=&quot;https://www.youtube.com/embed/KnUvd3zjG9U&quot; width=&quot;320&quot; youtube-src-id=&quot;KnUvd3zjG9U&quot;&gt;&lt;/iframe&gt;&lt;/div&gt;&lt;br /&gt;&lt;p&gt;In this article, we will discuss the following main topics. I encourage you to watch YouTube video to understand the source code in detail.&lt;/p&gt;&lt;p&gt;&lt;/p&gt;&lt;ul style=&quot;text-align: left;&quot;&gt;&lt;li&gt;Technique to switch players.&lt;/li&gt;&lt;li&gt;Logic to check winner player.&lt;/li&gt;&lt;li&gt;Calculate computer player best move.&lt;/li&gt;&lt;/ul&gt;&lt;h3 style=&quot;text-align: left;&quot;&gt;Technique to switch players&lt;/h3&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;I have assigned the value 0 to the first player and the value 1 to the second player, regardless of who plays first. If the human chooses to play first, the value 0 is assigned to the human variable, and the value 1 is assigned to the computer variable, and vice versa. Throughout the project, the system checks the current player against the human or computer variable to determine the player type. The first player always uses &quot;X,&quot; while the second player uses &quot;O.&quot; However, the value assigned to a box depends on the player type: the value of a box chosen by the human is 3, and the value of a box chosen by the computer is 5.&lt;span&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;/span&gt;&lt;/div&gt;&lt;pre class=&quot;prettyprint&quot; style=&quot;text-align: left;&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;#define firstPlayer 0 //Flag for first player
#define secondPlayer 1 //Flag for second player
int human,computer; //Variable to identify human or computer

//code to initialize player
void initGame(int choice){

    initBoard();
    if(choice == 1){
        human = firstPlayer;
        computer = secondPlayer;
    } else if(choice == 2){
        human = secondPlayer;
        computer = firstPlayer;
    }
    initPlayer(firstPlayer,secondPlayer);
    //getch();
}&lt;/code&gt;&lt;/pre&gt;&lt;h3 style=&quot;text-align: left;&quot;&gt;Logic to check winner player&lt;/h3&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;As you know, the value 3 is assigned to a box chosen by the human player, and the value 5 is assigned to a box chosen by the computer. To determine the winner, we will check the sum of the values of the boxes. If the total sum of a row, column, or diagonal is 9, the human player wins the game. Conversely, if the total sum is 15, the computer wins the game. We will calculate the sum of the values for each row, column, and both diagonals individually and compare the results to identify the winner.&lt;/div&gt;&lt;pre class=&quot;prettyprint&quot; style=&quot;text-align: left;&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
//This function check the winner
int checkWinner(){

    int total=0;

    //Check Column
    for(int i=0;i&amp;lt;3;i++){
        total = box[i].value + box[i + 3].value + box[i + 6].value;
        if (total == 9 || total == 15)
            return 1;
    }

    //Check rows
    for(int i=0;i&amp;lt;9;i=i+3){
        total = box[i].value + box[i + 1].value + box[i + 2].value;
        if (total == 9 || total == 15)
            return 1;
    }

    //Check first diagonal of the board
    total = box[0].value + box[4].value + box[8].value;

    if(total == 9 || total == 15)
        return 1;

    //Check second diagonal of the board
    total = box[2].value + box[4].value + box[6].value;

    if(total == 9 || total == 15)
        return 1;

    return 0;
}
&lt;/code&gt;&lt;/pre&gt;&lt;h3 style=&quot;text-align: left;&quot;&gt;Calculate computer&#39;s next best move&lt;/h3&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;We have already discussed the algorithm for the computer player to determine its next move. I have implemented this algorithm exactly as described in the source code. The computer player prioritizes selecting a winning position first. If a winning position is not available, it chooses a position that results in a draw. If neither a winning nor a draw position is available, the computer selects the next best move from a set of predefined steps.&lt;/div&gt;&lt;pre class=&quot;prettyprint&quot; style=&quot;text-align: left;&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;//This function check the winner
int checkWinner(){

    int total=0;

    //Check Column
    for(int i=0;i&amp;lt;3;i++){
        total = box[i].value + box[i + 3].value + box[i + 6].value;
        if (total == 9 || total == 15)
            return 1;
    }

    //Check rows
    for(int i=0;i&amp;lt;9;i=i+3){
        total = box[i].value + box[i + 1].value + box[i + 2].value;
        if (total == 9 || total == 15)
            return 1;
    }

    //Check first diagonal of the board
    total = box[0].value + box[4].value + box[8].value;

    if(total == 9 || total == 15)
        return 1;

    //Check second diagonal of the board
    total = box[2].value + box[4].value + box[6].value;

    if(total == 9 || total == 15)
        return 1;

    return 0;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;pre class=&quot;prettyprint&quot; style=&quot;text-align: left;&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
//This function will return game winning move 
//or game draw move based on prameters
//flag == 0, winning move
//flag == 1, draw move
int getWinDrawMove(int flag){

    int total=-1;

    if(flag==0){
        total=10;
    } else if(flag==1){
        total=6;
    }

    //Check Column
    for(int i=0;i&amp;lt;3;i++){
        if (total==(box[i].value+box[i + 3].value+box[i + 6].value)){
            if(box[i].value==0)
                return i;
            else if (box[i + 3].value==0)
                return i+3;
            else if (box[i + 6].value==0)
                return i+6;
        }
    }

    //Check rows
    for(int i=0;i&amp;lt;9;i=i+3){
        if ((box[i].value+box[i + 1].value+box[i + 2].value)==total){
            if(box[i].value==0)
                return i;
            else if (box[i+1].value==0)
                return i+1;
            else if (box[i+2].value==0)
                return i+2;
        }
    }
    //Check first diagonal of the board
    if((box[0].value+box[4].value+box[8].value) == total){
        if(box[0].value==0)
            return 0;
        else if (box[4].value==0)
            return 4;
        else
            return 8;
    }
    //Check second diagonal of the board
    if((box[2].value+box[4].value+box[6].value) == total){
        if(box[2].value==0)
            return 2;
        else if (box[4].value==0)
            return 4;
        else
            return 6;
    }

    return -1;
}

//Get location of boxes 5,2,4,6,8 respectively
int getMake2()
{
    if(box[4].value == 0)
        return 4;
    if(box[1].value == 0)
        return 1;
    if(box[3].value == 0)
        return 3;
    if(box[5].value == 0)
        return 5;
    if(box[7].value == 0)
        return 7;

    return -1;
}

//Get location of boxes 1,3,7,9 respectively
int getMake4()
{
    if(box[0].value == 0)
        return 0;
    if(box[2].value == 0)
        return 2;
    if(box[6].value == 0)
        return 6;
    if(box[8].value == 0)
        return 8;

    return -1;
}

//This function return best next move for computer player
int getNextMove(){

    int boxNum;


    if(p.numOfTurn &amp;gt;= 3){
        //Get winning position
        boxNum = getWinDrawMove(1);
        if(boxNum!=-1)
            return boxNum;

        //Get Draw position
        boxNum = getWinDrawMove(0);
        if(boxNum!=-1)
            return boxNum;
    }

    boxNum = getMake2();
    if(boxNum!=-1)
        return boxNum;

    boxNum = getMake4();
    if(boxNum!=-1)
        return boxNum;

    return -1;
}
 
&lt;/code&gt;&lt;/pre&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.codeincodeblock.com/feeds/8333544803420912314/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.codeincodeblock.com/2025/02/part-2-tic-tac-toe-game-in-c-programing.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/8333544803420912314'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/8333544803420912314'/><link rel='alternate' type='text/html' href='http://www.codeincodeblock.com/2025/02/part-2-tic-tac-toe-game-in-c-programing.html' title='Part 2: Tic Tac Toe game in C programing | Source Code explanation'/><author><name>Dinesh Subedi</name><uri>http://www.blogger.com/profile/15921581026092958477</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfxMED05n-0aBIoi4kgT-8kSHfpuRf1bFosaVy-JI-vEwMtJr0sNUFF4S2oj2axSo9IfljCyuPc4hieJ0HsUEPnmw7-8Rj6UTcQjG0Mwv0tiPhTTz6ginzbCdi48YU2oQ/s151/CIMG5697.JPG'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://img.youtube.com/vi/KnUvd3zjG9U/default.jpg" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7720722570285165075.post-5707737220941310781</id><published>2025-02-02T10:41:00.011+11:00</published><updated>2025-03-31T19:00:06.504+11:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C source code"/><category scheme="http://www.blogger.com/atom/ns#" term="Mini projects"/><title type='text'>Part 1: Tic Tac Toe game in C programing | Flowchart, Algorithm of Computer Player, and Data Structure</title><content type='html'>&lt;div style=&quot;text-align: left;&quot;&gt;&lt;a href=&quot;https://www.codeincodeblock.com/2011/06/mini-project-tic-tac-game-source-code.html&quot; target=&quot;_blank&quot;&gt;Previous Page&lt;/a&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;a href=&quot;https://www.codeincodeblock.com/2025/02/part-2-tic-tac-toe-game-in-c-programing.html&quot; target=&quot;_blank&quot;&gt;Next Page&lt;/a&gt;&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;&lt;span style=&quot;text-align: justify;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;&lt;span style=&quot;text-align: justify;&quot;&gt;Watch this tutorial in YouTube.&lt;/span&gt;&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;iframe allowfullscreen=&quot;&quot; class=&quot;BLOG_video_class&quot; height=&quot;266&quot; src=&quot;https://www.youtube.com/embed/rDieMorFw-8&quot; width=&quot;320&quot; youtube-src-id=&quot;rDieMorFw-8&quot;&gt;&lt;/iframe&gt;&lt;/div&gt;&lt;br /&gt;&lt;h2 style=&quot;text-align: left;&quot;&gt;Flowchart&lt;/h2&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhnO_9w8Fw3Pro1qjVYxIVO0TYPhErU_99W00GWN8HClV87N2ocpUdJhUEDRp8pxUW50kSagFZsLacajDhf19xUesw0fLgNvYLLugFRS4Sh-bw7_OAkE44nv2R-n9Aw2M0fOCXPNLd80HC5dUMADbBZx4at09R0cjEvMwlb9ZARSXftYSf6F-K4b2bA3wc/s907/Tic_Tac_Toe_Flowchart.jpg&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;907&quot; data-original-width=&quot;481&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhnO_9w8Fw3Pro1qjVYxIVO0TYPhErU_99W00GWN8HClV87N2ocpUdJhUEDRp8pxUW50kSagFZsLacajDhf19xUesw0fLgNvYLLugFRS4Sh-bw7_OAkE44nv2R-n9Aw2M0fOCXPNLd80HC5dUMADbBZx4at09R0cjEvMwlb9ZARSXftYSf6F-K4b2bA3wc/s16000/Tic_Tac_Toe_Flowchart.jpg&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;h3 style=&quot;text-align: left;&quot;&gt;Explanation of Flowchart:&lt;/h3&gt;&lt;div&gt;&lt;div&gt;&lt;b&gt;Start:&lt;/b&gt; The game process begins here.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Display Game Menu:&lt;/b&gt; The user can choose to play first or second.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Initialize Game:&lt;/b&gt; Initialize the human or computer as the first or second player. Set up the Tic-Tac-Toe board and assign initial values to the players.&lt;span&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Draw Game Window:&lt;/b&gt; Render the game window and wait for user input.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Start Game:&lt;/b&gt; Begin an infinite game loop.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Set Current Player (Human or Computer):&lt;/b&gt; Designate the current player as either the human or the computer and obtain input from the player.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Get Input from Player and Draw X or O Based on Player:&lt;/b&gt; Draw an &quot;X&quot; for the first player and an &quot;O&quot; for the second player.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Check for Game Winner or Draw:&lt;/b&gt; Determine if a player has won the game or if the game has ended in a draw.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Display Game Winner or Draw Message: &lt;/b&gt;Show a message indicating whether a player has won or if the game is a draw.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Ask User to Restart Game or Exit:&lt;/b&gt; If the user presses any key, restart the game. If the user presses the ESC key, exit the game.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Exit Game:&lt;/b&gt; The game process ends.&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;h3 style=&quot;text-align: left;&quot;&gt;Algorithm of computer player:&lt;/h3&gt;&lt;div&gt;As this game article is target for beginner c programmer, I haven&#39;t used complex AI algorithm which required creating complex data structure. Tic Tac Toe game has very limited number of steps, so I have formulated series of best game steps from high rank to low rank. Computer will choose next move based on predefine series of game steps.&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhPSZ7EUDtzvlpCbk0plNRN7G7tbsqzIwbq9nFEAXka1lLrAnLn1z4AXDxQM7qjF013Vj8eQ9n2ClmdWUHGN3JzZHPzmc73CX7JrkUbgm_sbHtWHn0vLvDIMpnMVjuwREGtFgUA73niOvyF3ayfratMGFrwVkGKEgZov-DCL9ZfnDDyFcEAmGttl7969U4/s295/Board.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;295&quot; data-original-width=&quot;240&quot; height=&quot;295&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhPSZ7EUDtzvlpCbk0plNRN7G7tbsqzIwbq9nFEAXka1lLrAnLn1z4AXDxQM7qjF013Vj8eQ9n2ClmdWUHGN3JzZHPzmc73CX7JrkUbgm_sbHtWHn0vLvDIMpnMVjuwREGtFgUA73niOvyF3ayfratMGFrwVkGKEgZov-DCL9ZfnDDyFcEAmGttl7969U4/s1600/Board.png&quot; width=&quot;240&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;div&gt;In every turn, computer will choose location starting from 1 to 11 steps.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;1. Choose location to win the game by scanning columns, rows, first diagonal, and second diagonal in order. If there is no winning position, then go to 2 steps.&lt;/div&gt;&lt;div&gt;2. Choose location to draw the game by scanning columns, rows, first diagonal, and second diagonal in order. If there is no game draw position, then go to 3 steps.&lt;/div&gt;&lt;div&gt;3. Choose center location i.e. fifth location, if not available go to step 4.&lt;/div&gt;&lt;div&gt;4. Choose second location, if not available go to step 5.&lt;/div&gt;&lt;div&gt;5. Choose fourth location, if not available go to step 6.&lt;/div&gt;&lt;div&gt;6. Choose sixth location, if not available go to step 7.&lt;/div&gt;&lt;div&gt;7. Choose eighth location, if not available go to step 8.&lt;/div&gt;&lt;div&gt;8. Choose first location, if not available go to step 9.&lt;/div&gt;&lt;div&gt;9. Choose third location, if not available go to step 10.&lt;/div&gt;&lt;div&gt;10. Choose seventh location, if not available go to step 11.&lt;/div&gt;&lt;div&gt;11. Choose ninth location&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;In above algorithm, 1 and 2 steps will not come in effective until third turn of the game.&lt;/div&gt;&lt;h3 style=&quot;text-align: left;&quot;&gt;Data Structure:&lt;/h3&gt;&lt;div&gt;This game is a 2D game played by two players on a 3x3 grid, totaling 9 boxes. There are three key elements/objects in this game: the player, the game board, and a 2D x-y coordinate system to represent the boxes. To model these elements, I have created three structure definitions: struct Point2D, struct BoardBox, and struct Player.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The Point2D structure is used to represent the center of each box, making it easier to draw an &quot;X&quot; or an &quot;O&quot; in the correct position. The BoardBox structure represents the nine boxes of the game. It contains the coordinates of the center of each box and a value assigned to it. The value is determined based on the player&#39;s choice: a value of 3 is assigned for the human player, and a value of 5 is assigned for the computer player.&lt;/div&gt;&lt;pre class=&quot;prettyprint&quot; style=&quot;text-align: left;&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;//Structure definition to store window x,y coordinates
struct Point2D {
    int x;
    int y;
};

//Structure definition to define each game board boxes
struct BoardBox {
    struct Point2D center;
    int value;
};

//struct variable to store nine boxes of the board.
struct BoardBox box[numBox]; 
&lt;/code&gt;&lt;/pre&gt;
&lt;div&gt;The Player structure represents both the human and computer players. It contains information about the current player, the next player, the box number selected by the current player, and the number of turns taken by the player. In total, there will be 9 turns to complete the game.&lt;/div&gt;&lt;pre class=&quot;prettyprint&quot; style=&quot;text-align: left;&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;//structure definition to store player information
struct Player {
    int numOfTurn;
    int selectedBox;
    int currentPlayer;
    int nextPlayer;

};

//Global variable to represent player
struct Player p; 
&lt;/code&gt;&lt;/pre&gt;
&lt;div&gt;&lt;br /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.codeincodeblock.com/feeds/5707737220941310781/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.codeincodeblock.com/2025/02/part-1-tic-tac-toe-game-in-c-programing.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/5707737220941310781'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/5707737220941310781'/><link rel='alternate' type='text/html' href='http://www.codeincodeblock.com/2025/02/part-1-tic-tac-toe-game-in-c-programing.html' title='Part 1: Tic Tac Toe game in C programing | Flowchart, Algorithm of Computer Player, and Data Structure'/><author><name>Dinesh Subedi</name><uri>http://www.blogger.com/profile/15921581026092958477</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfxMED05n-0aBIoi4kgT-8kSHfpuRf1bFosaVy-JI-vEwMtJr0sNUFF4S2oj2axSo9IfljCyuPc4hieJ0HsUEPnmw7-8Rj6UTcQjG0Mwv0tiPhTTz6ginzbCdi48YU2oQ/s151/CIMG5697.JPG'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://img.youtube.com/vi/rDieMorFw-8/default.jpg" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7720722570285165075.post-2549596548287894412</id><published>2024-12-04T21:42:00.006+11:00</published><updated>2025-03-31T18:59:59.160+11:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C source code"/><category scheme="http://www.blogger.com/atom/ns#" term="Mini projects"/><title type='text'>Part 2: Snake Game in C | Snake Collision Detection, Calculate next position and Changing direction</title><content type='html'>&lt;p&gt;&lt;b&gt;&lt;a href=&quot;https://www.codeincodeblock.com/2024/12/part-1-snake-game-in-c-flowchart-data.html&quot; target=&quot;_blank&quot;&gt;Previous page&lt;/a&gt;&lt;/b&gt;&amp;nbsp;&lt;/p&gt;&lt;p&gt;In this section, we will discuss the following items.&lt;/p&gt;&lt;p&gt;&lt;/p&gt;&lt;ul style=&quot;text-align: left;&quot;&gt;&lt;li&gt;Techniques to change direction of the snake based on user input.&lt;/li&gt;&lt;li&gt;Techniques to calculate the snake&#39;s next position.&lt;/li&gt;&lt;li&gt;Techniques to check for snake collision with window and its body.&lt;/li&gt;&lt;/ul&gt;&lt;h2 style=&quot;text-align: left;&quot;&gt;Snake direction and food&lt;/h2&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;We are using the gotoxy(int x, int y) function to move the snake on the screen. The top left corner of the PC window starts at (0,0). The right side of the screen is positive x-axis, and the bottom of the screen is positive y-axis. However, we can represent the direction of snake in all four directions by positive and negative axes (-x, 0), (x, 0), (0, -y), and (0, y). For the left arrow key, set direction as negative x-axis (-x,0), for the right arrow key set direction as positive x-axis (x,0), for the up arrow key set direction as negative y-axis (-y,0), and for the down arrow key set direction as positive y-axis (y,0). When the direction is changed, the snake will move perpendicular to current position, so we don&#39;t have to use both x, and y coordinates values. The coordinates system of the PC window is shown in the image below.&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgH4V6uhs78wpPsoQ2Pis5oiaHwqYYs8noOlCHp15eBpWmW5a_88WuQrLRMz3IiRD8hO33EM_3zwRnI7Y2Y48nJbei8S7OJYCEWKDTJVabNB3u8Wnro6YQICtMEInneLta7xCs7W0HhQfb5o-nP4uCI97Obe-5IJmR7v73L5HqI2-WnmpIHEBNMUKFd04o/s613/coordinates.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;613&quot; data-original-width=&quot;592&quot; height=&quot;320&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgH4V6uhs78wpPsoQ2Pis5oiaHwqYYs8noOlCHp15eBpWmW5a_88WuQrLRMz3IiRD8hO33EM_3zwRnI7Y2Y48nJbei8S7OJYCEWKDTJVabNB3u8Wnro6YQICtMEInneLta7xCs7W0HhQfb5o-nP4uCI97Obe-5IJmR7v73L5HqI2-WnmpIHEBNMUKFd04o/s320/coordinates.png&quot; width=&quot;309&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div&gt;&lt;span&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;/span&gt;Simply, we draw the &quot;0&quot; character as food in a random position on the window. To simplify this process, we create an array of Point2D struct variables (struct Point2D food[sSize]) and initialize it by storing all possible coordinates of the window. In this game, there are 800 possible coordinates, 40 towards x-axis and 20 towards y-axis. Now, we generate a random number between 0 and 800. The random number is used as an index of the food array, and we draw the &quot;0&quot; character at the coordinate of that index.&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot; style=&quot;text-align: left;&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
struct Point2D dir[4]; //array for snake direction vector
struct Point2D food[sSize];

void initDir(){

    //Up direction
    dir[UP].x = 0;
    dir[UP].y = -1;

    //Down direction
    dir[DW].x = 0;
    dir[DW].y = 1;

    //Right Direction
    dir[RT].x = 1;
    dir[RT].y = 0;

    //Left Direction
    dir[LT].x = -1;
    dir[LT].y = 0;
}

void initFood(){

    int i=0;
    for(int j=0;j&amp;lt;winYLen;j++){
        for(int k=0;k&amp;lt;winXLen;k++){
            food[i].x = k + startPosX;
            food[i].y = j + startPosY;

            i++;
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;&lt;b&gt;Calculate Snake&#39;s next position&lt;/b&gt;&lt;/h2&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;At first, we have to initialize snake variable which initial values such as length, body, head, tail and direction. We set snake length and calculate initial snake body coordinates from initial starting position, set snake head and tail coordinates and set snake initial direction. In this game, I have used initial length of 3, snake starting position (11,10), and initial moving direction is right (1, 0). The body of snake will be (11,10), (12,10), (13,10), snake head will be (13,10) and tail will be (11,10).&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;void initSnake(){

    for(int i=0;i&amp;lt;startLen;i++){
        s.body[i].x = startPosX + i;
        s.body[i].y = 10;
    }

    s.head.x = s.body[startLen-1].x;
    s.head.y = s.body[startLen-1].y;

    //In first frame of the game tail position
    //need to be out of window or blank
    s.tail.x = 0;
    s.tail.y = 0;

    s.dir.x = dir[RT].x; s.dir.y = dir[RT].y;

    s.length = startLen;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;div style=&quot;text-align: justify;&quot;&gt;Now, using initial snake position and direction we will calculate next position. Next position will be always snake&#39;s head position. As you know, snake always move in straight line and change direction ±90 degree from its current head position. In each given frame only one coordinate axis (either x or y) will change. So, we need to calculate new head position only. Snake body is an array of 2D coordinates. We know the maximum possible length of snake is 800 in this example. We had already created snake body array of size 800. We will add new head position in body array and swap the body coordinates so that previous tail coordinates of snake will no longer be the part of snake body will get removed. If snake collide with food, then we will not swap the body, but we will increase the length of the snake and increase score. On screen we will print blank on previous tail coordinates and print &quot;*&quot; on new head coordinate. Even we don&#39;t have to print whole snake body in each frame. Also, we don&#39;t have to print window in each frame, it is always fixed. Here, moving parts will be always head and tail of the snake other parts are not changes.&amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;For example, if the snake head is (13,10) and the direction is right (1,0), then add 1 unit to the x-coordinate. If direction is up (0, -1), then subtract 1 unit from the y-coordinate. If the direction is down (0,1), then add 1 unit to the y-coordinate. If direction is left (-1,0), then subtract 1 unit from the x-coordinate. However, if previous direct is right, then user should not be allowed to move left. Snake should move only by 90 degrees either positive or negative.&amp;nbsp;&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot; style=&quot;text-align: left;&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
int buildSnake(struct Point2D f,struct Point2D d){

    if(s.dir.x != -d.x &amp;amp;&amp;amp; s.dir.y != -d.y){
        s.dir.x = d.x; s.dir.y = d.y;
    }

    s.head.x = s.body[s.length-1].x + s.dir.x;
    s.head.y = s.body[s.length-1].y + s.dir.y;

    s.body[s.length].x = s.head.x;
    s.body[s.length].y = s.head.y;
    if(s.head.x == f.x &amp;amp;&amp;amp; s.head.y == f.y){
        s.length++;
        return 1;
    } else {
        s.tail.x = s.body[0].x;
        s.tail.y = s.body[0].y;
        //Swap snake body back starting from initial index
        for (int i = 0;i&amp;lt;s.length;i++){
            s.body[i].x = s.body[i+1].x;
            s.body[i].y = s.body[i+1].y;
        }
    }

    return 0;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;&lt;b&gt;Collision detection&lt;/b&gt;&lt;/h2&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;We have very few objects in this game, so the collision detection is very simple. We have to detect the collision of snake&#39;s head with four walls of window and its body. We already have coordinates of all these objects. After calculating the next snake&#39;s head position, we will compare the coordinates of snake&#39;s head position with four walls. Also, we will check weather new head position falls within its body. If a collision with walls and its body found, we will terminate game and ask user to restart again or exit.&amp;nbsp;&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
int checkCollision(){
    if(s.length == sSize){
        return 2;
    }

    if(s.head.x == wX1 || s.head.x == wX2){
        return 1;
    }

    if(s.head.y == wY1 ||s.head.y == wY3){
        return 1;
    }

    for (int i=0;i&amp;lt;s.length-2;i++){

        if(s.head.x == s.body[i].x &amp;amp;&amp;amp; s.head.y == s.body[i].y){
            return 1;
        }
    }

    return 0;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;div&gt;&amp;nbsp;&lt;/div&gt;&lt;div&gt;Please find video of this article in YouTube.&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;iframe allowfullscreen=&quot;&quot; class=&quot;BLOG_video_class&quot; height=&quot;266&quot; src=&quot;https://www.youtube.com/embed/nvi6fXKkc3I&quot; width=&quot;320&quot; youtube-src-id=&quot;nvi6fXKkc3I&quot;&gt;&lt;/iframe&gt;&lt;/div&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;p&gt;&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.codeincodeblock.com/feeds/2549596548287894412/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.codeincodeblock.com/2024/12/part-2-snake-game-in-c-snake-collision.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/2549596548287894412'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/2549596548287894412'/><link rel='alternate' type='text/html' href='http://www.codeincodeblock.com/2024/12/part-2-snake-game-in-c-snake-collision.html' title='Part 2: Snake Game in C | Snake Collision Detection, Calculate next position and Changing direction'/><author><name>Dinesh Subedi</name><uri>http://www.blogger.com/profile/15921581026092958477</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfxMED05n-0aBIoi4kgT-8kSHfpuRf1bFosaVy-JI-vEwMtJr0sNUFF4S2oj2axSo9IfljCyuPc4hieJ0HsUEPnmw7-8Rj6UTcQjG0Mwv0tiPhTTz6ginzbCdi48YU2oQ/s151/CIMG5697.JPG'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgH4V6uhs78wpPsoQ2Pis5oiaHwqYYs8noOlCHp15eBpWmW5a_88WuQrLRMz3IiRD8hO33EM_3zwRnI7Y2Y48nJbei8S7OJYCEWKDTJVabNB3u8Wnro6YQICtMEInneLta7xCs7W0HhQfb5o-nP4uCI97Obe-5IJmR7v73L5HqI2-WnmpIHEBNMUKFd04o/s72-c/coordinates.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7720722570285165075.post-7664702465260006754</id><published>2024-12-04T21:41:00.008+11:00</published><updated>2025-03-31T18:59:52.122+11:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C source code"/><category scheme="http://www.blogger.com/atom/ns#" term="Mini projects"/><title type='text'>Part 1: Snake Game in C | Flowchart, Data Structure and Algorithm</title><content type='html'>&lt;p style=&quot;text-align: left;&quot;&gt;&lt;b&gt;&lt;a href=&quot;https://www.codeincodeblock.com/2011/06/mini-projet-snake-game-in-c.html&quot; target=&quot;_blank&quot;&gt;Previous page&lt;/a&gt;&amp;nbsp; &amp;nbsp;&lt;/b&gt; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&lt;a href=&quot;https://www.codeincodeblock.com/2024/12/part-2-snake-game-in-c-snake-collision.html&quot; target=&quot;_blank&quot;&gt;Next Page&lt;/a&gt;&lt;/p&gt;&lt;h2 style=&quot;text-align: left;&quot;&gt;Flowchart&lt;/h2&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh56yuB9sbUl41SDr0zBVCPlvbhDhBWwi4J_J4rjw40rJuAGZJnZe2Cxu6foQNOoNBmM_taiVE4C6vWi8tQtHFOmlxEID4iU0RRyK-WHYnVOnCGyI0HTFEQMOjkOw4kivq5hzLHR_mMgNzS3vuXT8PNhhpmViUiArxXdEvRAfXWKwqWGvQlo2CO89X6Q4k/s967/Snake_Game_FlowChart.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Flowchart: Snake Game in C&quot; border=&quot;0&quot; data-original-height=&quot;773&quot; data-original-width=&quot;967&quot; height=&quot;512&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh56yuB9sbUl41SDr0zBVCPlvbhDhBWwi4J_J4rjw40rJuAGZJnZe2Cxu6foQNOoNBmM_taiVE4C6vWi8tQtHFOmlxEID4iU0RRyK-WHYnVOnCGyI0HTFEQMOjkOw4kivq5hzLHR_mMgNzS3vuXT8PNhhpmViUiArxXdEvRAfXWKwqWGvQlo2CO89X6Q4k/w640-h512/Snake_Game_FlowChart.png&quot; title=&quot;Flowchart: Snake Game in C&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;b&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Explanation of Flowchart:&lt;/b&gt;&lt;/div&gt;&lt;/b&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Start:&lt;/b&gt; The process begins here.&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Initialize game:&lt;/b&gt; Initialize Snake Direction, food, snake, window, variables, and others&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;&lt;span&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;/span&gt;Draw initial window:&lt;/b&gt; Draw the window when snake game is played. Window will have fix coordinates.&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Start Game:&lt;/b&gt; Start gameplay.&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Calculate Snake Next Position:&lt;/b&gt; For the first time, snake will start at a fix location. It will calculate the next position based on snake directions (up, down, left or right) provided by the user.&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Check Snake Eating Food:&lt;/b&gt; After calculating next position, check whether the snake&#39;s next location and food location collide.&amp;nbsp;&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Increase length of snake and draw food:&lt;/b&gt; If yes, then food is eaten by the snake. Increase the length of the snake and draw food in another random location.&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Check Collision:&lt;/b&gt; Check the snake&#39;s collision with snake body and window walls.&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Draw next frame (snake):&lt;/b&gt; Based on snake next position and length, draw the snake.&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Check Key Press:&lt;/b&gt; Check keyboard key presses by the user.&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Change Snake Direction:&lt;/b&gt; Based on key press (up, down, left and right arrows) by the user, change the direction of snake.&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Exit Game:&lt;/b&gt; Exit game if user presses ESC key or the snake collides with window or its body.&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;br /&gt;&lt;/div&gt;&lt;h2 style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Data Structure&lt;/b&gt;&lt;/h2&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;This is a 2D game played on flat window. So, each point on the window is (x, y) coordinate. The initial size of the game window is fixed, defined by the x-axis length and y-axis length. I am using an x-axis length 40 and y-axis length 20 of window. So, the maximum size of the snake is 40*20=800. The maximum number of foods required to display is also 800. Also, based on the widow size and starting position, we will calculate the coordinates of all four corners of the window.&amp;nbsp;&lt;/div&gt;&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;#define winXLen 40 //Snake game play window x-coordinate size
#define winYLen 20 //Snake game play window y-coordinate size
#define startPosX 11 //Game play window starting x-coordinate
#define startPosY 1 //Game play window starting y-coordinate
#define startLen 3 //Snake starting length
//Max size of the snake must be always &amp;gt;= winXLen * winYLen
#define sSize 800 

#define UP 0 //Up direction array index
#define DW 1 //Down direction array index
#define RT 2 //Right direction array index
#define LT 3 //Left direction array index

static const int winBorderX = winXLen + startPosX;
static const int winBorderY = winYLen + startPosY;
//First Corner of the Window
static const int wX1 = startPosX-1, wY1 = startPosY-1; 
//Second Corner of the Window
static const int wX2 = winBorderX, wY2 = startPosY-1; 
//Third Corner of the Window
static const int wX3 = winBorderX, wY3 = winBorderY; 
//Fourth Corner of the Window
static const int wX4 = startPosX-1, wY4 = winBorderY; 
&lt;/code&gt;&lt;/pre&gt;
&lt;div style=&quot;text-align: justify;&quot;&gt;We must always represent points (x, y) coordinates using single variable. It is done by defining struct variable &lt;b&gt;Point2D&lt;/b&gt; with two int x and int y variables inside it. Using this structure variable, we can define each point of the snake, snake direction and food. The body of snake is an array of (x,y) coordinates. So, we can define snake by array of Point2D &lt;b&gt;struct Point2D body[size]&lt;/b&gt;.&amp;nbsp;&lt;/div&gt;
&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;To move snake in player&#39;s given direction, display moving snake and check for collision, we need snake characteristics such as snake&#39;s body, head, tail, length, and direction in each frame of the game. We must bundle all these characteristics in struct variable Snake.&amp;nbsp; The structure variable &lt;b&gt;struct Snake s&lt;/b&gt; define the snake in any given frame.&amp;nbsp; Here, I am refreshing window in every 150 milliseconds so there will be 6-7 frames per second.&lt;/div&gt;&lt;pre class=&quot;prettyprint&quot; style=&quot;text-align: left;&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;struct Point2D{
    int x;
    int y;
};

struct Snake{
    struct Point2D body[sSize];
    struct Point2D head;
    struct Point2D tail;
    struct Point2D dir;
    int length;
};

struct Snake s;
//array for snake direction vector
struct Point2D dir[4]; 
struct Point2D food[sSize];
&lt;/code&gt;&lt;/pre&gt;&lt;h2 style=&quot;text-align: left;&quot;&gt;&lt;b&gt;

Algorithm&lt;/b&gt;&lt;/h2&gt;&lt;div&gt;&lt;ul style=&quot;text-align: left;&quot;&gt;&lt;li style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Step 1: &lt;/b&gt;Initialize global variables such as window length, height, snake starting position, snake initial length, total number of moving coordinates inside the window.&lt;/li&gt;&lt;li style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Step 2: &lt;/b&gt;Create C structure for 2D points, and the snake, and create global variables for snake, direction, and food.&lt;/li&gt;&lt;li style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Step 3:&lt;/b&gt; Initialize direction, food, snake, and hide mouse cursor&lt;/li&gt;&lt;li style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Step 4:&lt;/b&gt; Draw window and draw snake in initial starting position&lt;/li&gt;&lt;li style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Step 5:&lt;/b&gt; Generate random value range 0 to maximum size of available coordinates and draw food in a random position&lt;/li&gt;&lt;li style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Step 6:&lt;/b&gt; Start game and capture game status flag.&amp;nbsp;&lt;/li&gt;&lt;li style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Step 7:&lt;/b&gt; Initialize game status flag to zero and variable to capture user input&lt;/li&gt;&lt;li style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Step 8:&lt;/b&gt; Start do-while loop and break loop when user presses a key.&lt;/li&gt;&lt;ul&gt;&lt;li style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Step 8.1:&lt;/b&gt; Delay by 150 milliseconds or as needed so that there will be 6-7 frame per second.&lt;/li&gt;&lt;li style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Step 8.2:&lt;/b&gt; Calculate Snake next position and check collision with food. Initialize snake head by next snake position. If snake do not collide with food, initialize tail variable by snake tail coordinates and swap the value of snake body array so that the next position will be the snake head, and the second last position will be the snake tail.&amp;nbsp;&lt;/li&gt;&lt;li style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Step 8.3:&lt;/b&gt; If the snake collides with food, draw food in random location, and increase snake length and game score. Otherwise, go to step 8.4.&lt;/li&gt;&lt;li style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Step 8.4:&lt;/b&gt; Check for collisions of the snake with the window walls and within the snake body.&lt;/li&gt;&lt;li style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Step 8.5:&lt;/b&gt; If the snake collides, then exit the game and go to step 9.&lt;/li&gt;&lt;li style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Step 8.6:&lt;/b&gt; Draw the snake head in next position and delete the snake tail.&lt;/li&gt;&lt;li style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Step 8.7:&lt;/b&gt; Check for key presses by user. If a key is entered, go to step 8.8; Otherwise, do nothing and continue loop from step 8.1.&lt;/li&gt;&lt;li style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Step 8.8:&lt;/b&gt; If an arrow key (up, down, left, right) is entered, change the direction of the snake. If ESC key entered, exit the game. Otherwise, start the game again from step 8.&lt;/li&gt;&lt;/ul&gt;&lt;li style=&quot;text-align: justify;&quot;&gt;&amp;nbsp;&lt;b&gt;Step 9:&lt;/b&gt; Display the game over message and request user to start game again by pressing any key or exit the game by pressing the ESC key.&lt;/li&gt;&lt;li style=&quot;text-align: justify;&quot;&gt;&lt;b&gt;Step 10:&lt;/b&gt; If user press any key, start the game from step 3; Otherwise, exit the game.&lt;/li&gt;&lt;/ul&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;Please find video of this article in YouTube.&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;iframe allowfullscreen=&quot;&quot; class=&quot;BLOG_video_class&quot; height=&quot;266&quot; src=&quot;https://www.youtube.com/embed/qea9XB6WqTo&quot; width=&quot;320&quot; youtube-src-id=&quot;qea9XB6WqTo&quot;&gt;&lt;/iframe&gt;&lt;/div&gt;&lt;br /&gt;&lt;div style=&quot;text-align: justify;&quot;&gt;&lt;br /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.codeincodeblock.com/feeds/7664702465260006754/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.codeincodeblock.com/2024/12/part-1-snake-game-in-c-flowchart-data.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/7664702465260006754'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/7664702465260006754'/><link rel='alternate' type='text/html' href='http://www.codeincodeblock.com/2024/12/part-1-snake-game-in-c-flowchart-data.html' title='Part 1: Snake Game in C | Flowchart, Data Structure and Algorithm'/><author><name>Dinesh Subedi</name><uri>http://www.blogger.com/profile/15921581026092958477</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfxMED05n-0aBIoi4kgT-8kSHfpuRf1bFosaVy-JI-vEwMtJr0sNUFF4S2oj2axSo9IfljCyuPc4hieJ0HsUEPnmw7-8Rj6UTcQjG0Mwv0tiPhTTz6ginzbCdi48YU2oQ/s151/CIMG5697.JPG'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh56yuB9sbUl41SDr0zBVCPlvbhDhBWwi4J_J4rjw40rJuAGZJnZe2Cxu6foQNOoNBmM_taiVE4C6vWi8tQtHFOmlxEID4iU0RRyK-WHYnVOnCGyI0HTFEQMOjkOw4kivq5hzLHR_mMgNzS3vuXT8PNhhpmViUiArxXdEvRAfXWKwqWGvQlo2CO89X6Q4k/s72-w640-h512-c/Snake_Game_FlowChart.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7720722570285165075.post-4037289626970214899</id><published>2024-06-03T20:34:00.017+10:00</published><updated>2025-03-31T18:59:42.917+11:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C source code"/><category scheme="http://www.blogger.com/atom/ns#" term="Mini projects"/><title type='text'>Part 4: Library management in C| Pagination, Dynamic Memory allocation, write Comma Separated Values (CSV) file</title><content type='html'>&lt;p&gt;&lt;a href=&quot;https://www.codeincodeblock.com/2024/06/part-3-library-management-in-c-read.html&quot;&gt;&lt;b&gt;Previous Page&lt;/b&gt;&lt;/a&gt;&lt;br /&gt;&lt;/p&gt;&lt;p&gt;In this part, we will create pagination in C programming to view large set of books data. In college there might be thousands of books. We can&#39;t display all items on the screen, so we need to create techniques to display small set of data at a time and allow users to select next page or previous page to view data which is called pagination. Also, we will discuss to manage large set of books data and write books data into CSV file.&lt;/p&gt;&lt;p&gt;Here, we will discuss following items:&lt;/p&gt;&lt;p&gt;&lt;/p&gt;&lt;ul style=&quot;text-align: left;&quot;&gt;&lt;li&gt;Pagination: Users can explore large set of data by selecting next or previous page of data.&lt;/li&gt;&lt;li&gt;Dynamic Memory allocation: Dynamic numbers of books are loaded into the memory, modify or delete book details from the memory using dynamic memory allocation.&lt;/li&gt;&lt;li&gt;Write Comma Separated Values (CSV): Export large set of books data into CSV file.&lt;/li&gt;&lt;/ul&gt;&lt;div&gt;Please follow the source code of header file userMenu.h and loadCsvData.h.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Pagination:&lt;/b&gt;&lt;/div&gt;&lt;div&gt;We have three main functions to implement pagination features. The main technique is to load data into computer memory (RAM). The number of data which can be loaded in memory depend upon size of the memory. However, we will not get memory problem to load couple of thousands of data. In this application I haven&#39;t used large set of data however this technique can be used for any size of data.&lt;/div&gt;&lt;div&gt;The name of the functions are readBooks(), viewAllBooks(), and viewBooksByPage().&amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;span&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;/span&gt;int readBooks()&lt;/b&gt;: This function is written inside loadCsvData.h header file. This function is called at the very first start of the application inside void adminMenu() and void studentMenu().&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;ol style=&quot;text-align: left;&quot;&gt;&lt;li&gt;Line 148: int bkSize = getRowCount(fpl), function getRowCount() reads the books data file to count number of books and assign count to the variable bkSize. This variable is used to allocate size of the array of book structure.&amp;nbsp;&lt;/li&gt;&lt;li&gt;Line 151:&amp;nbsp;rewind(fpl); this will rewind the file pointer back to start of the file to continue reading books data.&lt;/li&gt;&lt;li&gt;Line 151:&amp;nbsp;bk = (struct books*)malloc(bkSize * sizeof(struct books)); using malloc function we will allocate the size of the array bk equal to number of books count, and bk is array pointer.&lt;/li&gt;&lt;li&gt;Remaining codes up to line 194 will read books data from the file using loadBookValues functions which is discussed in part 3 of this tutorial.&amp;nbsp;&lt;/li&gt;&lt;li&gt;Line 196: bk++, this will increment the pointer by 1 unit so that we can assign new books value into the array.&lt;/li&gt;&lt;li&gt;Line 201: bk=(bk-bkSize), this will move pointer back to initial position so that we can view data from the beginning of array.&amp;nbsp;&lt;/li&gt;&lt;/ol&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;void viewAllBooks(int flag): &lt;/b&gt;This function calculates the value of lower index and higher index of an array based on user input to display books data on the screen. The parameter flag will decide whether it is viewed by student or admin user. The number of data displayed per page is 15 which is declared by variable pageSize. At first lower index is zero, and higher index is 15 which is defined by variables lIndex and hIndex respectively. Now, when user will press key &#39;b&#39; to view next page, the lower and higher index will be incremented by 15, if the value of higher index is greater than books count then higher index will be equal to books count, stops incrementing variables value. In similar way, if user press key &#39;n&#39; to view previous page, the initial and lower index will be subtracted by 15. If lower index value will be less than zero, then initial index is set to zero and stops decrementing variables value. Every time user press key, the calculated initial index and higher index is passed to function viewBooksBypage() to display books data on the screen.&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Add, Update and Delete books data: &lt;/b&gt;As books data is already loaded in memory data, modifying and deleting data do not involve C file operations. Add, update and delete operation happens directly in data array. Here dynamic memory allocation plays major role to perform these operations.&lt;/div&gt;&lt;div&gt;&lt;ul style=&quot;text-align: left;&quot;&gt;&lt;li&gt;&lt;b&gt;Update book data: &lt;/b&gt;We can update the value of array directly which is very fast and easy. The function updateBook() is created to update books data. It requests book&#39;s new details from the user and update the value in array.&lt;/li&gt;&lt;li&gt;&lt;b&gt;Add book data: &lt;/b&gt;We can&#39;t simply add additional elements in array because memory is not already allocated. At first, we have to allocate memory and add new elements. The function addBook() is created to add books data. It requests new books information and add books data in the array.&lt;/li&gt;&lt;ul&gt;&lt;li&gt;Line 375: int newbkCount=bkCount+1;, assign variable by new book count.&lt;/li&gt;&lt;li&gt;Line 377: bk = (struct books*)realloc(bk,newbkCount * sizeof(struct books));, the memory of array bk is reallocated using realloc function by new new book count.&lt;/li&gt;&lt;li&gt;Line 378: bk = (bk+bkCount);, move the pointer to new element of an array.&lt;/li&gt;&lt;li&gt;Line 380 to 386: Copy the books value into bk array using strcpy function.&lt;/li&gt;&lt;li&gt;Line 388: bk = (bk-bkCount), move the pointer back to initial position of an array.&lt;/li&gt;&lt;li&gt;Line 389: update the variable bkCount by new count i.e newbkCount.&amp;nbsp;&lt;/li&gt;&lt;/ul&gt;&lt;li&gt;&lt;b&gt;Delete book data: &lt;/b&gt;The logic to delete data is to allocate new memory block with size 1 item less than current memory block. Copy all data to new memory block except the item which we want to delete. Free previous memory block and point pointer to new memory block.&lt;/li&gt;&lt;ul&gt;&lt;li&gt;Line 475:&amp;nbsp;tmp_bk = (struct books*)malloc((bkCount-1) * sizeof(struct books)), allocate new memory block of size bkCount-1.&lt;/li&gt;&lt;li&gt;Line 477:&amp;nbsp;if(indexToRemove != 0) memmove(tmp_bk,bk,(indexToRemove)*sizeof(struct books)), copy data from memory bock bk to tmp_bk upto the block which we want to delete.&lt;/li&gt;&lt;li&gt;Line 480:&amp;nbsp;if(indexToRemove != (bkCount-1)) memmove(tmp_bk+indexToRemove,bk+(indexToRemove+1),(bkCount-indexToRemove-1)*sizeof(struct books)), copy data from memory bock bk to tmp_bk after the block which we want to delete.&lt;/li&gt;&lt;li&gt;Line 483:&amp;nbsp;free(bk), free memory block.&lt;/li&gt;&lt;li&gt;Line 484: bk = tmp_bk, assign the address of new memory block to old pointer bk.&lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt;&lt;div&gt;&lt;b&gt;Write data into Comma Separated Values (CSV) file&lt;/b&gt;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;The method to write data into CSV file is straight forward and easy. We can use fprintf() function to write data in file as a required format.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;iframe allowfullscreen=&quot;&quot; class=&quot;BLOG_video_class&quot; height=&quot;266&quot; src=&quot;https://www.youtube.com/embed/woC7Mf9VLtY&quot; width=&quot;320&quot; youtube-src-id=&quot;woC7Mf9VLtY&quot;&gt;&lt;/iframe&gt;&lt;/div&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;p&gt;&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.codeincodeblock.com/feeds/4037289626970214899/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.codeincodeblock.com/2024/06/part-4-library-management-in-c.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/4037289626970214899'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/4037289626970214899'/><link rel='alternate' type='text/html' href='http://www.codeincodeblock.com/2024/06/part-4-library-management-in-c.html' title='Part 4: Library management in C| Pagination, Dynamic Memory allocation, write Comma Separated Values (CSV) file'/><author><name>Dinesh Subedi</name><uri>http://www.blogger.com/profile/15921581026092958477</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfxMED05n-0aBIoi4kgT-8kSHfpuRf1bFosaVy-JI-vEwMtJr0sNUFF4S2oj2axSo9IfljCyuPc4hieJ0HsUEPnmw7-8Rj6UTcQjG0Mwv0tiPhTTz6ginzbCdi48YU2oQ/s151/CIMG5697.JPG'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://img.youtube.com/vi/woC7Mf9VLtY/default.jpg" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7720722570285165075.post-610605184355750056</id><published>2024-06-03T20:34:00.016+10:00</published><updated>2025-03-31T18:59:31.396+11:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C source code"/><category scheme="http://www.blogger.com/atom/ns#" term="Mini projects"/><title type='text'>Part 3: Library management in C| Read Comma Separated Values (CSV) file and Student Login System</title><content type='html'>&lt;p&gt;&lt;a href=&quot;https://www.codeincodeblock.com/2024/06/part-2-library-management-in-c.html&quot;&gt;&lt;b&gt;Previous Page&lt;/b&gt;&lt;/a&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;b&gt;&amp;nbsp;&lt;a href=&quot;https://www.codeincodeblock.com/2024/06/part-4-library-management-in-c.html&quot;&gt;Next Page&lt;/a&gt;&lt;/b&gt;&lt;/p&gt;&lt;p&gt;In this application we have two scenarios where we read CSV files. First to read Students data and second to read books data. Students need to provide student id to login application. We read the students data from csv file and compare the student id. Also, we read large set of books data from csv file.&lt;/p&gt;&lt;p&gt;Sample student csv data:&lt;/p&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzI86h7iBATP-vhxVJGrUtGbiau6Bb4uIXIuE3TrxLj_TLjnKEgaM3ehuzRfLt0sUli_nCiTW-_mt8IGQ66Jk_HRoVh66Cwnz2D0oE_7QRwZF03Mr7GOW1TKrTQy41mnLE4hWSZ39ZTMEpgNj8deMIe9AQ3uTbiSg_g7e70cl0atSizmC9Q321_e1UYKE/s1113/StudentData.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;467&quot; data-original-width=&quot;1113&quot; height=&quot;269&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzI86h7iBATP-vhxVJGrUtGbiau6Bb4uIXIuE3TrxLj_TLjnKEgaM3ehuzRfLt0sUli_nCiTW-_mt8IGQ66Jk_HRoVh66Cwnz2D0oE_7QRwZF03Mr7GOW1TKrTQy41mnLE4hWSZ39ZTMEpgNj8deMIe9AQ3uTbiSg_g7e70cl0atSizmC9Q321_e1UYKE/w640-h269/StudentData.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;Sample books csv data:&lt;p&gt;&lt;/p&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjtTXhyphenhyphenp4T94bzhhhxsxywK5tfeTMy6s2Q-jywOpZM0e7Htu8QJ0CjEojhB-pzNutUYdcODvNJCHKZq-9E_UUdlobF1aeg3tobbwzZkcsK98uHE_vgeV13MO-6m1sgqmWB47468vTO_S7ygWRwEaRbQUzy22C9Dx74ESLQqdQnWVKIUUalgKvttu9tsY6U/s1732/BookData.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;346&quot; data-original-width=&quot;1732&quot; height=&quot;128&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjtTXhyphenhyphenp4T94bzhhhxsxywK5tfeTMy6s2Q-jywOpZM0e7Htu8QJ0CjEojhB-pzNutUYdcODvNJCHKZq-9E_UUdlobF1aeg3tobbwzZkcsK98uHE_vgeV13MO-6m1sgqmWB47468vTO_S7ygWRwEaRbQUzy22C9Dx74ESLQqdQnWVKIUUalgKvttu9tsY6U/w640-h128/BookData.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;p&gt;The header file loadCsvData.h is written to load csv files student data and books data. There are four main functions which reads the files.&lt;/p&gt;&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
static int getStudentID(char stuId[MAX_ID], struct stuProfile *st);
static int  loadStuValues(char *line, char *sFields[STU_COL_NUM]);
int readBooks();
static int  loadBookValues(char *line, char *lFields[BK_COL_NUM]);
int getRowCount(FILE *fpl);
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;span&gt;&lt;/span&gt;&lt;/p&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;First two functions&amp;nbsp;&lt;b&gt;static int getStudentID(char stuId[MAX_ID], struct stuProfile *st) &lt;/b&gt;and&amp;nbsp;&lt;b&gt;static int&amp;nbsp; loadStuValues(char *line, char *sFields[STU_COL_NUM]) &lt;/b&gt;loads student data. Let&#39;s breakdown these functions.&lt;p&gt;&lt;/p&gt;&lt;p&gt;&lt;b&gt;Function getStudentID(char stuId[MAX_ID], struct stuProfile *st): &lt;/b&gt;This function compares the student id passed in the paraments with the student data read and if student id found, it will initialize the stuProfile structure pointer by student information.&amp;nbsp;&lt;/p&gt;&lt;p&gt;&lt;/p&gt;&lt;ol style=&quot;text-align: left;&quot;&gt;&lt;li&gt;Line 49:&amp;nbsp;&lt;b&gt;fps = fopen(STU_DATA_FILE, &quot;r&quot;) &lt;/b&gt;reads the csv file in read mode.&amp;nbsp;&lt;/li&gt;&lt;li&gt;Line 58:&amp;nbsp;&lt;b&gt;while (!feof(fps)) &lt;/b&gt;loop reads the file line by line until the end of the file is reached.&lt;/li&gt;&lt;li&gt;Line 61:&amp;nbsp;&lt;b&gt;if(fgets(inBuffer, BUFFER_SZ-1, fps)==NULL) break;&amp;nbsp;&lt;/b&gt;reads the line from the file into the buffer. The loop will break if end of the file is reached.&lt;/li&gt;&lt;li&gt;Line 65 and 69:&amp;nbsp;&lt;b&gt;if(++rowNum==1) continue; &lt;/b&gt;and&lt;b&gt; if(strlen(inBuffer)==0) continue; &lt;/b&gt;skips the first header data and empty lines.&lt;/li&gt;&lt;li&gt;Line 72:&amp;nbsp;&lt;b&gt;if(loadStuValues(inBuffer,sFields)==FAIL)&lt;/b&gt;{This call function loadStuValues() to read each columns values from the line. The parameter sFields is character pointer to array of string equal to number of columns. The size of the array must be equal to number of columns in csv file. After reading columns value, function will assign it to sFields pointer variable.&amp;nbsp;&lt;/li&gt;&lt;li&gt;Line 78:&amp;nbsp;&lt;b&gt;if(strcmp(sFields[ID],stuId)==0) &lt;/b&gt;it compares the student id passed in the parameter to file data. If student id exits, followings line will initialize structure stuProfile elements.&lt;/li&gt;&lt;/ol&gt;&lt;div&gt;Source code of the function:&lt;/div&gt;&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
static int getStudentID(char stuId[MAX_ID], struct stuProfile *st){

    FILE *fps;

    // char* array will point to fields
    char *sFields[STU_COL_NUM];

    int err_count = 0;

    fps = fopen(STU_DATA_FILE, &quot;r&quot;);
    if(fps == NULL) {
        //printf(&quot;Error opening file: %d\n&quot;,errno);
        return(FAIL);
    }

    char inBuffer [BUFFER_SZ];
    long rowNum = 0L;

    while (!feof(fps)) {

        // load line into static buffer
        if(fgets(inBuffer, BUFFER_SZ-1, fps)==NULL)
            break;

        // skip first line (headers)
        if(++rowNum==1)
            continue;

        // jump over empty lines
        if(strlen(inBuffer)==0)
            continue;
        // set pFields array pointers to null-terminated 
        //string fields in inBuffer
        if(loadStuValues(inBuffer,sFields)==FAIL){
           err_count++;
            if(err_count &amp;gt; MAX_ERROR_NUM)
                break;
        } else {
            //Compare Student ID
            if(strcmp(sFields[ID],stuId)==0){

                strcpy(st-&amp;gt;stuID,sFields[ID]);
                strcpy(st-&amp;gt;fName,sFields[fNAME]);
                strcpy(st-&amp;gt;lName,sFields[lNAME]);
                strcpy(st-&amp;gt;faculty,sFields[FACULTY]);

                fclose(fps);
                return PASS;
            }
        }
    }
    fclose(fps);

    return FAIL;
}
&lt;/code&gt;&lt;/pre&gt;&lt;b&gt;Function&amp;nbsp;loadStuValues(char *line, char *sFields[STU_COL_NUM]): &lt;/b&gt;This function reads the column value separated by csv. To include the comma value inside the column we will user enclose the column value by double inverted quotation.&amp;nbsp;&lt;div&gt;&lt;ol style=&quot;text-align: left;&quot;&gt;&lt;li&gt;Line 97: &lt;b&gt;char delim=&#39;,&#39;;&amp;nbsp;&lt;/b&gt;Initialize delimiter value by comma (,). We can user delimiter other than comma.&lt;/li&gt;&lt;li&gt;Line 98:&amp;nbsp;&lt;b&gt;if(line == NULL) return FAIL; &lt;/b&gt;If the input character buffer value is null, it will return fail flag.&lt;/li&gt;&lt;li&gt;Line 103:&amp;nbsp;&lt;b&gt;if(*(line + strlen(line)-1) == &#39;\r&#39; || *(line + strlen(line)-1) == &#39;\n&#39;) *(line + strlen(line)-1) = &#39;\0&#39;;&amp;nbsp;&lt;/b&gt;It chop of last char of input if it is a CR or LF (e.g.Windows file loading in Unix env.). It can be removed if sure fgets has removed both CR and LF from end of line.&lt;/li&gt;&lt;li&gt;Line 106: &lt;b&gt;char *cptr = line;&lt;/b&gt; This declares a character pointer and initializes it to point to the start of the line.&lt;/li&gt;&lt;li&gt;Line 111:&amp;nbsp;&lt;b&gt;sFields[fld]=cptr; &lt;/b&gt;This declares a character pointer and initializes it to point to the start of cptr variable. sFields[fld] is a string which represent the column values. At this line we can consider sFields[0] has value of whole line.&amp;nbsp;&lt;/li&gt;&lt;li&gt;Line 112 to 126:&amp;nbsp;&lt;b&gt;while((ch=*cptr) != &#39;\0&#39; &amp;amp;&amp;amp; fld &amp;lt; STU_COL_NUM) &lt;/b&gt;It loop through each character of string cptr until it reaches end of line. Inside while loop, we check opening quote (&quot;), closing quote (&quot;), and comma (,) value in each character and if found will split string by assigning null character (&#39;\0&#39;). Each time adding null character we will increment the index of array sFields and continue loop. At the end array sFields[0] is equal to first column, sFields[1] is equal to second column and so on.&lt;/li&gt;&lt;li&gt;Line 128 to 131: It will verify the number of columns found in the file and the required number of columns.&lt;/li&gt;&lt;li&gt;After reading line successfully, the function ends by returning true flag.&lt;/li&gt;&lt;/ol&gt;&lt;/div&gt;&lt;div&gt;The source code of the above function:&lt;/div&gt;&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
static int  loadStuValues(char *line, char *sFields[STU_COL_NUM]){
    char delim=&#39;,&#39;;
    if(line == NULL)
        return FAIL;

    // chop of last char of input if it is a CR or LF 
    //(e.g.Windows file loading in Unix env.)
    // can be removed if sure fgets has removed both CR 
    //and LF from end of line
    if(*(line + strlen(line)-1) == &#39;\r&#39; || *(line + strlen(line)-1) == &#39;\n&#39;)
        *(line + strlen(line)-1) = &#39;\0&#39;;

    char *cptr = line;
    int fld = 0;
    int inquote = FALSE;
    char ch;

    sFields[fld]=cptr;
    while((ch=*cptr) != &#39;\0&#39; &amp;amp;&amp;amp; fld &amp;lt; STU_COL_NUM){

        if(ch == &#39;&quot;&#39;) {
            if(! inquote){
                sFields[fld]=cptr+1;
            }else {
                *cptr = &#39;\0&#39;;// zero out quote and jump over it
            }
            inquote = ! inquote;
        } else if(ch == delim &amp;amp;&amp;amp; ! inquote){
            *cptr = &#39;\0&#39;;// end of field, null terminate it
            sFields[++fld]=cptr+1;
        }

        cptr++;
    }
    if(fld &amp;gt; STU_COL_NUM-1){
        return FAIL;
    } else if (fld &amp;lt; STU_COL_NUM-1){
        return FAIL;
    }
    return PASS;
}
&lt;/code&gt;&lt;/pre&gt;&lt;div&gt;Second two functions &lt;b&gt;int readBooks();&lt;/b&gt; and &lt;b&gt;static int&amp;nbsp; loadBookValues(char *line, char *lFields[BK_COL_NUM]); &lt;/b&gt;very much similar to above two functions. To understand the code further please follow my youtube video provided below. LoadBookValues and LoadStuValues is exactly same. However, getStudentID function we read only specific student data and assign it to stuProfile structure variable, and readBooks() function read all books data and assign it to array of bk (Book) structure variable. The size of Array of book structure &#39;bk&#39; is allocated dynamically. We will discuss about in next part.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Student login system:&lt;/b&gt;&lt;/div&gt;&lt;div&gt;Student should choose the login in student mode at the start of an application. To login student should provide only student Id. The provided student Id is verified by reading student csv data in getStudentID function. If student Id found in the csv file, application let user to continue. Here, I choose not to use password for students because they will use application basically in read mode to view books details and view books issued to them. Student can&#39;t modify the application data.&lt;/div&gt;&lt;p&gt;&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.codeincodeblock.com/feeds/610605184355750056/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.codeincodeblock.com/2024/06/part-3-library-management-in-c-read.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/610605184355750056'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/610605184355750056'/><link rel='alternate' type='text/html' href='http://www.codeincodeblock.com/2024/06/part-3-library-management-in-c-read.html' title='Part 3: Library management in C| Read Comma Separated Values (CSV) file and Student Login System'/><author><name>Dinesh Subedi</name><uri>http://www.blogger.com/profile/15921581026092958477</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfxMED05n-0aBIoi4kgT-8kSHfpuRf1bFosaVy-JI-vEwMtJr0sNUFF4S2oj2axSo9IfljCyuPc4hieJ0HsUEPnmw7-8Rj6UTcQjG0Mwv0tiPhTTz6ginzbCdi48YU2oQ/s151/CIMG5697.JPG'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzI86h7iBATP-vhxVJGrUtGbiau6Bb4uIXIuE3TrxLj_TLjnKEgaM3ehuzRfLt0sUli_nCiTW-_mt8IGQ66Jk_HRoVh66Cwnz2D0oE_7QRwZF03Mr7GOW1TKrTQy41mnLE4hWSZ39ZTMEpgNj8deMIe9AQ3uTbiSg_g7e70cl0atSizmC9Q321_e1UYKE/s72-w640-h269-c/StudentData.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7720722570285165075.post-8453192354019002306</id><published>2024-06-03T20:34:00.015+10:00</published><updated>2025-03-31T18:59:24.457+11:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C source code"/><category scheme="http://www.blogger.com/atom/ns#" term="Mini projects"/><title type='text'>Part 2: Library management in C | Username/Password Login System and Manage Admin Accounts</title><content type='html'>&lt;p&gt;&lt;b&gt;&lt;a href=&quot;https://www.codeincodeblock.com/2024/06/part-1-library-management-in-c.html&quot;&gt;Previous Page&lt;/a&gt;&amp;nbsp; &lt;/b&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;a href=&quot;https://www.codeincodeblock.com/2024/06/part-3-library-management-in-c-read.html&quot; target=&quot;_blank&quot;&gt;&lt;b&gt;Next Page&lt;/b&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;In this part, we will learn the techniques to implement a username and password login system and manage user accounts.&lt;/p&gt;&lt;p&gt;When a user runs the application for the first time in admin mode, the application requests the user to create an admin account. However, from the second run onwards, the user has to log in using their account details. After logging into admin mode, the user can add or modify multiple admin accounts. To identify the application’s first run, it will check if the admin account file exists in the system. If the file doesn’t exist, then the application calls the create account function. Otherwise, if the file exists, it will call the Admin login function.&lt;/p&gt;&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
int checkFirstLogin(){
    int flag=1;

    fa = fopen(DATA_FILE,&quot;rb&quot;);

    if(fa!= NULL){
        flag= 0;
    }
    fclose(fa);

    return flag;

}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;span&gt;&lt;/span&gt;&lt;/p&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;Source code of function to create account:&lt;p&gt;&lt;/p&gt;&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
void createAccount(){

    char passV[MAX_PWD_SZ];
    struct password pd;

    printWelcomeMsg();

    gotoxy(35,8);
    printf(&quot;Please Enter New Username and Password.&quot;);
    gotoxy(35,10);
    printf(&quot;New User Name: &quot;);
    getString(pd.userName,MAX_USR_SZ);
    gotoxy(35,11);
    printf(&quot;New Password: &quot;);
    getPassword(pd.password,MAX_PWD_SZ);
    gotoxy(35,12);
    printf(&quot;Re-type Password: &quot;);
    getPassword(passV,MAX_PWD_SZ);


    if(strcmp(passV,pd.password)==0){

        add(pd);

        printWelcomeMsg();

        gotoxy(35,8);
        printf(&quot;Congratulation! User account created.&quot;);
        gotoxy(35,10);
        printf(&quot;Please press any key to continue and log in.&quot;);
        if(getch()){
            adminLogin();
        }

    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;In the above code, it gets the username and password details from the user and saves them in a file. The most interesting part of this code is that it hides the password entered by the user. It displays an asterisk (*) instead of the actual character to hide the password. The user can even delete entered characters before confirming. The task of password hiding is performed by the function getPassword(), which is shown below.&lt;/p&gt;&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
static void getPassword(char *buff, size_t sz){

    char ch;
    int i=0;

    while(ch!=13 &amp;amp;&amp;amp; i!=sz)
    {
        ch=getch();

        if(ch==8 &amp;amp;&amp;amp; i&amp;gt;0){
            printf(&quot;\b \b&quot;);
            i--;
            buff[i]=&#39;\0&#39;;
        }else if(ch!=13 &amp;amp;&amp;amp; ch!=8){

            putch(&#39;*&#39;);
            buff[i] = ch;
            i++;
        }
    }

    buff[i]=&#39;\0&#39;;
    ch=&#39; &#39;;i=0;
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;In above code, it reads user character using getch() function, display Asterix (*) using putch() function, and remove the character from the screen by printing backspace, space and backspace (printf(&quot;\b \b&quot;)). While loop is used to read multiple characters.&lt;/p&gt;&lt;p&gt;After getting username and password details from the user, we will call add() function inside create account function to save user account details in C file.&lt;/p&gt;&lt;p&gt;Now, we will create admin login function. Source code is given below:&lt;/p&gt;&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
void adminLogin(){

    struct password pd;

    printWelcomeMsg();

    gotoxy(35,8);
    printf(&quot;Please Enter Username and Password.&quot;);
    gotoxy(35,10);
    printf(&quot;User Name: &quot;);
    getString(pd.userName,MAX_USR_SZ);
    gotoxy(35,11);
    printf(&quot;Password: &quot;);
    getPassword(pd.password,MAX_PWD_SZ);

    if(check(pd,0)==1){

        printWelcomeMsg();

        gotoxy(35,10);
        printf(&quot;Login Successfull.&quot;);
        gotoxy(35,13);
        printf(&quot;Please press any key to continue.&quot;);
        if(getch()){
            adminMenu();
        }
    } else {

        printWelcomeMsg();

        gotoxy(35,10);
        printf(&quot;Sorry! Username or Password do not match.&quot;);
        gotoxy(35,13);
        printf(&quot;Please press any key to re-login.&quot;);
        if(getch()){
            adminLogin();
        }
    }
}&lt;span style=&quot;font-family: Times New Roman;&quot;&gt;&lt;span style=&quot;white-space: normal;&quot;&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;In the above code, it gets the username and password, and checks the details in the system using the check() function. The check function reads the user account details from the file and compares them with the details provided by the user. If the user account exists, then it will take the user to the adminMenu() screen. Otherwise, it will request the user to log in again.&lt;/p&gt;&lt;p&gt;From the admin menu, the user can add, modify, view, and delete admin accounts by selecting option A. We will not discuss the function which gets details from the user or displays details on the screen. The source code of the function given below will read or modify data from the C file where the user account details are stored.&lt;/p&gt;&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;

#define DATA_FILE &quot;adminAccess.dat&quot;
#define TEMP_FILE &quot;tempFile.dat&quot;

//Read data from file

int check(struct password d,int flag){

    struct password a;
    int i=0;
    fp = fopen(DATA_FILE,&quot;rb&quot;);
    while(fread(&amp;amp;a,sizeof(a),1,fp)==1){
        if(flag==0){
            if(strcmp(a.userName,d.userName)==0 &amp;amp;&amp;amp; 
            strcmp(a.password,d.password)==0){
                i=1;
                break;
            }
        } else if (flag==1){
            if(strcmp(a.userName,d.userName)==0){
                i=1;
                break;
            }
        }
    }
    fclose(fp);
    return i;
}

//Read data from file
int view(struct password d[], int sz){

    struct password a;
    int i=0;
    fp = fopen(DATA_FILE,&quot;rb&quot;);
    while(fread(&amp;amp;a,sizeof(a),1,fp)==1 &amp;amp;&amp;amp; i&amp;lt;sz){
        d[i]=a;
        i++;
    }
    fclose(fp);
    return i;
}

//Add data into the file
void add(struct password d){

    fp = fopen(DATA_FILE,&quot;ab+&quot;);
    fseek(fp,0,SEEK_END);
    fwrite(&amp;amp;d,sizeof(d),1,fp);
    fclose(fp);
}


//Update data into the file
int update(struct password d){

    struct password a;
    int flag=0;

    fp=fopen(DATA_FILE,&quot;rb+&quot;);

    while(fread(&amp;amp;a,sizeof(a),1,fp)==1){
        if(strcmp(a.userName, d.userName)==0){
            fseek(fp,ftell(fp)-sizeof(a),0);
            fwrite(&amp;amp;d,sizeof(d),1,fp);
            fclose(fp);
            flag=1;
        }
    }
    fclose(fp);

    return flag;
}

//Delete data from the file
int del(char *userName){

    struct password a;
    int flag=0;

    fp=fopen(DATA_FILE,&quot;rb+&quot;);
    ft=fopen(TEMP_FILE,&quot;wb+&quot;);

    while(fread(&amp;amp;a,sizeof(a),1,fp)==1){
        if(strcmp(userName, a.userName)!=0){
            fwrite(&amp;amp;a,sizeof(a),1,ft);
        } else {
            flag=1;
        }
    }

    fclose(ft);
    fclose(fp);

    remove(DATA_FILE);
    rename(TEMP_FILE,DATA_FILE);

    return flag;

}

&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Above source code is reused from the project Contact Management. It will read, add, modify, and delete data from the file using C file handling functions. Please follow &lt;a href=&quot;https://www.codeincodeblock.com/2011/09/contacts-manager-mini-project-in-c-with.html&quot; target=&quot;_blank&quot;&gt;Contact Management&lt;/a&gt; project to understand the source code.&amp;nbsp;&lt;/p&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;iframe allowfullscreen=&quot;&quot; class=&quot;BLOG_video_class&quot; height=&quot;266&quot; src=&quot;https://www.youtube.com/embed/8DvPY4oScMc&quot; width=&quot;320&quot; youtube-src-id=&quot;8DvPY4oScMc&quot;&gt;&lt;/iframe&gt;&lt;/div&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.codeincodeblock.com/feeds/8453192354019002306/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.codeincodeblock.com/2024/06/part-2-library-management-in-c.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/8453192354019002306'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/8453192354019002306'/><link rel='alternate' type='text/html' href='http://www.codeincodeblock.com/2024/06/part-2-library-management-in-c.html' title='Part 2: Library management in C | Username/Password Login System and Manage Admin Accounts'/><author><name>Dinesh Subedi</name><uri>http://www.blogger.com/profile/15921581026092958477</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfxMED05n-0aBIoi4kgT-8kSHfpuRf1bFosaVy-JI-vEwMtJr0sNUFF4S2oj2axSo9IfljCyuPc4hieJ0HsUEPnmw7-8Rj6UTcQjG0Mwv0tiPhTTz6ginzbCdi48YU2oQ/s151/CIMG5697.JPG'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://img.youtube.com/vi/8DvPY4oScMc/default.jpg" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7720722570285165075.post-6655834051933004501</id><published>2024-06-03T20:33:00.007+10:00</published><updated>2025-03-31T18:59:15.458+11:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C source code"/><category scheme="http://www.blogger.com/atom/ns#" term="Mini projects"/><title type='text'>Part 1: Library management in C | Flowchart and Function Stack Call Diagram</title><content type='html'>&lt;p&gt;&lt;a href=&quot;https://www.codeincodeblock.com/2011/03/mini-project-library-management-in-c.html&quot;&gt;&lt;b&gt;Previous Page&lt;/b&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;b&gt;&amp;nbsp;&lt;a href=&quot;https://www.codeincodeblock.com/2024/06/part-2-library-management-in-c.html&quot;&gt;Next Page&lt;/a&gt;&lt;/b&gt;&lt;/p&gt;&lt;p&gt;The application is represented by three mainMenu, adminMenu and studentMenu flowchart. The mainMenu flowchart represents the options provided to the user to choose application mode and user security. The adminMenu flowchart represents the all the tasks that administrator can perform, and the studentMenu flowchart represents the tasks that students can perform.&lt;/p&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj9tWR7rMdBV1hn5FhBE0Ro8uM_IMpHZY0adLopZHQipibUswBar1aYWM4VUXQvKNUPPC17A6MIQDWk9lHja56girlbc2BhVT3fSIt0Us8x1GkAGwy7slqSHEVoHHnC2OEuLj250w3ZlO4U7ju_PozkdRYUyQoF__Lvi_F6p9EDHdMOIo1BzSYHAALOIpo/s961/MainMenu.jpg&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Main Menu flowchart&quot; border=&quot;0&quot; data-original-height=&quot;961&quot; data-original-width=&quot;600&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj9tWR7rMdBV1hn5FhBE0Ro8uM_IMpHZY0adLopZHQipibUswBar1aYWM4VUXQvKNUPPC17A6MIQDWk9lHja56girlbc2BhVT3fSIt0Us8x1GkAGwy7slqSHEVoHHnC2OEuLj250w3ZlO4U7ju_PozkdRYUyQoF__Lvi_F6p9EDHdMOIo1BzSYHAALOIpo/s16000/MainMenu.jpg&quot; title=&quot;Main Menu flowchart&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;p&gt;&lt;b&gt;&lt;span&gt;&lt;/span&gt;&lt;/b&gt;&lt;/p&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;b&gt;Explanation of Main Menu flowchart:&lt;/b&gt;&lt;p&gt;&lt;/p&gt;&lt;p&gt;&lt;b&gt;Start:&lt;/b&gt; The process begins here.&lt;/p&gt;&lt;p&gt;&lt;b&gt;Main User Menu:&lt;/b&gt; The application displays the user menu to select the mode of the application.&lt;/p&gt;&lt;p&gt;&lt;b&gt;Admin or Student?:&lt;/b&gt; This is the decision point where the user can choose either Admin mode or Student mode. The general idea is that library staff will choose Admin mode and students will choose Student mode.&lt;/p&gt;&lt;p&gt;&lt;b&gt;Student Login:&lt;/b&gt; If the user is a Student, the application requests the user to log in by providing their student ID.&lt;/p&gt;&lt;p&gt;&lt;b&gt;Exist?:&lt;/b&gt; The application checks if the student exists in the system. If the student ID exists, the process moves to the Student Menu Process. If the student ID does not exist, the application requests the user to enter it again.&lt;/p&gt;&lt;p&gt;&lt;b&gt;Student Menu Process:&lt;/b&gt; This is a sub-process of the application. This process executes the application in Student mode. It is represented by the Student Menu flowchart.&lt;/p&gt;&lt;p&gt;&lt;b&gt;Setup?:&lt;/b&gt; If the user is an Admin, the application checks if it is the first run (setup) of the application.&lt;/p&gt;&lt;p&gt;&lt;b&gt;Create Account:&lt;/b&gt; If the application is running for the first time, the application requests the user to create the first admin account by providing a username and password.&lt;/p&gt;&lt;p&gt;&lt;b&gt;Admin Login:&lt;/b&gt; The application moves to the Admin login screen if an admin account already exists.&lt;/p&gt;&lt;p&gt;&lt;b&gt;Exist?:&lt;/b&gt; The application checks if the admin user account exists in the system. If the admin account exists, the process moves to the Admin Menu Process. If the admin account does not exist, the application will request the user to enter the details again.&lt;/p&gt;&lt;p&gt;&lt;b&gt;Admin Menu Process:&lt;/b&gt; This is a sub-process of the application. This process executes the application in Admin mode. It is represented by the Admin Menu flowchart.&lt;/p&gt;&lt;p&gt;&lt;b&gt;End:&lt;/b&gt; End of the application.&lt;/p&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi4lJTyv6uW5DHcIqwsYqKzdKDJb3TyqcRFyRBlMY_k2ZAf-cqVBXBifgrP2Ch-9U7o0HUV6TFQSo9RhRpX3NGy7sdGv0UgJbkAlYG12BCsWI6GOL65KTtN1IawDqLY3lV9aFwct_FddK5a0xSDgpB9KSRwVMVyxgTznSOhX2GXyu31nnjUk_uYcR7wlVA/s1051/AdminMenu.jpg&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Admin Menu Flowchart&quot; border=&quot;0&quot; data-original-height=&quot;1051&quot; data-original-width=&quot;521&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi4lJTyv6uW5DHcIqwsYqKzdKDJb3TyqcRFyRBlMY_k2ZAf-cqVBXBifgrP2Ch-9U7o0HUV6TFQSo9RhRpX3NGy7sdGv0UgJbkAlYG12BCsWI6GOL65KTtN1IawDqLY3lV9aFwct_FddK5a0xSDgpB9KSRwVMVyxgTznSOhX2GXyu31nnjUk_uYcR7wlVA/s16000/AdminMenu.jpg&quot; title=&quot;Admin Menu Flowchart&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;p&gt;&lt;b&gt;Explanation of Admin Menu flowchart:&lt;/b&gt;&lt;/p&gt;&lt;p&gt;&lt;b&gt;Start:&lt;/b&gt; The Admin process begins here.&lt;/p&gt;&lt;p&gt;&lt;b&gt;Admin Menu:&lt;/b&gt; The application displays the admin menu to select the task to perform. User can select task by input key A, B, C, D, E or Esc.&lt;/p&gt;&lt;p&gt;&lt;b&gt;All Decision Points:&lt;/b&gt; If user input A, application takes user to Add/Modify Admin Account task menu, else if user input B, application takes user to Add/Modify Books info task menu, else if user input C, application takes user to issued or Return Books task menu, else if user input D, application takes user to search Books task, else if E or ESC applicaiton will end.&lt;/p&gt;&lt;p&gt;&lt;b&gt;Add/Modify Admin Account:&lt;/b&gt; User can view, add, update and delete admin account.&lt;/p&gt;&lt;p&gt;&lt;b&gt;Add/Modify Books Info:&lt;/b&gt; User can view, add, update and delete books data.&lt;/p&gt;&lt;p&gt;&lt;b&gt;Issued or Return Books:&lt;/b&gt; User can issue books to the students and update returned books.&lt;/p&gt;&lt;p&gt;&lt;b&gt;Student Menu Process:&lt;/b&gt; This is a sub-process of the application. This process executes the application in Student mode. It is represented by the Student Menu flowchart.&lt;/p&gt;&lt;p&gt;&lt;b&gt;Search Books:&lt;/b&gt; User can search books by proving book ID.&lt;/p&gt;&lt;p&gt;&lt;b&gt;End:&lt;/b&gt; End of the application.&lt;/p&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiqnKfqGuYpkrZm0v3TWsVybNZ0yPFsGPKOZFBYyqSf5gVQJDPK6R5zhIqADJhaexKNxX2_L11VByxwLbkI5bmqQmdikWgl0oJIoLkjGWuz8sMbwE4mUBwRhgDSu3NnXu_NWKx0D0G3cqFbMmDbDeYscmPTqz548zrBJtXQ5euCPAfj_9W59Yg6LatF0yc/s961/StudentMenu.jpg&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Student Menu Flowchart&quot; border=&quot;0&quot; data-original-height=&quot;961&quot; data-original-width=&quot;521&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiqnKfqGuYpkrZm0v3TWsVybNZ0yPFsGPKOZFBYyqSf5gVQJDPK6R5zhIqADJhaexKNxX2_L11VByxwLbkI5bmqQmdikWgl0oJIoLkjGWuz8sMbwE4mUBwRhgDSu3NnXu_NWKx0D0G3cqFbMmDbDeYscmPTqz548zrBJtXQ5euCPAfj_9W59Yg6LatF0yc/s16000/StudentMenu.jpg&quot; title=&quot;Student Menu Flowchart&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;p&gt;&lt;b&gt;Explanation of Student Menu flowchart:&lt;/b&gt;&lt;/p&gt;&lt;p&gt;&lt;b&gt;Start: &lt;/b&gt;The student process begins here.&lt;/p&gt;&lt;p&gt;&lt;b&gt;Student Menu:&lt;/b&gt; The application displays the student menu to select the task to perform. User can select task by input key A, B, C, D or Esc.&lt;/p&gt;&lt;p&gt;&lt;b&gt;All Decision Points:&lt;/b&gt; If user input A, application takes user to search books task, else if user input B, application takes user to view all books, else if user input C, application takes user to view issued or Returned Books, else if user input D or ESC applicaiton will end.&lt;/p&gt;&lt;p&gt;&lt;b&gt;Search Books:&lt;/b&gt; User can search books by proving book ID.&lt;/p&gt;&lt;p&gt;&lt;b&gt;View All Books:&lt;/b&gt; User can view all books avaiable in the library.&lt;/p&gt;&lt;p&gt;&lt;b&gt;View My Issued Books:&lt;/b&gt; User can view issued and returned books.&lt;/p&gt;&lt;p&gt;&lt;b&gt;End:&lt;/b&gt; End of the application.&lt;/p&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiEPupy1FY7SDLUZCMJBsfSPgOu7OC16iOSkup2-8RvqW73D5GsyLTr_ljcWvq-EI8VPyo3i3HY-MW7bHxUsKs2eK51pdJHTC8RVeYbkpJV52D1UO5uG_SIR86OSv91ZdxhLgGT-Ja-hBI5dirXszoI5yvYqpEsQxevwWAUCJEmnt9Q7qP-o_cyzL9VELw/s1011/Function_Call_Diagram.jpg&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Function Stack Call Diagram&quot; border=&quot;0&quot; data-original-height=&quot;791&quot; data-original-width=&quot;1011&quot; height=&quot;501&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiEPupy1FY7SDLUZCMJBsfSPgOu7OC16iOSkup2-8RvqW73D5GsyLTr_ljcWvq-EI8VPyo3i3HY-MW7bHxUsKs2eK51pdJHTC8RVeYbkpJV52D1UO5uG_SIR86OSv91ZdxhLgGT-Ja-hBI5dirXszoI5yvYqpEsQxevwWAUCJEmnt9Q7qP-o_cyzL9VELw/w640-h501/Function_Call_Diagram.jpg&quot; title=&quot;Function Stack Call Diagram&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;p&gt;Above is the function call stack diagram. It is different from a flowchart. A flowchart helps to represent application flow, business cases, and user interactions. It helps to explain application features to non-technical business users. However, in the function call stack diagram, you will find the link between the functions within the application source code. It helps technical users or developers to understand the application source code.&lt;/p&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;iframe allowfullscreen=&quot;&quot; class=&quot;BLOG_video_class&quot; height=&quot;266&quot; src=&quot;https://www.youtube.com/embed/71g2ZdDeQwo&quot; width=&quot;320&quot; youtube-src-id=&quot;71g2ZdDeQwo&quot;&gt;&lt;/iframe&gt;&lt;/div&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.codeincodeblock.com/feeds/6655834051933004501/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.codeincodeblock.com/2024/06/part-1-library-management-in-c.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/6655834051933004501'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/6655834051933004501'/><link rel='alternate' type='text/html' href='http://www.codeincodeblock.com/2024/06/part-1-library-management-in-c.html' title='Part 1: Library management in C | Flowchart and Function Stack Call Diagram'/><author><name>Dinesh Subedi</name><uri>http://www.blogger.com/profile/15921581026092958477</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfxMED05n-0aBIoi4kgT-8kSHfpuRf1bFosaVy-JI-vEwMtJr0sNUFF4S2oj2axSo9IfljCyuPc4hieJ0HsUEPnmw7-8Rj6UTcQjG0Mwv0tiPhTTz6ginzbCdi48YU2oQ/s151/CIMG5697.JPG'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj9tWR7rMdBV1hn5FhBE0Ro8uM_IMpHZY0adLopZHQipibUswBar1aYWM4VUXQvKNUPPC17A6MIQDWk9lHja56girlbc2BhVT3fSIt0Us8x1GkAGwy7slqSHEVoHHnC2OEuLj250w3ZlO4U7ju_PozkdRYUyQoF__Lvi_F6p9EDHdMOIo1BzSYHAALOIpo/s72-c/MainMenu.jpg" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7720722570285165075.post-2898123444622336287</id><published>2023-11-03T10:36:00.004+11:00</published><updated>2025-03-31T18:59:02.428+11:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C source code"/><category scheme="http://www.blogger.com/atom/ns#" term="Mini projects"/><title type='text'>Chapter 2: Contact Management in C | File Handling</title><content type='html'>&lt;p&gt;&lt;a href=&quot;https://www.codeincodeblock.com/2023/11/chapter-1-contact-management-in-c-flow.html&quot; target=&quot;_blank&quot;&gt;&amp;nbsp;&amp;lt;&amp;lt;Previous Chapter&lt;/a&gt;&lt;/p&gt;&lt;p&gt;If you remember we have categoried all the functions into two types user functions and operational functions. Here I will explain the operational function and its usage in user functions one by one.&lt;/p&gt;&lt;p&gt;First, let&#39;s define Variables and Data Structure.&lt;/p&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
// Define Constant Variables
#define ESC 27
#define MAX_NAME_SZ 15
#define MAX_NUM_SZ 25
#define READ_ARRAY_SZ 15
#define DATA_FILE &quot;dataFile.dat&quot;
#define TEMP_FILE &quot;tempFile.dat&quot;

//Define data structure

struct data{
    char fName[MAX_NAME_SZ];
    char lName[MAX_NAME_SZ];
    char mPhone[MAX_NUM_SZ];
    char wPhone[MAX_NUM_SZ];
    char hPhone[MAX_NUM_SZ];
};
&lt;/code&gt;&lt;/pre&gt;&lt;div&gt;We will use struct data types to store contact information. It has only five fields First Name (fName), Last Name (lName), Mobile Phone (mPhone), Work Phone (wPhone), Home Phone (hPhone), and all these variables are char types. We can&#39;t set primary key as in database but we will choose Mobile Phone i.e mPhone as a primary key and will make sure that Mobile Phone number will not be a null value or duplicate while adding data into the file.&lt;/div&gt;&lt;div style=&quot;font-weight: bold;&quot;&gt;&lt;span&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;/span&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;&lt;b&gt;Function getString(): &lt;/b&gt;This function reads the data from the buffer and puts data into the array. You might think that scanf() function is very easy compared to this. Yes, you are true but there are problems with scanf() function. It does not clear the overflow value from the buffer. For example a user might input 20 long characters for the first name, but the size of the first name array is just 15 so remaining 5 characters will remain in the buffer. In the next use of scanf() function, it will read the previous remaining characters and you will get incorrect data. The scanf() function is useful only if you are sure about the input value.&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
//Get string input from user
static void getString(char *buff, size_t sz){

    fgets(buff,sz, stdin);
    if ((strlen(buff) &amp;gt; 0) &amp;amp;&amp;amp; (buff[strlen (buff) - 1] == &#39;\n&#39;))
        buff[strlen (buff) - 1] = &#39;\0&#39;;

    fflush(stdin);
}
&lt;/code&gt;&lt;/pre&gt;&lt;b&gt;Function readData(): &lt;/b&gt;This is a user function. It will interact with the user to get contact information. In the below code, you can see, it displays message using printf function and read input value using getString function which we have discussed above. After reading data, it will return the struct data type variable &#39;c&#39;.&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
//Function to read contact data
struct data readData(){
    struct data c;

    gotoxy(35,11);
    printf(&quot;Enter first name: &quot;);
    getString(c.fName,sizeof(c.fName));

    gotoxy(35,12);
    printf(&quot;Enter last name: &quot;);
    getString(c.lName,sizeof(c.lName));

    gotoxy(35,13);
    printf(&quot;Enter mobile phone: &quot;);
    getString(c.mPhone,sizeof(c.mPhone));

    gotoxy(35,14);
    printf(&quot;Enter work phone: &quot;);
    getString(c.wPhone,sizeof(c.wPhone));

    gotoxy(35,15);
    printf(&quot;Enter home phone: &quot;);
    getString(c.hPhone,sizeof(c.hPhone));

    return c;
}&amp;nbsp;&lt;/code&gt;&lt;/pre&gt;&lt;div&gt;&lt;b&gt;Declare File Pointers: &lt;/b&gt;Now let&#39;s&amp;nbsp;declare the file pointers, and use these pointers to create files. Both pointers are required, you will find it in the code somewhere below.&lt;/div&gt;&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;//File pointers
FILE *fp, *ft;&lt;b&gt;
&lt;/b&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;div style=&quot;font-weight: bold;&quot;&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;&lt;b&gt;Function&amp;nbsp;add(): &lt;/b&gt;This is an operational function that adds the data into the file. Adding data into the file is very simple. First, open the file using file pointer fp in ab+ mode which is for both reading and appending data in binary mode. There are many opening modes in C, please google about it to study in detail. After opening the file, the fseek function will move the cursor always at the end of the file so that data will not get overridden. The function fwrite writes the data into the file in a block of size equal to the size of 5 char variables inside the struct.&lt;div&gt;At last, the file is closed using fclose function.&lt;br /&gt;&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
//Add data into the file
void add(struct data d){

    fp = fopen(DATA_FILE,&quot;ab+&quot;);
    fseek(fp,0,SEEK_END);
    fwrite(&amp;amp;d,sizeof(d),1,fp);
    fclose(fp);
}&amp;nbsp;&lt;/code&gt;&lt;/pre&gt;&lt;b&gt;Function&amp;nbsp;searchByNum(): &lt;/b&gt;This function searches the numbers in the file from top to bottom one by one. If a number, passed in the function parameter is found then it will return 1 otherwise it will return 0.&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
//Search mobile number in the file
int searchByNum(char *num){

    struct data a;
    int i=0;
    if(strcmp(num,&quot;&quot;)==0){
        i=2;
    } else {
        fp = fopen(DATA_FILE,&quot;rb&quot;);
        while(fread(&amp;amp;a,sizeof(a),1,fp)==1){
            if(strcmp(num, a.mPhone)==0){
                i=1; //return 1 if found
            }
        }
        fclose(fp);
    }

    return i; //return 0 if not found
}&amp;nbsp;&lt;/code&gt;&lt;/pre&gt;&lt;b&gt;Function&amp;nbsp;addItems(): &lt;/b&gt;This function interacts with the user to get input data. After getting data, it checks the phone number in the file. If it exits will not add data and request the user to go back to update data. If it does not exist then it calls the add() function to save the data into the file that we had discussed above. At last, it allows the user to add another item or exit the function.&amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
//Add contacts
void addItems(){

    struct data c;

    system(&quot;cls&quot;);
    gotoxy(35,6);
    printf(&quot;----Welcome to Contact Management System----&quot;);
    gotoxy(35,8);
    printf(&quot;Please enter details:&quot;);

    c = readData();
    if(searchByNum(c.mPhone)==2){
        gotoxy(35,16);
        printf(&quot;Mobile number is empty. Record can&#39;t be saved.&quot;);
    } else if(searchByNum(c.mPhone)==1){
        gotoxy(35,16);
        printf(&quot;Mobile number %s exist. Please go back to update.&quot;,c.mPhone);
    } else {
        add(c);
        gotoxy(35,17);
        printf(&quot;Record Successfully Saved.&quot;);
    }
    gotoxy(35,27);
    printf(&quot;Please press any key to continue or enter ESC key to go back.&quot;);
    if(getch()==ESC){
        mainMenu();
    } else {
        addItems();
    }
}&amp;nbsp;&lt;/code&gt;&lt;/pre&gt;&lt;b&gt;Function&amp;nbsp;view(): &lt;/b&gt;This function reads the data from the file and stores the data into the array of structure data a.&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
//Read data from file
int view(struct data d[], int sz){

    struct data a;
    int i=0;
    fp = fopen(DATA_FILE,&quot;rb&quot;);
    while(fread(&amp;amp;a,sizeof(a),1,fp)==1 &amp;amp;&amp;amp; i&amp;lt;sz){
        d[i]=a;
        i++;
    }
    fclose(fp);
    return i;
}

&lt;/code&gt;&lt;/pre&gt;
  
  &lt;b&gt;Function&amp;nbsp;viewItems(): &lt;/b&gt;This function gets the data from the view() function that we discussed above and displays the contact information in a tabular form. However, this function displays only 15 items only, due to the limitation of console windows size. You can implement a pagination feature to display the remaining items on the next page. I will add this feature in my next tutorials.&amp;nbsp;&amp;nbsp;&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
//Display contacts only 15 items
void viewItems(){

    struct data c[READ_ARRAY_SZ];
    int data_sz=0;
    data_sz = view(c,READ_ARRAY_SZ);

    system(&quot;cls&quot;);
    gotoxy(35,6);
    printf(&quot;----Welcome to Contact Management System----&quot;);
    gotoxy(35,8);
    printf(&quot;View Contact function selected %d&quot;,data_sz);


    gotoxy(15,10);
    printf(&quot;First Name&quot;);
    gotoxy(35,10);
    printf(&quot;Last Name&quot;);
    gotoxy(55,10);
    printf(&quot;Mobile Number&quot;);
    gotoxy(70,10);
    printf(&quot;Work Number&quot;);
    gotoxy(85,10);
    printf(&quot;Home Number&quot;);
    for (int i=0;i&lt;data_sz back.=&quot;&quot; c=&quot;&quot; code=&quot;&quot; else=&quot;&quot; enter=&quot;&quot; esc=&quot;&quot; fname=&quot;&quot; getch=&quot;&quot; go=&quot;&quot; gotoxy=&quot;&quot; hphone=&quot;&quot; i=&quot;&quot; if=&quot;&quot; key=&quot;&quot; lease=&quot;&quot; lname=&quot;&quot; mainmenu=&quot;&quot; mphone=&quot;&quot; printf=&quot;&quot; s=&quot;&quot; to=&quot;&quot; viewitems=&quot;&quot; wphone=&quot;&quot;&gt;&lt;/data_sz&gt;&lt;/code&gt;&lt;/pre&gt;&lt;b&gt;Function&amp;nbsp;update(): &lt;/b&gt;To update the existing data, we first search for the old mobile number in the file. After finding the mobile number in the file it rewinds the file cursor just by 1 block of data using fseek function. You can check the logic below. After rewinding the cursor by 1 block, we will overwrite the data with the new value.&lt;/div&gt;&lt;div&gt;&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
//Update data into the file
void update(struct data d, char *oldNumber){

    struct data a;

    fp=fopen(DATA_FILE,&quot;rb+&quot;);

    while(fread(&amp;amp;a,sizeof(a),1,fp)==1){
        if(strcmp(oldNumber, a.mPhone)==0){
            fseek(fp,ftell(fp)-sizeof(a),0);
            fwrite(&amp;amp;d,sizeof(d),1,fp);
            fclose(fp);
        }
    }

}&amp;nbsp;&lt;/code&gt;&lt;/pre&gt;&lt;b&gt;Function&amp;nbsp;updateItems(): &lt;/b&gt;This function asks users to input the mobile number that they want to update. It searches the number in the file, and if found then it will ask the user for new contact information and pass the value into the update function which we have discussed above. If a number does not exist in the file, it simply requests the user to continue searching for another number or go back.&amp;nbsp;&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
//Update contact details
void updateItems(){

    char pNum[MAX_NUM_SZ];
    struct data c;
    system(&quot;cls&quot;);
    gotoxy(35,6);
    printf(&quot;----Welcome to Contact Management System----&quot;);
    gotoxy(35,7);
    printf(&quot;Please enter the Mobile Phone that you want to update details&quot;);
    gotoxy(35,9);
    printf(&quot;Enter Mobile Phone:&quot;);
    getString(pNum,sizeof(pNum));

    if(searchByNum(pNum)==1){
        gotoxy(35,10);
        printf(&quot;Mobile number %s exist. Please enter new details.&quot;,pNum);
        c=readData();
        update(c,pNum);
    } else {
        gotoxy(35,11);
        printf(&quot;Mobile number %s do not exist.&quot;,pNum);
    }
    gotoxy(35,27);
    printf(&quot;Please enter any key to continue or enter ESC key to go back.&quot;);
    if(getch()==ESC){
        mainMenu();
    } else {
        updateItems();
    }
}&amp;nbsp;&lt;/code&gt;&lt;/pre&gt;&lt;b&gt;Function&amp;nbsp;del(): &lt;/b&gt;This is the most interesting function among all the functions we created. I like the logic that we are using to delete files. Actually, we don&#39;t have any function to delete data from the file directly because once we allocate a block of data in a file it is not possible to remove that block of data. So in the below function, we copy all the data from the source file to the target file except the data that we want to delete. It is more like shifting memory blocks from one file to another file. After copying all the data we delete the source file and rename the target file as the source file name.&amp;nbsp;&lt;/div&gt;&lt;div&gt;However, this technique is not efficient if the data size is huge. For huge data file, we have to find different techniques that I will leave with you for now.&lt;br /&gt;&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
//Delete data from the file
void del(char *delNumber){

    struct data a;

    fp=fopen(DATA_FILE,&quot;rb+&quot;);
    ft=fopen(TEMP_FILE,&quot;wb+&quot;);

    while(fread(&amp;amp;a,sizeof(a),1,fp)==1){
        if(strcmp(delNumber, a.mPhone)!=0){
            fwrite(&amp;amp;a,sizeof(a),1,ft);
        }
    }

    fclose(ft);
    fclose(fp);

    remove(DATA_FILE);
    rename(TEMP_FILE,DATA_FILE);

}&amp;nbsp;&lt;/code&gt;&lt;/pre&gt;&lt;b&gt;Function&amp;nbsp;deleteItems(): &lt;/b&gt;This function requests the mobile phone number that the user wants to delete. It searches the data in the file if it exists then it deletes the data by calling del() function, if not it requests the user to continue for another number or go back.&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
//Delete contacts details
void deleteItems(){

    char pNum[MAX_NUM_SZ];
    char choice;
    system(&quot;cls&quot;);
    gotoxy(35,6);
    printf(&quot;----Welcome to Contact Management System----&quot;);
    gotoxy(35,7);
    printf(&quot;Please enter the Mobile Phone that you want to delete&quot;);
    gotoxy(35,9);
    printf(&quot;Enter Mobile Phone:&quot;);
    getString(pNum,sizeof(pNum));

    if(searchByNum(pNum)==1){
        gotoxy(35,12);
        printf(&quot;Mobile number %s exist. Do you want to delete it?.&quot;,pNum);
        gotoxy(35,14);
        printf(&quot;Please press y to delete or any key to skip.&quot;);
        choice=tolower(getch());
        if(choice==&#39;y&#39;){
            del(pNum);
            gotoxy(35,16);
            printf(&quot;Phone number successfully deleted.&quot;);
        }

    } else {
        gotoxy(35,12);
        printf(&quot;Mobile number %s do not exist.&quot;,pNum);
    }

    gotoxy(35,27);
    printf(&quot;Please enter any key to continue or enter ESC key to go back.&quot;);

    if(getch()==ESC){
        mainMenu();
    } else {
        deleteItems();
    }
}
&lt;/code&gt;&lt;/pre&gt;

This is the end of the code. I hope you have understood the logic implemented in the application. Please go back to the project&#39;s main page to download source code&amp;nbsp;&lt;a href=&quot;https://www.codeincodeblock.com/2011/09/contacts-manager-mini-project-in-c-with.html&quot; target=&quot;_blank&quot;&gt;Project Main Page&lt;/a&gt;.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;You can also watch a video about this project on YouTube.&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;iframe allowfullscreen=&quot;&quot; class=&quot;BLOG_video_class&quot; height=&quot;266&quot; src=&quot;https://www.youtube.com/embed/K0oLBbzrZ2I&quot; width=&quot;320&quot; youtube-src-id=&quot;K0oLBbzrZ2I&quot;&gt;&lt;/iframe&gt;&lt;/div&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.codeincodeblock.com/feeds/2898123444622336287/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.codeincodeblock.com/2023/11/chapter-2-contact-management-in-c-file.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/2898123444622336287'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/2898123444622336287'/><link rel='alternate' type='text/html' href='http://www.codeincodeblock.com/2023/11/chapter-2-contact-management-in-c-file.html' title='Chapter 2: Contact Management in C | File Handling'/><author><name>Dinesh Subedi</name><uri>http://www.blogger.com/profile/14592859300444169698</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://img.youtube.com/vi/K0oLBbzrZ2I/default.jpg" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7720722570285165075.post-1225966000200451074</id><published>2023-11-01T20:05:00.004+11:00</published><updated>2025-03-31T18:58:53.966+11:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C source code"/><category scheme="http://www.blogger.com/atom/ns#" term="Mini projects"/><title type='text'>Chapter 1: Contact Management in C | Flow Chart and Functions</title><content type='html'>&lt;p style=&quot;text-align: left;&quot;&gt;&lt;a href=&quot;https://www.codeincodeblock.com/2011/09/contacts-manager-mini-project-in-c-with.html&quot; target=&quot;_blank&quot;&gt;&amp;lt;&amp;lt;Previous Chapter&lt;/a&gt;&amp;nbsp; &amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&lt;a href=&quot;https://www.codeincodeblock.com/2023/11/chapter-2-contact-management-in-c-file.html&quot; target=&quot;_blank&quot;&gt;Next Chapter&amp;gt;&amp;gt;&lt;/a&gt;&amp;nbsp;&lt;/p&gt;&lt;p&gt;&lt;b&gt;Application Flow Chart:&lt;/b&gt;&lt;/p&gt;&lt;p&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/p&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;b&gt;&lt;/b&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEidX8xK8FCqP7AbrOjGf0JRW_yiO1pJ-AuwFnmCjyZ2iIPOJ5En5PENBv2kUMoWfJPUwbXWRI4vlvKW0xg5u5g-8lh1YipAcc26ULngVvvRfJLlAstXtAPbvG2jf1H9jPTIwi8j2hSgX6D9wBMIr9R40Hz927tDI8X38b9VMrg3VnUkLKdyrffISasZSwTJ/s1080/Contact%20Management.jpeg&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;1080&quot; data-original-width=&quot;1080&quot; height=&quot;640&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEidX8xK8FCqP7AbrOjGf0JRW_yiO1pJ-AuwFnmCjyZ2iIPOJ5En5PENBv2kUMoWfJPUwbXWRI4vlvKW0xg5u5g-8lh1YipAcc26ULngVvvRfJLlAstXtAPbvG2jf1H9jPTIwi8j2hSgX6D9wBMIr9R40Hz927tDI8X38b9VMrg3VnUkLKdyrffISasZSwTJ/w640-h640/Contact%20Management.jpeg&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;p&gt;&lt;/p&gt;&lt;br /&gt;&lt;div&gt;&lt;b&gt;Functions:&lt;/b&gt;&amp;nbsp;&lt;/div&gt;&lt;div&gt;We will divide the above application into two kinds of functions. The first type of function is user functions which interact with the user to get input and display output, the second type of function is operational functions which do the actual tasks.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The list of user functions is as follows:&lt;/div&gt;&lt;div&gt;&lt;ul style=&quot;text-align: left;&quot;&gt;&lt;li&gt;&lt;b&gt;mainMenu():&lt;/b&gt;&amp;nbsp;It displays the options to the user.&lt;b&gt;&amp;nbsp;&lt;/b&gt;&lt;/li&gt;&lt;li&gt;&lt;b&gt;viewItems():&amp;nbsp;&lt;/b&gt;It displays the list of contact information on the screen.&lt;b&gt;&amp;nbsp;&lt;/b&gt;&lt;/li&gt;&lt;li&gt;&lt;b&gt;addItems():&amp;nbsp;&lt;/b&gt;It requests the user to input contact information added to the file.&lt;/li&gt;&lt;li&gt;&lt;b&gt;updateItems(): &lt;/b&gt;It requests the user to update the contact information in the file.&lt;/li&gt;&lt;li&gt;&lt;b&gt;deleteItems():&amp;nbsp;&lt;/b&gt;It requests the user to delete the contact information in the file.&lt;/li&gt;&lt;li&gt;&lt;b&gt;readData():&amp;nbsp;&lt;/b&gt;It requests the user to input contact information.&lt;/li&gt;&lt;/ul&gt;&lt;div&gt;&lt;span&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;/span&gt;The list of operational functions is as follows:&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;ul style=&quot;text-align: left;&quot;&gt;&lt;li&gt;&lt;b&gt;view(): &lt;/b&gt;It fetches the data from the file.&lt;/li&gt;&lt;li&gt;&lt;b&gt;add():&amp;nbsp;&lt;/b&gt;It adds the data into the file.&lt;/li&gt;&lt;li&gt;&lt;b&gt;update():&amp;nbsp;&lt;/b&gt;It updates the existing data in the file.&lt;/li&gt;&lt;li&gt;&lt;b&gt;del():&amp;nbsp;&lt;/b&gt;It deletes the existing data from the file.&lt;/li&gt;&lt;li&gt;&lt;b&gt;searchByNum():&amp;nbsp;&lt;/b&gt;It searches the data in the file based on unique data elements. In this case, it is a phone number.&lt;/li&gt;&lt;li&gt;&lt;b&gt;getString():&amp;nbsp;&lt;/b&gt;It reads the data input and saves it into the data structure.&lt;/li&gt;&lt;/ul&gt;&lt;div&gt;Please find the source code up to this part below.&lt;/div&gt;&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;
// Define C standard headers
#include&amp;lt;windows.h&amp;gt;
#include&amp;lt;stdio.h&amp;gt;
#include&amp;lt;conio.h&amp;gt;
#include&amp;lt;ctype.h&amp;gt;
#include&amp;lt;string.h&amp;gt;
#include &quot;gotoxy.h&quot;

// Define Constant Variables
#define ESC 27

// Declare functions
void mainMenu();
void viewItems();
void addItems();
void updateItems();
void deleteItems();

// C main function
int main(){
    mainMenu();
    return 0;
}

//Start function definitions

//Display user menu
void mainMenu(){


    char choice;

    system(&quot;cls&quot;);

    gotoxy(35,6);
    printf(&quot;----Welcome to Contact Management System----&quot;);
    gotoxy(35,8);
    printf(&quot;Please select the any option v, a, u, d, e or ESC&quot;);
    gotoxy(35,10);
    printf(&quot;V) View All Contact&quot;);
    gotoxy(35,12);
    printf(&quot;A) Add Contact&quot;);
    gotoxy(35,14);
    printf(&quot;U) Update Contact&quot;);
    gotoxy(35,16);
    printf(&quot;D) Delete Contact&quot;);
    gotoxy(35,18);
    printf(&quot;E) Exit application&quot;);
    gotoxy(35,20);
    printf(&quot;Please enter ESC to exit application&quot;);

    choice=tolower(getch());

    switch(choice){
        case &#39;v&#39;:
            viewItems();
            break;
        case &#39;a&#39;:
            addItems();
            break;
        case &#39;u&#39;:
            updateItems();
            break;
        case &#39;d&#39;:
            deleteItems();
            break;
        case &#39;e&#39;:
            exit(0);
        case ESC:
            exit(0);
        default:
            gotoxy(35,30);
            printf(&quot;Please enter options V, A, U, D, E or ESC&quot;);
            if(getch())
                mainMenu();
    }
}

//Display contacts only 15 items
void viewItems(){

    system(&quot;cls&quot;);
    gotoxy(35,6);
    printf(&quot;----Welcome to Contact Management System----&quot;);
    gotoxy(35,8);
    printf(&quot;View Contact function selected&quot;);

    gotoxy(35,27);
    printf(&quot;Please enter ESC key to go back.&quot;);
    if(getch()==ESC){
        mainMenu();
    } else {
        viewItems();
    }

}

//Add contacts
void addItems(){

    system(&quot;cls&quot;);
    gotoxy(35,6);
    printf(&quot;----Welcome to Contact Management System----&quot;);
    gotoxy(35,8);
    printf(&quot;Add Contact function selected&quot;);

    gotoxy(35,27);
    printf(&quot;Please press any key to continue or enter ESC key to go back.&quot;);
    if(getch()==ESC){
        mainMenu();
    } else {
        addItems();
    }
}

//Update contact details
void updateItems(){

    system(&quot;cls&quot;);
    gotoxy(35,6);
    printf(&quot;----Welcome to Contact Management System----&quot;);
    gotoxy(35,8);
    printf(&quot;Update Contact function selected&quot;);

    gotoxy(35,27);
    printf(&quot;Please enter any key to continue or enter ESC key to go back.&quot;);
    if(getch()==ESC){
        mainMenu();
    } else {
        updateItems();
    }
}

//Delete contacts details
void deleteItems(){

    system(&quot;cls&quot;);
    gotoxy(35,6);
    printf(&quot;----Welcome to Contact Management System----&quot;);
    gotoxy(35,8);
    printf(&quot;Delete Contact function selected&quot;);

    gotoxy(35,27);
    printf(&quot;Please enter any key to continue or enter ESC key to go back.&quot;);

    if(getch()==ESC){
        mainMenu();
    } else {
        deleteItems();
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;b&gt;

Explaining the Code:&lt;/b&gt;&lt;div&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;&lt;div&gt;There isn&#39;t much to explain the above code, most part of it is self-explanatory. It will display the options to the user and based on the user input the respective functions are called to do a specific task. After completing tasks user can go back to the main screen by pressing the ESC key, and select another option, or exit the application.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Also, I am using gotoxy(x,y) function to align the text. You will see this function throughout my articles. Please find the my article gotoxy in Code::blocks to learn about it.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;We will add file handling code and explain it in detail in the next chapter.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;You can also watch a video about this project on YouTube.&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;iframe allowfullscreen=&quot;&quot; class=&quot;BLOG_video_class&quot; height=&quot;266&quot; src=&quot;https://www.youtube.com/embed/K0oLBbzrZ2I&quot; width=&quot;320&quot; youtube-src-id=&quot;K0oLBbzrZ2I&quot;&gt;&lt;/iframe&gt;&lt;/div&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.codeincodeblock.com/feeds/1225966000200451074/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.codeincodeblock.com/2023/11/chapter-1-contact-management-in-c-flow.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/1225966000200451074'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/1225966000200451074'/><link rel='alternate' type='text/html' href='http://www.codeincodeblock.com/2023/11/chapter-1-contact-management-in-c-flow.html' title='Chapter 1: Contact Management in C | Flow Chart and Functions'/><author><name>Dinesh Subedi</name><uri>http://www.blogger.com/profile/14592859300444169698</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEidX8xK8FCqP7AbrOjGf0JRW_yiO1pJ-AuwFnmCjyZ2iIPOJ5En5PENBv2kUMoWfJPUwbXWRI4vlvKW0xg5u5g-8lh1YipAcc26ULngVvvRfJLlAstXtAPbvG2jf1H9jPTIwi8j2hSgX6D9wBMIr9R40Hz927tDI8X38b9VMrg3VnUkLKdyrffISasZSwTJ/s72-w640-h640-c/Contact%20Management.jpeg" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7720722570285165075.post-8012136470074600118</id><published>2020-03-28T09:24:00.004+11:00</published><updated>2025-03-31T18:58:44.972+11:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C source code"/><category scheme="http://www.blogger.com/atom/ns#" term="Mini projects"/><title type='text'>Quiz Game in C Part 3: Final Game Play and score</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;&lt;b&gt;&lt;a href=&quot;https://www.codeincodeblock.com/2011/06/mini-project-quiz-in-c.html&quot; target=&quot;_blank&quot;&gt;First Page&lt;/a&gt;&lt;/b&gt;&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;iframe allowfullscreen=&quot;&quot; class=&quot;BLOG_video_class&quot; height=&quot;266&quot; src=&quot;https://www.youtube.com/embed/xxoK1LSrv3w&quot; width=&quot;320&quot; youtube-src-id=&quot;xxoK1LSrv3w&quot;&gt;&lt;/iframe&gt;&lt;/div&gt;&lt;br /&gt;&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;&lt;br /&gt;&lt;/div&gt;&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
In previous articles, we created functions, multi-dimensional character array to store questions, options, and answers. Up to this point, we have everything ready to finish gameplay.&lt;br /&gt;
Here we will use the following techniques:&lt;br /&gt;
&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;Create for loop to display question one by one&lt;/li&gt;
&lt;li&gt;Create another infinite loop inside for loop to check the answer given by the user. The loop breaks only if the user-provided an answer is within options (a, b, c and d)&amp;nbsp; otherwise it will loop infinitely.&amp;nbsp;&lt;/li&gt;
&lt;li&gt;Calculate the score for the correct answer provided.&lt;/li&gt;
&lt;li&gt;Use gotoxy to manage text indentation.&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;
&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;Here is the final gamePlay() code used in this article:&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;void gamePlay(){
    system(&quot;cls&quot;);
    char question[10][250];
    strcpy(question[0], &quot;This is question no 1&quot;);
    strcpy(question[1], &quot;This is question no 2&quot;);
    strcpy(question[2], &quot;This is question no 3&quot;);
    strcpy(question[3], &quot;This is question no 4&quot;);
    strcpy(question[4], &quot;This is question no 5&quot;);
    strcpy(question[5], &quot;This is question no 6&quot;);
    strcpy(question[6], &quot;This is question no 7&quot;);
    strcpy(question[7], &quot;This is question no 8&quot;);
    strcpy(question[8], &quot;This is question no 9&quot;);
    strcpy(question[9], &quot;This is question no 10&quot;);

    char option[10][4][50] = {
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
    };

    char answer[10]={&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;a&#39;,&#39;b&#39;};
    char letter[4]={&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;};
    char ans;
    int score=0;

    for(int i=0;i&amp;lt;10;i++){
            system(&quot;cls&quot;);
            gotoxy(20,8);
            printf(&quot;%s\n&quot;,question[i]);
            for(int j=0;j&amp;lt;4;j++){
                if(j==0 || j==2){
                    gotoxy(20,10 + j);
                    printf(&quot;%c) %s\n&quot;,letter[j],option[i][j]);
                } else {
                    gotoxy(55,9 + j);
                    printf(&quot;%c) %s\n&quot;,letter[j],option[i][j]);
                }
            }

            do{
                gotoxy(22,15);
                printf(&quot;Please Choose Answer using key a|b|c|d: &quot;);
                ans=tolower(getch());
                if(ans==&#39;a&#39;||ans==&#39;b&#39;||ans==&#39;c&#39;||ans==&#39;d&#39;)
                    break;
            }while(1==1);

            if(ans==answer[i]){
                gotoxy(22,15);
                printf(&quot;Correct Answer!!PRESS ANY KEY TO Continue....&quot;);
                score++;
                getch();
            }else{
                gotoxy(22,15);
                printf(&quot;Wrong Answer!!PRESS ANY KEY TO Continue....&quot;);
                getch();
            }

        }
        system(&quot;cls&quot;);
        gotoxy(22,8);
        printf(&quot;You have score %d Out of 10.PRESS ANY KEY...&quot;,score);
        getch();

        mainMenu();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;div&gt;
Explaining the code:&lt;/div&gt;
&lt;div&gt;
We will declare two variables &quot;ans&quot; and &quot;score&quot; to store the answer provided by the user and to store the total score.&amp;nbsp;&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;    char ans;
    int score=0;&lt;/code&gt;&lt;/pre&gt;
&lt;div&gt;
And two nested for loop is used to display answers and options. First for loop statement loops 10 times and another nested for loop statement loops 4 times so in total there will be 40 loops. Inside first for loop another infinite do-while loop is created to waits user input and validation. Users can provide any value outside the provided options. This scenario is handled using an infinite do-while loop it only breaks if and only the user provides the correct value.&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;do{
        gotoxy(22,15);
        printf(&quot;Please Choose Answer using key a or b or c or d: &quot;);
        ans=tolower(getch());
        if(ans==&#39;a&#39;||ans==&#39;b&#39;||ans==&#39;c&#39;||ans==&#39;d&#39;)
            break;
    }while(1==1);
&lt;/code&gt;&lt;/pre&gt;
&lt;div&gt;
Finally, the if-else statement is used to compare the answer provided by the user and correct answer stored in character array variables &quot;answer&quot;.&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;    if(ans==answer[i]){
        gotoxy(22,15);
        printf(&quot;Correct Answer!! PRESS ANY KEY TO Continue....&quot;);
        score++;
        getch();
    }else{
        gotoxy(22,15);
        printf(&quot;Wrong Answer!! PRESS ANY KEY TO Continue....&quot;);
        getch();
    }
&lt;/code&gt;&lt;/pre&gt;
&lt;div&gt;
After completing the game, the final score is displayed and we will call mainMenu() function to direct the program to the main menu screen where the user can choose to play again or quit the game.&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt; mainMenu();&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.codeincodeblock.com/feeds/8012136470074600118/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.codeincodeblock.com/2020/03/quiz-game-in-c-part-3-final-game-play.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/8012136470074600118'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/8012136470074600118'/><link rel='alternate' type='text/html' href='http://www.codeincodeblock.com/2020/03/quiz-game-in-c-part-3-final-game-play.html' title='Quiz Game in C Part 3: Final Game Play and score'/><author><name>Dinesh Subedi</name><uri>http://www.blogger.com/profile/15921581026092958477</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfxMED05n-0aBIoi4kgT-8kSHfpuRf1bFosaVy-JI-vEwMtJr0sNUFF4S2oj2axSo9IfljCyuPc4hieJ0HsUEPnmw7-8Rj6UTcQjG0Mwv0tiPhTTz6ginzbCdi48YU2oQ/s151/CIMG5697.JPG'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://img.youtube.com/vi/xxoK1LSrv3w/default.jpg" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7720722570285165075.post-5229790645973407960</id><published>2020-03-28T09:23:00.004+11:00</published><updated>2025-03-31T18:58:36.681+11:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C source code"/><category scheme="http://www.blogger.com/atom/ns#" term="Mini projects"/><title type='text'>Quiz game in C Part 2: Multi-dimensional C array</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;&lt;b&gt;&lt;a href=&quot;https://www.codeincodeblock.com/2020/03/quiz-game-in-c-part-1-flow-chart-and.html&quot; target=&quot;_blank&quot;&gt;Previous Page&lt;/a&gt;&lt;/b&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;b&gt;&lt;a href=&quot;https://www.codeincodeblock.com/2020/03/quiz-game-in-c-part-3-final-game-play.html&quot; target=&quot;_blank&quot;&gt;Next Page&lt;/a&gt;&lt;/b&gt;&lt;/span&gt;&lt;/div&gt;&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;iframe allowfullscreen=&quot;&quot; class=&quot;BLOG_video_class&quot; height=&quot;266&quot; src=&quot;https://www.youtube.com/embed/xxoK1LSrv3w&quot; width=&quot;320&quot; youtube-src-id=&quot;xxoK1LSrv3w&quot;&gt;&lt;/iframe&gt;&lt;/div&gt;&lt;br /&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;span style=&quot;font-family: inherit;&quot;&gt;In this article, we will discuss the gameplay() function but not all only the usages of one dimension, two-dimension, and third dimension character array. Choosing the correct dimension of the array is very important to store information effectively. We have to display a question, four options and store the correct answer to compare the answer provided by the user. Remember these three information are connected to each other if we mismatch the order then the game will go wrong.&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: inherit;&quot;&gt;Here, we will declare three character array to store questions, four options, and answer in the same order of the array index.&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: inherit;&quot;&gt;&lt;br /&gt;&lt;/span&gt;
&lt;span style=&quot;font-family: inherit;&quot;&gt;Question is a string which is an array of character and we will ask 10 questions in total. We create a two-dimension character array, the first index is a total number of questions i.e 10 and the second index is the length of a string.&lt;/span&gt;&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;    char question[10][250];
    strcpy(question[0], &quot;This is question no 1&quot;);
    strcpy(question[1], &quot;This is question no 2&quot;);
    strcpy(question[2], &quot;This is question no 3&quot;);
    strcpy(question[3], &quot;This is question no 4&quot;);
    strcpy(question[4], &quot;This is question no 5&quot;);
    strcpy(question[5], &quot;This is question no 6&quot;);
    strcpy(question[6], &quot;This is question no 7&quot;);
    strcpy(question[7], &quot;This is question no 8&quot;);
    strcpy(question[8], &quot;This is question no 9&quot;);
    strcpy(question[9], &quot;This is question no 10&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
We can&#39;t assign string using &quot;=&quot; to the two-dimension array and correct way to use it is strcpy() function.&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: inherit;&quot;&gt;&lt;br /&gt;&lt;/span&gt;
&lt;span style=&quot;font-family: inherit;&quot;&gt;Next, we create a three-dimension array to store four options for each question. A first index is a number of questions i.e 10, a second index is a number of options i.e 4 and a third index is the length of a string.&lt;/span&gt;&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;    char option[10][4][50] = {
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
    };&lt;/code&gt;&lt;/pre&gt;
&lt;span style=&quot;font-family: inherit;&quot;&gt;Now, we create a one-dimension array to store the answer corresponding to the questions.&lt;/span&gt;&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;    char answer[10]={&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;a&#39;,&#39;b&#39;};&lt;/code&gt;&lt;/pre&gt;
&lt;span style=&quot;font-family: inherit;&quot;&gt;Here is the main menu code for the gameplay() function used in this article&lt;/span&gt;&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;void gamePlay(){
    system(&quot;cls&quot;);
    char question[10][250];
    strcpy(question[0], &quot;This is question no 1&quot;);
    strcpy(question[1], &quot;This is question no 2&quot;);
    strcpy(question[2], &quot;This is question no 3&quot;);
    strcpy(question[3], &quot;This is question no 4&quot;);
    strcpy(question[4], &quot;This is question no 5&quot;);
    strcpy(question[5], &quot;This is question no 6&quot;);
    strcpy(question[6], &quot;This is question no 7&quot;);
    strcpy(question[7], &quot;This is question no 8&quot;);
    strcpy(question[8], &quot;This is question no 9&quot;);
    strcpy(question[9], &quot;This is question no 10&quot;);

    char option[10][4][50] = {
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
        {&quot;option1&quot;,&quot;option2&quot;,&quot;option3&quot;,&quot;option4&quot;},
    };

    char answer[10]={&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;a&#39;,&#39;b&#39;};
    char letter[4]={&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;};

            for(int i=0;i&amp;lt;10;i++){
            printf(&quot;%s\n&quot;,question[i]);
            for(int j=0;j&amp;lt;4;j++){
                printf(&quot;%c) %s\n&quot;,letter[j],option[i][j]);
            }
            printf(&quot;Answer is: %c\n&quot;,answer[i]);
        }
}
&lt;/code&gt;&lt;/pre&gt;
In the &lt;a href=&quot;https://www.codeincodeblock.com/2020/03/quiz-game-in-c-part-3-final-game-play.html&quot; target=&quot;_blank&quot;&gt;next part&lt;/a&gt; of the article, we will finalize the gameplay() function and complete the quiz game.&lt;/div&gt;&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;br /&gt;&lt;/div&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://www.codeincodeblock.com/feeds/5229790645973407960/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.codeincodeblock.com/2020/03/quiz-game-in-c-part-2-multi-dimensional.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/5229790645973407960'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/5229790645973407960'/><link rel='alternate' type='text/html' href='http://www.codeincodeblock.com/2020/03/quiz-game-in-c-part-2-multi-dimensional.html' title='Quiz game in C Part 2: Multi-dimensional C array'/><author><name>Dinesh Subedi</name><uri>http://www.blogger.com/profile/15921581026092958477</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfxMED05n-0aBIoi4kgT-8kSHfpuRf1bFosaVy-JI-vEwMtJr0sNUFF4S2oj2axSo9IfljCyuPc4hieJ0HsUEPnmw7-8Rj6UTcQjG0Mwv0tiPhTTz6ginzbCdi48YU2oQ/s151/CIMG5697.JPG'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://img.youtube.com/vi/xxoK1LSrv3w/default.jpg" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7720722570285165075.post-7548430629314855612</id><published>2020-03-28T09:22:00.005+11:00</published><updated>2025-03-31T18:58:23.809+11:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C source code"/><category scheme="http://www.blogger.com/atom/ns#" term="Mini projects"/><title type='text'>Quiz Game in C part 1 - Flow Chart and Main Menu</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;br /&gt;
&lt;div style=&quot;margin: 0in; text-align: left;&quot;&gt;&lt;span style=&quot;font-family: calibri;&quot;&gt;&lt;b&gt;&lt;a href=&quot;https://www.codeincodeblock.com/2011/06/mini-project-quiz-in-c.html&quot; target=&quot;_blank&quot;&gt;Previous Page&lt;/a&gt;&lt;/b&gt;&lt;/span&gt;&lt;b style=&quot;font-family: calibri;&quot;&gt;&amp;nbsp;&lt;/b&gt;&lt;b style=&quot;font-family: calibri;&quot;&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;a href=&quot;https://www.codeincodeblock.com/2020/03/quiz-game-in-c-part-2-multi-dimensional.html&quot; target=&quot;_blank&quot;&gt;Next Page&lt;/a&gt;&lt;/b&gt;&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;iframe allowfullscreen=&quot;&quot; class=&quot;BLOG_video_class&quot; height=&quot;266&quot; src=&quot;https://www.youtube.com/embed/xxoK1LSrv3w&quot; width=&quot;320&quot; youtube-src-id=&quot;xxoK1LSrv3w&quot;&gt;&lt;/iframe&gt;&lt;/div&gt;&lt;br /&gt;&lt;div style=&quot;margin: 0in; text-align: left;&quot;&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style=&quot;margin: 0in; text-align: left;&quot;&gt;
&lt;b style=&quot;font-family: calibri;&quot;&gt;Application Flow Chart:&lt;/b&gt;&lt;/div&gt;
&lt;div style=&quot;font-family: Calibri; font-size: 11pt; margin: 0in;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhA8wkP2uRrH_dlsztJJhZ30CenWcntXufw6d5mIZdChUNk1uMy8NfwU_pRhutXnRPwBUtzmMKr2QINgeRmsdAyZOpTUBDDV5Q31fCDysDeThB-gyCtit32L9ycaYb7tW6g6mTQPhIQnWs/s1600/FlowChart_Quiz.jpeg&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;1600&quot; data-original-width=&quot;1480&quot; height=&quot;640&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhA8wkP2uRrH_dlsztJJhZ30CenWcntXufw6d5mIZdChUNk1uMy8NfwU_pRhutXnRPwBUtzmMKr2QINgeRmsdAyZOpTUBDDV5Q31fCDysDeThB-gyCtit32L9ycaYb7tW6g6mTQPhIQnWs/s640/FlowChart_Quiz.jpeg&quot; width=&quot;592&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div style=&quot;font-family: calibri; margin: 0in;&quot;&gt;
&lt;b&gt;Start:&lt;/b&gt; Quiz program
start&lt;/div&gt;
&lt;div style=&quot;font-family: calibri; margin: 0in;&quot;&gt;
&lt;b&gt;Main Menu:&lt;/b&gt; Program
display menu to the user to start the game or to quit.&lt;/div&gt;
&lt;div style=&quot;font-family: calibri; margin: 0in;&quot;&gt;
&lt;b&gt;User Input:&lt;/b&gt; The application stops to get user input.&lt;/div&gt;
&lt;div style=&quot;font-family: calibri; margin: 0in;&quot;&gt;
&lt;b&gt;Decision Tree:&lt;/b&gt; If
user input is S then Quiz game start else if user input is Q then the program will
quit.&lt;/div&gt;
&lt;div style=&quot;font-family: calibri; margin: 0in;&quot;&gt;
&lt;b&gt;Quiz Game:&lt;/b&gt; User gets
10 questions one by one and each correct score is marked as 1.&lt;/div&gt;
&lt;div style=&quot;font-family: calibri; margin: 0in;&quot;&gt;
&lt;b&gt;Display Score:&lt;/b&gt; It
display final score after ending the game and the user is directed to the main menu.&lt;/div&gt;
&lt;div style=&quot;font-family: calibri; margin: 0in;&quot;&gt;
&lt;b&gt;Stop:&lt;/b&gt; End of the
game.&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div style=&quot;font-family: calibri; margin: 0in;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div style=&quot;font-family: calibri; margin: 0in;&quot;&gt;
Here is the main
menu code for the Quiz game used in this article&lt;span style=&quot;font-size: 11pt;&quot;&gt;:&lt;/span&gt;&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;#include &amp;lt;stdio.h&amp;gt;
#include &amp;lt;conio.h&amp;gt;
#include &amp;lt;ctype.h&amp;gt;
#include &quot;gotoxy.h&quot;

/* Define variable*/
#define ESC 27

/* Function declaration*/
void mainMenu();
void gamePlay();

int main() {
    mainMenu();
    return 0;
}

/* Function definition*/
void mainMenu(){

    char choice;

    system(&quot;cls&quot;);
    gotoxy(30,8);
    printf(&quot;WELCOME TO I.Q TEST PROGRAM&quot;);
    gotoxy(30,10);
    printf(&quot;----------------------------&quot;);
    gotoxy(30,12);
    printf(&quot;Enter S to start game&quot;);
    gotoxy(30,14);
    printf(&quot;Enter Q or ESc to quit&quot;);
    gotoxy(30,16);
    printf(&quot;----------------------------&quot;);

    choice=toupper(getch());

    switch(choice){
    case &#39;S&#39;:
        gamePlay();
        break;
    case &#39;Q&#39;:
        exit(0);
    case ESC:
        exit(0);
    default:
        gotoxy(30,18);
        printf(&quot;Wrong Entry!!&quot;);
        gotoxy(30,20);
        printf(&quot;Press any key and re-enter correct option&quot;);
        if(getch())
            mainMenu();
    }
}
//Function defination
void gamePlay(){
    system(&quot;cls&quot;);
    printf(&quot;Choice S selected&quot;);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div style=&quot;margin: 0in;&quot;&gt;
&lt;div style=&quot;font-family: calibri; font-size: 11pt;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div style=&quot;font-family: calibri;&quot;&gt;
&lt;b style=&quot;font-family: calibri;&quot;&gt;Explaining the Code:&lt;/b&gt;&lt;br /&gt;
Let&#39;s start digging
the code. Here you will learn to breakdown application in function and using
switch statements to switch between functions based on user input.&lt;/div&gt;
&lt;/div&gt;
&lt;div style=&quot;font-family: Calibri; font-size: 11pt; margin: 0in;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div style=&quot;font-family: calibri; margin: 0in;&quot;&gt;
First, we will include the user define header &quot;gotoxy.h&quot;&lt;span style=&quot;mso-spacerun: yes;&quot;&gt;&amp;nbsp;
&lt;/span&gt;and system library headers &quot;stdio.h&quot;, &quot;conio.h&quot; and
&quot;ctype.h&quot;. The &quot;stdio.h&quot; is C Standard Input Output
library, &quot;conio.h&quot; is not a C Standard Input Output but required for
user input function getch() and &quot;ctype.h&quot; is C Standard library
required for toupper() function. To learn about &quot;gotoxy.h&quot; library function please follow my previous article &lt;a href=&quot;https://www.codeincodeblock.com/2011/03/gotoxy-in-codeblock.html&quot; target=&quot;_blank&quot;&gt;gotoxy in codeblock.&lt;/a&gt;&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;#include &amp;lt;stdio.h&amp;gt;
#include &amp;lt;conio.h&amp;gt;
#include &amp;lt;ctype.h&amp;gt;
#include &quot;gotoxy.h&quot;&amp;nbsp;&lt;/code&gt;&lt;/pre&gt;
&lt;div style=&quot;font-family: Calibri; margin: 0in;&quot;&gt;
27 is the ASCII decimal
code for the &quot;ESC&quot; character. In a switch statement, this value is used
to check the user input &quot;ESC&quot; key.&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;/* Define variable*/
#define ESC 27&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
Next, we will define functions. These functions are created as per the application flow chart. In above flow chart, you can see there are three processes main menu, quiz game, and display score. Here display score process is simple and small so no need to create a separate function and it can be included in a quiz game.&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&lt;code class=&quot;language-cpp&quot;&gt;/* Function declaration*/
void mainMenu();
void gamePlay();

int main() {
    mainMenu();
    return 0;
}
&lt;/code&gt;&lt;/pre&gt;
This is another line please :D&lt;br /&gt;
mainMenu() function displays user options and waits for the user input. Switch statement is used to switch the application state. If user input &quot;S&quot; gamePlay() function is called to start the game, else if user input &quot;Q&quot; program exits by calling exit(0) and if user input other then these two options then again mainMenu() function is called to return program in the current state. This technique will help to create an infinite loop, until and unless the user input correct option program will remain in the current sate.&lt;br /&gt;
You may have noticed that at top of each function system(&quot;cls&quot;) function is called which is used to clear screen.&lt;br /&gt;
Finally, gamePlay() function is the main part of this application which we will discuss in the &lt;a href=&quot;https://www.codeincodeblock.com/2020/03/quiz-game-in-c-part-2-multi-dimensional.html&quot; target=&quot;_blank&quot;&gt;next part.&lt;/a&gt;&lt;/div&gt;&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://www.codeincodeblock.com/feeds/7548430629314855612/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.codeincodeblock.com/2020/03/quiz-game-in-c-part-1-flow-chart-and.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/7548430629314855612'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/7548430629314855612'/><link rel='alternate' type='text/html' href='http://www.codeincodeblock.com/2020/03/quiz-game-in-c-part-1-flow-chart-and.html' title='Quiz Game in C part 1 - Flow Chart and Main Menu'/><author><name>Dinesh Subedi</name><uri>http://www.blogger.com/profile/15921581026092958477</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfxMED05n-0aBIoi4kgT-8kSHfpuRf1bFosaVy-JI-vEwMtJr0sNUFF4S2oj2axSo9IfljCyuPc4hieJ0HsUEPnmw7-8Rj6UTcQjG0Mwv0tiPhTTz6ginzbCdi48YU2oQ/s151/CIMG5697.JPG'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://img.youtube.com/vi/xxoK1LSrv3w/default.jpg" height="72" width="72"/><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7720722570285165075.post-92074061371146893</id><published>2013-08-27T00:10:00.001+10:00</published><updated>2013-08-27T00:10:32.492+10:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="GLFW graphics"/><title type='text'>Basic GLFW Tutorials with C++</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
GLFW (OpenGL FrameWork) is open source library to create OpenGL Window and multi-platform &amp;nbsp;too. Very easy to manage OpenGL context and event with GLFW. It is specially suitable for game development. GLFW doesn&#39;t render 3D scene for that you have to use OpenGL library function. GLFW help to create window , handle keyboard , mouse and joystick events. This tutorials is for those who are new to OpenGL and GLFW. By the end of this tutoirals series understand the basic knowledge about OpenGL and handling events with GLFW.&lt;br /&gt;
&lt;br /&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;a href=&quot;http://www.codeincodeblock.com/2011/02/setup-glfw-project-in-codeblock.html&quot;&gt;&lt;span style=&quot;font-size: large;&quot;&gt;Tutorials 1:&lt;/span&gt;&lt;/a&gt; Setup GLFW in Code::Blocks IDE in Windows Machine&lt;/div&gt;
&lt;br /&gt;
&lt;span style=&quot;font-size: large;&quot;&gt;&lt;a href=&quot;http://www.codeincodeblock.com/2012/04/glfw-tutorial-1introduction-to-opengl.html&quot;&gt;Tutorials 2:&lt;/a&gt; &lt;/span&gt;&amp;nbsp;Introduction to GLFW&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-size: large;&quot;&gt;&lt;a href=&quot;http://www.codeincodeblock.com/2012/04/glfw-opengl-framework-tutorial-2.html&quot;&gt;Tutorials 3:&lt;/a&gt;&lt;/span&gt; Drawing Basic Shapes&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-size: large;&quot;&gt;&lt;a href=&quot;http://www.codeincodeblock.com/2012/04/glfwopengl-framework-tutorial.html&quot;&gt;Tutorials 4:&lt;/a&gt;&lt;/span&gt; Transformation: Translation, Rotation and Scalling&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-size: large;&quot;&gt;&lt;a href=&quot;http://www.codeincodeblock.com/2012/04/glfw-tutorial-4-texture-mapping-sample.html&quot;&gt;Tutorials 5:&lt;/a&gt;&lt;/span&gt; Texture Mapping&amp;nbsp;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://www.codeincodeblock.com/feeds/92074061371146893/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.codeincodeblock.com/2013/08/basic-glfw-tutorials-with-c.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/92074061371146893'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/92074061371146893'/><link rel='alternate' type='text/html' href='http://www.codeincodeblock.com/2013/08/basic-glfw-tutorials-with-c.html' title='Basic GLFW Tutorials with C++'/><author><name>Dinesh Subedi</name><uri>http://www.blogger.com/profile/15921581026092958477</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfxMED05n-0aBIoi4kgT-8kSHfpuRf1bFosaVy-JI-vEwMtJr0sNUFF4S2oj2axSo9IfljCyuPc4hieJ0HsUEPnmw7-8Rj6UTcQjG0Mwv0tiPhTTz6ginzbCdi48YU2oQ/s151/CIMG5697.JPG'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7720722570285165075.post-3319011937091712626</id><published>2013-07-27T22:47:00.001+10:00</published><updated>2015-05-10T19:30:24.944+10:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Modern OpenGL"/><title type='text'>Modern OpenGL Tutorial Series</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Modern OpenGL are different than ancient opengl version before 2.0. After opengl 2.0 vetex shader and fragment shader became compulsory. It is little bit difficult for beginner to start.&lt;br /&gt;
&lt;br /&gt;
All chapter include basic concept of Modern OpenGL and especially focus on beginner. After going through all the chapter user can get concept of shader, drawing shapes, perspective projection, transformation, color, texture mapping and load 3D model wavefront OBJ.&lt;br /&gt;
&lt;br /&gt;
Download all the code as a zip from here: &lt;a href=&quot;https://github.com/smokindinesh/Modern-OpenGL-Series/archive/master.zip&quot; target=&quot;_blank&quot;&gt;https://github.com/smokindinesh/Modern-OpenGL-Series/archive/master.zip&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
All the code in this series of articles is available from github: &lt;a href=&quot;https://github.com/smokindinesh/Modern-OpenGL-Series&quot; target=&quot;_blank&quot;&gt;https://github.com/smokindinesh/Modern-OpenGL-Series&lt;/a&gt; You can download a zip of all the files from that page, or you can clone the repository if you are familiar with git.&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;Tutorials 1: &lt;a href=&quot;http://www.codeincodeblock.com/2013/05/setup-modern-opengl-3-and-4-with-glfw.html&quot;&gt;Setup Modern OpenGLin Code::Blocks IDE&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Tutorials 2: &lt;a href=&quot;http://www.codeincodeblock.com/2013/05/beginner-learning-materials-for-modern.html&quot;&gt;Sample source code to check OpenGL setup&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Tutorials 3: &lt;a href=&quot;http://www.codeincodeblock.com/2013/05/introduction-to-modern-opengl-3x-with.html&quot;&gt;Introduction to Modern OpenGL&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Tutorials 4: &lt;a href=&quot;http://www.codeincodeblock.com/2013/05/modern-opengl-3x-drawing-basic.html&quot;&gt;Drawing Basic Shapes&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Tutorials 5: &lt;a href=&quot;http://www.codeincodeblock.com/2013/05/modern-opengl-3x-perspective-projection.html&quot;&gt;Perspective Projection&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Tutorials 6: &lt;a href=&quot;http://www.codeincodeblock.com/2013/05/modern-opengl-3x-rotation-scalling-and.html&quot;&gt;Rotation,Translation and Scalling&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Tutorials 7: &lt;a href=&quot;http://www.codeincodeblock.com/2013/06/modern-opengl-3x-playing-with-color.html&quot;&gt;Playing With Colors&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Tutorials 8: &lt;a href=&quot;http://www.codeincodeblock.com/2013/06/modern-opengl-3x-texture-mapping.html&quot;&gt;Texture Mapping&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Tutorials 9: &lt;a href=&quot;http://www.codeincodeblock.com/2013/07/modern-opengl3d-model-obj-loaderparser.html&quot;&gt;Load 3D model wavefront OBJ&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://www.codeincodeblock.com/feeds/3319011937091712626/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.codeincodeblock.com/2013/07/modern-opengl-32-tutorial-series-with.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/3319011937091712626'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/3319011937091712626'/><link rel='alternate' type='text/html' href='http://www.codeincodeblock.com/2013/07/modern-opengl-32-tutorial-series-with.html' title='Modern OpenGL Tutorial Series'/><author><name>Dinesh Subedi</name><uri>http://www.blogger.com/profile/15921581026092958477</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfxMED05n-0aBIoi4kgT-8kSHfpuRf1bFosaVy-JI-vEwMtJr0sNUFF4S2oj2axSo9IfljCyuPc4hieJ0HsUEPnmw7-8Rj6UTcQjG0Mwv0tiPhTTz6ginzbCdi48YU2oQ/s151/CIMG5697.JPG'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7720722570285165075.post-2466214444822147611</id><published>2013-07-27T11:00:00.000+10:00</published><updated>2015-05-10T19:55:15.817+10:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Modern OpenGL"/><title type='text'>Modern OpenGL tutorial 3D model .obj loader/parser  with C++ and GLM</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
When you need to draw a more advanced object like character, house, terrain, vehicles we can&#39;t pass the vertices by ourselves for these object so we have to use the 3D model and model are simply the meshes made of one or more number of vertices. There are many 3D modeling software one of them is blender which is open source also. Blender help to create the model and export it into different file format like .obj, 3ds, md2 etc among them I choose the .obj (wave front obj) file which is very simple. OBJ only contain vertex, normal, texture and other material information. It doesn&#39;t support animation for animation we can use &amp;nbsp;3ds, md2 &amp;nbsp;3Dmodel. There are many library to load 3D model.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Download&lt;/b&gt;&lt;br /&gt;
All the code in this series of articles is available from github:&amp;nbsp;&lt;a href=&quot;https://github.com/smokindinesh/Modern-OpenGL-Series&quot; target=&quot;_blank&quot;&gt;https://github.com/smokindinesh/Modern-OpenGL-Series&lt;/a&gt;&amp;nbsp;&amp;nbsp;You can download a zip of all the files&amp;nbsp;from that page, or you can clone the repository if you are familiar with git.&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp;In this articles I will show you how to write your own .obj model parser.&lt;br /&gt;
&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
For a quick and simplicity rather than making our own 3D model we use existing one. At first if you don&#39;t have blender then download it form &lt;a href=&quot;http://www.blender.org/download/get-blender/&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;.&lt;br /&gt;
We will export the blender default cube in .obj format. We don&#39;t use any other material effect, texture and normal just only vertices are exported.&lt;br /&gt;
Open the blender you will see the default cube. You don&#39;t have to do anythings just export it in obj format.&lt;br /&gt;
For exporting goto file-&amp;amp;gt;export-&amp;amp;gt;wavefront(.obj) option. Give name &quot;cube&quot; and choose &amp;nbsp;the directory where you want to export it.While exporting don&#39;t forgot to check the triangular faces which is shown in figure.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiMuiUvXrztp-Pu7wcjEczwJULq2xzxaK_rLtC8RRdWd7U6QBnNIMmtv2nFmv0V9pspZzM8WLsh_JZ0PfMX_hbY_fIK9bO7QkWtA_gGiKmrRal4J0CixuJt_8mr16n_cB79v-kkTBUH0ko/s1600/exportObj.JPG&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;320&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiMuiUvXrztp-Pu7wcjEczwJULq2xzxaK_rLtC8RRdWd7U6QBnNIMmtv2nFmv0V9pspZzM8WLsh_JZ0PfMX_hbY_fIK9bO7QkWtA_gGiKmrRal4J0CixuJt_8mr16n_cB79v-kkTBUH0ko/s320/exportObj.JPG&quot; width=&quot;145&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
You will see two file &quot;cube.obj&quot; and &quot;cube.mtl&quot;.&lt;br /&gt;
The .obj file contains the mesh : vertices and &amp;nbsp;faces.&lt;br /&gt;
The .mtl file contains information about material.&lt;br /&gt;
Lets inspects the .obj file how it looks like. You will see pretty simple format.&lt;br /&gt;
&lt;pre class=&quot;brush:cpp&quot;&gt;# Blender v2.67 (sub 0) OBJ File: &#39;&#39;
# www.blender.org
mtllib cude.mtl
o Cube
v 1.000000 -1.000000 -1.000000
v 1.000000 -1.000000 1.000000
v -1.000000 -1.000000 1.000000
v -1.000000 -1.000000 -1.000000
v 1.000000 1.000000 -0.999999
v 0.999999 1.000000 1.000001
v -1.000000 1.000000 1.000000
v -1.000000 1.000000 -1.000000
usemtl Material
s off
f 1 2 3
f 5 8 7
f 1 5 6
f 2 6 3
f 3 7 4
f 5 1 4
f 4 1 3
f 6 5 7
f 2 1 6
f 6 7 3
f 7 8 4
f 8 5 4

&lt;/pre&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;/div&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;lines starting with # are comments&lt;/li&gt;
&lt;li&gt;o introduces a new object&lt;/li&gt;
&lt;li&gt;v introduces a vertex&lt;/li&gt;
&lt;li&gt;vt introduces texture coordinates&lt;/li&gt;
&lt;li&gt;vn introduces a normal&lt;/li&gt;
&lt;li&gt;f introduces a face, using vertex indices, starting at 1&lt;/li&gt;
&lt;li&gt;usemtl and mtlib describe the look of the model&lt;/li&gt;
&lt;/ul&gt;
But in our model we doesn&#39;t see vn and vt because we haven&#39;t use it. One thing you may surprise that for making complete cube we need 12 triangles that is 12 * 3 = 36 vertex but you see there is only 8 vertex. This is because cube has only 8 corner so we only 8 vertex is enough. For representing all 12 triangles by 8 vertex we use f (face index) we can see&lt;br /&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
f 1 2 3&lt;/div&gt;
f 5 8 7&lt;br /&gt;
f 1 5 6&lt;br /&gt;
These are the vertex index. f 1 2 3 means vertex first, second and third makes one triangular face among the 12 triangular face of cube. Other f &amp;nbsp;5 8 7 is also similar 5th , 8th, 7th vertex makes another triangular face and so on. In this way all the 12 triangle is represented.&lt;br /&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
Our obj parser is limited it doesn&#39;t support &amp;nbsp;multiple object , texture and normal. This is only for learning purpose so that we can understand how to write our own complet obj parser.For that I have created the mesh class.&lt;br /&gt;
&lt;b&gt;mesh.h&lt;/b&gt;&lt;/div&gt;
&lt;pre class=&quot;brush:cpp&quot;&gt;#ifndef MESH_H
#define MESH_H
#include&lt;glm glm.hpp=&quot;&quot;&gt;
#include&lt;glm gtc=&quot;&quot; matrix_transform.hpp=&quot;&quot;&gt;
#include&lt;glm gtc=&quot;&quot; type_ptr.hpp=&quot;&quot;&gt;
#include&lt;vector&gt;
#include&lt;iostream&gt;
#include&lt;fstream&gt;
#include&lt;string&gt;
#include&lt;sstream&gt;
#include&lt;cstdlib&gt;
#include&lt;gl glfw.h=&quot;&quot;&gt;

class Mesh
{
    public:
        Mesh();//constructor
        void LoadObjModel(const char *filename);//function to load obj model
        std::vector&lt;glm::vec3&gt; returnMesh();//return the vertices of mesh data
    private:
        std::vector&lt;glm::vec3&gt; vertices;//to store vertex information of 3D model started with v
        std::vector&lt;glm::vec3&gt; meshVertices;//to store all 3D model face vertices
        std::vector&lt;int&gt; faceIndex;//to store the number of face index started with f

};

#endif
 // MESH_H

&lt;/int&gt;&lt;/glm::vec3&gt;&lt;/glm::vec3&gt;&lt;/glm::vec3&gt;&lt;/gl&gt;&lt;/cstdlib&gt;&lt;/sstream&gt;&lt;/string&gt;&lt;/fstream&gt;&lt;/iostream&gt;&lt;/vector&gt;&lt;/glm&gt;&lt;/glm&gt;&lt;/glm&gt;&lt;/pre&gt;
&lt;b&gt;mesh.cpp&lt;/b&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;pre class=&quot;brush:cpp&quot;&gt;#include &quot;../include/Mesh.h&quot;

Mesh::Mesh()
{
    //ctor
}
void Mesh::LoadObjModel(const char *filename)
{
    std::ifstream in(filename, std::ios::in);
    if (!in)
        {
            std::cerr &amp;amp;lt;&amp;amp;lt; &quot;Cannot open &quot; &amp;amp;lt;&amp;amp;lt; filename &amp;amp;lt;&amp;amp;lt; std::endl;
            exit(1);

        }
    std::string line;
    while (std::getline(in, line))
    {

      if (line.substr(0,2)==&quot;v &quot;){
            std::istringstream v(line.substr(2));
            glm::vec3 vert;
            double x,y,z;
            v&amp;amp;gt;&amp;amp;gt;x;v&amp;amp;gt;&amp;amp;gt;y;v&amp;amp;gt;&amp;amp;gt;z;
            vert=glm::vec3(x,y,z);
            vertices.push_back(vert);
      }
      else if(line.substr(0,2)==&quot;f &quot;){
        std::istringstream v(line.substr(2));
        GLuint a,b,c;
        v&amp;amp;gt;&amp;amp;gt;a;v&amp;amp;gt;&amp;amp;gt;b;v&amp;amp;gt;&amp;amp;gt;c;
        a--;b--;c--;
        faceIndex.push_back(a);
        faceIndex.push_back(b);
        faceIndex.push_back(c);
      }

    }

 //calculate all mesh vertices using face index
for(unsigned int i=0; i &amp;amp;lt; faceIndex.size(); i++)
{
    glm::vec3 meshData;
    meshData=glm::vec3(vertices[faceIndex[i]].x,vertices[faceIndex[i]].y,vertices[faceIndex[i]].z);
    meshVertices.push_back(meshData);

}

}

//function for returing mesh vertex data
std::vector&lt;glm::vec3&gt; Mesh::returnMesh()
{
    return meshVertices;
}
&lt;/glm::vec3&gt;&lt;/pre&gt;
&lt;pre class=&quot;brush:cpp&quot;&gt;&lt;glm::vec3&gt;
&lt;/glm::vec3&gt;&lt;/pre&gt;
This is end of chapter for my Modern OpenGL tutorial series for beginner. If you haven&#39;t follow all previous chapter then you can get here&amp;nbsp;&lt;a href=&quot;http://www.codeincodeblock.com/2013/07/modern-opengl-32-tutorial-series-with.html&quot;&gt;http://www.codeincodeblock.com/2013/07/modern-opengl-32-tutorial-series-with.html&lt;/a&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://www.codeincodeblock.com/feeds/2466214444822147611/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.codeincodeblock.com/2013/07/modern-opengl3d-model-obj-loaderparser.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/2466214444822147611'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/2466214444822147611'/><link rel='alternate' type='text/html' href='http://www.codeincodeblock.com/2013/07/modern-opengl3d-model-obj-loaderparser.html' title='Modern OpenGL tutorial 3D model .obj loader/parser  with C++ and GLM'/><author><name>Dinesh Subedi</name><uri>http://www.blogger.com/profile/15921581026092958477</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfxMED05n-0aBIoi4kgT-8kSHfpuRf1bFosaVy-JI-vEwMtJr0sNUFF4S2oj2axSo9IfljCyuPc4hieJ0HsUEPnmw7-8Rj6UTcQjG0Mwv0tiPhTTz6ginzbCdi48YU2oQ/s151/CIMG5697.JPG'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiMuiUvXrztp-Pu7wcjEczwJULq2xzxaK_rLtC8RRdWd7U6QBnNIMmtv2nFmv0V9pspZzM8WLsh_JZ0PfMX_hbY_fIK9bO7QkWtA_gGiKmrRal4J0CixuJt_8mr16n_cB79v-kkTBUH0ko/s72-c/exportObj.JPG" height="72" width="72"/><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7720722570285165075.post-3414921382592947192</id><published>2013-06-21T13:08:00.001+10:00</published><updated>2015-05-10T19:51:10.945+10:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Modern OpenGL"/><title type='text'>Modern OpenGL tutorial Texture Mapping Example source code</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Texture mapping technique haven&#39;t change in Modern OpenGL. If you are experience in ancient version of OpenGL you might have done Texture mapping which is similar to here.Only difference is adding the extra variable to the vertex shader and fragment shader. Texture memory lie in video memory similar to VBO which is uploaded to OpenGL. Two things we have to pass in vertex shader and fragment shader. One is texture co-ordinate to define how to map on vertex and another texture color data to define the color of every pixel.Many article are there in internet about texture.Some of the great article are below.&lt;br /&gt;
&lt;br /&gt;
&lt;ol style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&lt;a href=&quot;http://codeincodeblock.blogspot.com/2011/06/bitmap-and-texture-map-in-opengl.html&quot;&gt;Texture Maping and Bitmap&lt;/a&gt;&amp;nbsp; This example use the OpenGL version 1.5 where VBO and VAO are absent.&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.arcsynthesis.org/gltut/Texturing/Tutorial%2014.html&quot;&gt;Texture is not Picture&lt;/a&gt;&amp;nbsp;Article presents whats the texture is about.&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://tomdalling.com/blog/modern-opengl/02-textures/&quot;&gt;Texure&lt;/a&gt;&amp;nbsp;This is the blog form where I learn about Modern OpenGL.&amp;nbsp;&lt;/li&gt;
&lt;/ol&gt;
&lt;div&gt;
&lt;b&gt;Download&lt;/b&gt;&lt;br /&gt;
All the code in this series of articles is available from github:&amp;nbsp;&lt;a href=&quot;https://github.com/smokindinesh/Modern-OpenGL-Series&quot; target=&quot;_blank&quot;&gt;https://github.com/smokindinesh/Modern-OpenGL-Series&lt;/a&gt;&amp;nbsp;&amp;nbsp;You can download a zip of all the files&amp;nbsp;from that page, or you can clone the repository if you are familiar with git.&lt;br /&gt;
&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;In this program I am going to map a texture on a square. My aim is to provide the simplest source code so that beginner can understand quickly and write there own. Code of this project is similar to my previous articles I only specify the added function. In this project I have added one library &lt;b&gt;loadBMP.cpp&lt;/b&gt; and &lt;b&gt;loadBMP.h &lt;/b&gt;which load the Bitmap image for texture. Function to load the texture is given below.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;pre class=&quot;brush:cpp&quot;&gt;//Makes the image into a texture, and returns the id of the texture
GLuint loadTexture(Image* image) {
 GLuint textureId;
 glGenTextures(1, &amp;amp;textureId); //Make room for our texture
 glBindTexture(GL_TEXTURE_2D, textureId); //Tell OpenGL which texture to edit
 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
 //Map the image to the texture
 glTexImage2D(GL_TEXTURE_2D,                //Always GL_TEXTURE_2D
     0,                            //0 for now
     GL_RGB,                       //Format OpenGL uses for image
     image-&amp;gt;width, image-&amp;gt;height,  //Width and height
     0,                            //The border of the image
     GL_RGB, //GL_RGB, because pixels are stored in RGB format
     GL_UNSIGNED_BYTE, //GL_UNSIGNED_BYTE, because pixels are stored
                       //as unsigned numbers
     image-&amp;gt;pixels);               //The actual pixel data
 return textureId; //Returns the id of the texture
}

GLuint _textureId; //The id of the texture

static void LoadTextureMaping()
{
    Image* image = loadBMP(&quot;chessBoard.bmp&quot;);
 _textureId = loadTexture(image);
 delete image;
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;div&gt;
At first texture memory is resides in texture unit and then it is uploaded to OpenGL. Lets look the implementation of texture in our code.
&lt;/div&gt;
&lt;/div&gt;
&lt;pre class=&quot;brush:cpp&quot;&gt;// bind the texture and set the &quot;tex&quot; uniform in the fragment shader
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, _textureId);
    glUniform1i(program-&amp;gt;uniform(&quot;tex&quot;),0); //set to 0 because the texture is bound to GL_TEXTURE0
&lt;/pre&gt;
&lt;/div&gt;
&quot;tex&quot; is the uniform sampler2D variable in fragment shader. Uniform variable is used because it value is uniform and doesn&#39;t change. Uniform variable can be used in both fragment and vertex shader. Texture can&#39;t be used whithout calling &lt;b&gt;glActiveTexture &lt;/b&gt;after that texture is bound by &lt;b&gt;glBindTexture&lt;/b&gt;. We call the &lt;b&gt;glUniform1i &lt;/b&gt;to upload the texture data form texture unit to &quot;tex&quot; variable of fragment shader. Second argument is 0 because texture is bind in 0 texture unit.&lt;br /&gt;
Final step is to get the texture co-ordinate.Texture co-ordinates is pass with vertex data.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:cpp&quot;&gt;// Put the three triangle verticies into the VBO
    GLfloat vertexData[] = {
        //  X     Y     Z     U     V
         -0.5f, -0.5f, 0.0f,  0.0f, 0.0f,
         -0.5f,0.5f, 0.0f,  0.0f, 1.0f,
         0.5f,-0.5f, 0.0f,  1.0f, 0.0f,
         0.5f,0.5f, 0.0f,  1.0f, 1.0f,

    };

    glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW);
    // connect the xyz to the &quot;vPosition&quot; attribute of the vertex shader
    glEnableVertexAttribArray(program-&amp;gt;attrib(&quot;vPosition&quot;));
    glVertexAttribPointer(program-&amp;gt;attrib(&quot;vPosition&quot;), 3, GL_FLOAT, GL_FALSE,5*sizeof(GLfloat), NULL);


    glVertexAttribPointer(program-&amp;gt;attrib(&quot;vertTextCoord&quot;), 2, GL_FLOAT, GL_TRUE, 5*sizeof(GLfloat),(const GLvoid*)(3*sizeof(GLfloat)));
    glEnableVertexAttribArray(program-&amp;gt;attrib(&quot;vertTextCoord&quot;));
&lt;/pre&gt;
You have seen in above code how I pass the texture co-ordinate in attribute variable &quot;vertTextCoord&quot;. This is similar to my previous article &lt;a href=&quot;http://codeincodeblock.blogspot.com/2013/06/modern-opengl-3x-playing-with-color.html&quot;&gt;Playing with color&lt;/a&gt; how color data are passed.&lt;br /&gt;
This the final output of our program.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiT8Y4NR1n82a3WnyernhhEKtVfDvNJVlAwNHKXt_aK8pzItAlgVKKmOMeWc39q1vItB7Y5awSjN_BGkb_Eh9BNyU1ARmUJNIjzCMhqpTq9AuKbL9nLtS_Ju2HOdC37aKklclREr3sSK_o/s1600/Capture.JPG&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;250&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiT8Y4NR1n82a3WnyernhhEKtVfDvNJVlAwNHKXt_aK8pzItAlgVKKmOMeWc39q1vItB7Y5awSjN_BGkb_Eh9BNyU1ARmUJNIjzCMhqpTq9AuKbL9nLtS_Ju2HOdC37aKklclREr3sSK_o/s320/Capture.JPG&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
Next Chapter: &lt;a href=&quot;http://www.codeincodeblock.com/2013/07/modern-opengl3d-model-obj-loaderparser.html&quot;&gt;3D model .OBJ loader/parser &lt;/a&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://www.codeincodeblock.com/feeds/3414921382592947192/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.codeincodeblock.com/2013/06/modern-opengl-3x-texture-mapping.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/3414921382592947192'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/3414921382592947192'/><link rel='alternate' type='text/html' href='http://www.codeincodeblock.com/2013/06/modern-opengl-3x-texture-mapping.html' title='Modern OpenGL tutorial Texture Mapping Example source code'/><author><name>Dinesh Subedi</name><uri>http://www.blogger.com/profile/15921581026092958477</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfxMED05n-0aBIoi4kgT-8kSHfpuRf1bFosaVy-JI-vEwMtJr0sNUFF4S2oj2axSo9IfljCyuPc4hieJ0HsUEPnmw7-8Rj6UTcQjG0Mwv0tiPhTTz6ginzbCdi48YU2oQ/s151/CIMG5697.JPG'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiT8Y4NR1n82a3WnyernhhEKtVfDvNJVlAwNHKXt_aK8pzItAlgVKKmOMeWc39q1vItB7Y5awSjN_BGkb_Eh9BNyU1ARmUJNIjzCMhqpTq9AuKbL9nLtS_Ju2HOdC37aKklclREr3sSK_o/s72-c/Capture.JPG" height="72" width="72"/><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7720722570285165075.post-3081973720791068162</id><published>2013-06-21T03:51:00.000+10:00</published><updated>2015-05-10T19:50:23.550+10:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Modern OpenGL"/><title type='text'>Modern OpenGL tutorial Playing with color example </title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
At first have a look screen shot of our program what we have going to build.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjf8xk_Y4B2KK1dWbdoLUc00TTUgjzDH5H5pTt9EWs6lOlhoD0p0PHXQ6bKzWYFZ-L6T3XODJ00-j40thjAe3elPHD8Xr3Uj2sLhuEIKRZHtz70rVnQKCDo0QZfAp-1g1HfVD3yaIhb84s/s1600/Capture.JPG&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;250&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjf8xk_Y4B2KK1dWbdoLUc00TTUgjzDH5H5pTt9EWs6lOlhoD0p0PHXQ6bKzWYFZ-L6T3XODJ00-j40thjAe3elPHD8Xr3Uj2sLhuEIKRZHtz70rVnQKCDo0QZfAp-1g1HfVD3yaIhb84s/s320/Capture.JPG&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
You have seen a triangle having different color at each vertex. In previous tutorials series we are just drawing the white triangle without color.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Download&lt;/b&gt;&lt;br /&gt;
All the code in this series of articles is available from github:&amp;nbsp;&lt;a href=&quot;https://github.com/smokindinesh/Modern-OpenGL-Series&quot; target=&quot;_blank&quot;&gt;https://github.com/smokindinesh/Modern-OpenGL-Series&lt;/a&gt;&amp;nbsp;&amp;nbsp;You can download a zip of all the files&amp;nbsp;from that page, or you can clone the repository if you are familiar with git.&lt;br /&gt;
&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp;For color we have just pass the 3 vertex data into VBO just like below&lt;br /&gt;
&lt;pre class=&quot;brush:cpp&quot;&gt;// Put the three triangle verticies into the VBO
    GLfloat vertexData[] = {
        //  X     Y     Z 
         0.0f, 0.8f, 0.0f,
        -0.8f,-0.8f, 0.0f,
         0.8f,-0.8f, 0.0f,
    };

    glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW);
    // connect the xyz to the &quot;vPosition&quot; attribute of the vertex shader
    glEnableVertexAttribArray(program-&amp;gt;attrib(&quot;vPosition&quot;));
    glVertexAttribPointer(program-&amp;gt;attrib(&quot;vPosition&quot;), 3, GL_FLOAT, GL_FALSE, 0 , NULL);
&lt;/pre&gt;
Now here we are going to give a color &amp;nbsp;for every vertex for that we can pass the color data by creating and binding another VBO &amp;nbsp;or within same VBO with vertex data. Here we pass the color data with vertex and bind it in same VBO just like below.&lt;br /&gt;
&lt;pre class=&quot;brush:cpp&quot;&gt;// Put the three triangle verticies into the VBO
    GLfloat vertexData[] = {
        //  X     Y     Z   R    G     B    A
         0.0f, 0.8f, 0.0f,1.0f,0.0f,0.0f,1.0f,
        -0.8f,-0.8f, 0.0f,0.0f,1.0f,0.0f,1.0f,
         0.8f,-0.8f, 0.0f,0.0f,0.0f,1.0f,1.0f,
    };

    glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW);
    // connect the xyz to the &quot;vPosition&quot; attribute of the vertex shader
    glEnableVertexAttribArray(program-&amp;gt;attrib(&quot;vPosition&quot;));
    glVertexAttribPointer(program-&amp;gt;attrib(&quot;vPosition&quot;), 3, GL_FLOAT, GL_FALSE, 7*sizeof(GLfloat), NULL);
    // connect the RGBA to the &quot;vColor&quot; attribute of the vertex shader and passed to the fragment shader
    glVertexAttribPointer(program-&amp;gt;attrib(&quot;vColor&quot;), 4, GL_FLOAT, GL_FALSE, 7*sizeof(GLfloat),(const GLvoid*)(3*sizeof(GLfloat)));
    glEnableVertexAttribArray(program-&amp;gt;attrib(&quot;vColor&quot;));
&lt;/pre&gt;
You can see the differences what we have added. We have passed four color value where first three are for color (RGB) and fourth for Alpha(A). You can also see the differences in the call of &lt;b&gt;glVertexAttriPointer, &lt;/b&gt;the most important change is last two argument. Second argument is &lt;b&gt;7*sizeof(GLfloat)&lt;/b&gt; which means how many bytes are in between start of one value and start next value.In our data there 7 GLfloat value for single vertex where 3 for xyz vertex value and 4 for RGBA color value.While connection xyz vertex with &lt;b&gt;&quot;vPosition&quot;&lt;/b&gt; attribute variable of vertex shader in argument second we are passing &quot;3&quot; to read 3 data for xyz &amp;nbsp;single vertex but another vertex data start at 8th position after 4 color data so there is gap of &lt;b&gt;7*sizeof(GLfloat) &lt;/b&gt;bytes which we have to specify. Gap is always calculated in bytes not the number of value. For connection RGBA color data with &lt;b&gt;&quot;vColor&quot;&lt;/b&gt; attribute variable of vertex shader which is further passed to fragment shader you can see the last argument of &lt;b&gt;glVertexAttriPointer&lt;/b&gt; is &lt;b&gt;(const GLvoid*)(3*sizeof(GLfloat))&lt;/b&gt;&amp;nbsp; which is offset argument which means how many bytes from the start is the first value. Our color data isn&#39;t in initial position it is after 3 bytes vertex data so we have to pass the offset value. In above while connection xyz vertex last argument offset value is NULL because the vertex data is in initial position.&lt;br /&gt;
&lt;br /&gt;
Next Chapter: &lt;a href=&quot;http://codeincodeblock.blogspot.com/2013/06/modern-opengl-3x-texture-mapping.html&quot;&gt;Texture Mapping&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://www.codeincodeblock.com/feeds/3081973720791068162/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.codeincodeblock.com/2013/06/modern-opengl-3x-playing-with-color.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/3081973720791068162'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/3081973720791068162'/><link rel='alternate' type='text/html' href='http://www.codeincodeblock.com/2013/06/modern-opengl-3x-playing-with-color.html' title='Modern OpenGL tutorial Playing with color example '/><author><name>Dinesh Subedi</name><uri>http://www.blogger.com/profile/15921581026092958477</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfxMED05n-0aBIoi4kgT-8kSHfpuRf1bFosaVy-JI-vEwMtJr0sNUFF4S2oj2axSo9IfljCyuPc4hieJ0HsUEPnmw7-8Rj6UTcQjG0Mwv0tiPhTTz6ginzbCdi48YU2oQ/s151/CIMG5697.JPG'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjf8xk_Y4B2KK1dWbdoLUc00TTUgjzDH5H5pTt9EWs6lOlhoD0p0PHXQ6bKzWYFZ-L6T3XODJ00-j40thjAe3elPHD8Xr3Uj2sLhuEIKRZHtz70rVnQKCDo0QZfAp-1g1HfVD3yaIhb84s/s72-c/Capture.JPG" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7720722570285165075.post-9139063349089372781</id><published>2013-06-01T03:31:00.000+10:00</published><updated>2015-05-10T19:49:27.628+10:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Modern OpenGL"/><title type='text'>Modern OpenGL tutorial Rotation, Scalling and Translation Matrix using GML (OpenGL Mathematics)</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
In previous article &lt;a href=&quot;http://codeincodeblock.blogspot.com/2013/05/modern-opengl-3x-perspective-projection.html&quot;&gt;perspective projection&lt;/a&gt; I have shown you how to do perspective projection. Now its time to do Scalling, Translation and Rotation which are very important task. In ancient version of OpenGL for these operation opengl provide funcition like glRotate, glScale, glTranslate but in modern opengl this function are not available so we are using GLM (OpenGL Mathematics) for doing such task. From this article I have change the source code with OOP. I have made two&amp;nbsp;reusable&amp;nbsp;classes Program and Shader.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Download&lt;/b&gt;&lt;br /&gt;
All the code in this series of articles is available from github:&amp;nbsp;&lt;a href=&quot;https://github.com/smokindinesh/Modern-OpenGL-Series&quot; target=&quot;_blank&quot;&gt;https://github.com/smokindinesh/Modern-OpenGL-Series&lt;/a&gt;&amp;nbsp;&amp;nbsp;You can download a zip of all the files&amp;nbsp;from that page, or you can clone the repository if you are familiar with git.&lt;br /&gt;
&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
GLM function for rotation, scalling and translation is given below.&lt;/div&gt;
&lt;pre class=&quot;brush:cpp&quot;&gt;// Projection matrix : 45° Field of View, aspect ratio, display range : 1 unit &amp;lt;-&amp;gt; 200 units
    projectionMatrix = glm::perspective(45.0f, (float)SCREEN_SIZE.x / (float)SCREEN_SIZE.y, 1.0f, 200.0f);
    glUniformMatrix4fv(program-&amp;gt;uniform(&quot;prespective&quot;),1,GL_FALSE,glm::value_ptr(projectionMatrix));
    // Camera matrix
    viewMatrix       = glm::lookAt(
                            glm::vec3(0,0,1), // Camera is at (4,3,3), in World Space
                            glm::vec3(0,0,0), // and looks at the origin
                            glm::vec3(0,1,0)  // Head is up (set to 0,-1,0 to look upside-down)
                            );

    glUniformMatrix4fv(program-&amp;gt;uniform(&quot;camera&quot;),1,GL_FALSE,glm::value_ptr(viewMatrix));
    // Model matrix : an identity matrix (model will be at the origin)
    modelMatrix= glm::mat4(1.0f);// Changes for each model !
    modelMatrix= glm::translate(modelMatrix,glm::vec3(0,0,-5));//translating to negative z-axis
    modelMatrix= glm::scale(modelMatrix,glm::vec3(2,2,2));//scalling by 2x
    modelMatrix= glm::rotate(modelMatrix, -rotationAngle, glm::vec3(0,0,1));//rotating in clockwise direction

    glUniformMatrix4fv(program-&amp;gt;uniform(&quot;model&quot;),1,GL_FALSE,glm::value_ptr(modelMatrix));
&lt;/pre&gt;
For continuous rotaton, to update the value of &amp;nbsp;rotationAngle I have made the update function.&lt;/div&gt;
&lt;pre class=&quot;brush:cpp&quot;&gt;    // update the scene based on the time elapsed since last update
    void Update(float secondsElapsed) {
    const GLfloat degreesPerSecond = 100.0f;
    rotationAngle += secondsElapsed * degreesPerSecond;
    while(rotationAngle &amp;gt; 360.0f) rotationAngle -= 360.0f;
}
&lt;/pre&gt;
&lt;br /&gt;
Next Chapter: &lt;a href=&quot;http://codeincodeblock.blogspot.com/2013/06/modern-opengl-3x-playing-with-color.html&quot;&gt;Playing with Color&lt;/a&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://www.codeincodeblock.com/feeds/9139063349089372781/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.codeincodeblock.com/2013/05/modern-opengl-3x-rotation-scalling-and.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/9139063349089372781'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/9139063349089372781'/><link rel='alternate' type='text/html' href='http://www.codeincodeblock.com/2013/05/modern-opengl-3x-rotation-scalling-and.html' title='Modern OpenGL tutorial Rotation, Scalling and Translation Matrix using GML (OpenGL Mathematics)'/><author><name>Dinesh Subedi</name><uri>http://www.blogger.com/profile/15921581026092958477</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfxMED05n-0aBIoi4kgT-8kSHfpuRf1bFosaVy-JI-vEwMtJr0sNUFF4S2oj2axSo9IfljCyuPc4hieJ0HsUEPnmw7-8Rj6UTcQjG0Mwv0tiPhTTz6ginzbCdi48YU2oQ/s151/CIMG5697.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7720722570285165075.post-8039391642553945882</id><published>2013-06-01T02:04:00.000+10:00</published><updated>2013-06-01T02:04:11.809+10:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="GTK"/><title type='text'>Setup GTK project in Code::Blocks (windows 7)</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;br /&gt;
&lt;div style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; border-bottom-width: 0px; border-collapse: collapse; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline; word-wrap: break-word;&quot;&gt;
Follow the following step to setup GTK project in Code::Blocks (windows 7)&lt;/div&gt;
&lt;div style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; border-bottom-width: 0px; border-collapse: collapse; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline; word-wrap: break-word;&quot;&gt;
&lt;b&gt;step 1:&lt;/b&gt; Download gtk+-bundle_2.24.10-20120208_win32.zip (all-in-one bundle) from&amp;nbsp;&lt;a href=&quot;http://www.gtk.org/download/win32.php&quot; rel=&quot;nofollow&quot; style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; color: #0077cc; cursor: pointer; font-size: 14px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; text-decoration: none; vertical-align: baseline;&quot;&gt;http://www.gtk.org/download/win32.php&lt;/a&gt;&lt;/div&gt;
&lt;div style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; border-bottom-width: 0px; border-collapse: collapse; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline; word-wrap: break-word;&quot;&gt;
&lt;b&gt;step 2: &lt;/b&gt;&amp;nbsp;Extract it in c drive creating new directory or any other place. In my case&amp;nbsp;&lt;strong style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; font-size: 14px; font-weight: bold; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline;&quot;&gt;C:\GTK&lt;/strong&gt;&amp;nbsp;is the directory where I extracted the zip file.&lt;/div&gt;
&lt;div style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; border-bottom-width: 0px; border-collapse: collapse; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline; word-wrap: break-word;&quot;&gt;
My extracted files looks like below.&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;border-collapse: collapse; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;div style=&quot;border-collapse: collapse; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;border-collapse: collapse; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;div style=&quot;border-collapse: collapse; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;border-collapse: collapse; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;div style=&quot;border-collapse: collapse; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;border-collapse: collapse; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiXNpOQ5ekkeNYtfbPvkomGjNvfsCeD-8jb9JpcIVER-mGqYXPply7UV6rZB_TdI9YSDflmE8nes-T41CryAbN5ICwJ5p5aVVOF5M14vrKSX6dcGC1coFuvzd1FMXfzvIC9LsjL00JLLxI/s1600/CdriveGTK.PNG&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;273&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiXNpOQ5ekkeNYtfbPvkomGjNvfsCeD-8jb9JpcIVER-mGqYXPply7UV6rZB_TdI9YSDflmE8nes-T41CryAbN5ICwJ5p5aVVOF5M14vrKSX6dcGC1coFuvzd1FMXfzvIC9LsjL00JLLxI/s640/CdriveGTK.PNG&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; border-bottom-width: 0px; border-collapse: collapse; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline; word-wrap: break-word;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; border-bottom-width: 0px; border-collapse: collapse; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline; word-wrap: break-word;&quot;&gt;
&lt;b&gt;&lt;/b&gt;&lt;/div&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;b&gt;step 3:&lt;/b&gt; Now Open Code::Blocks , create new project , from project wizard slect GTK project. And click go.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;border-collapse: collapse; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijVqSM0mi2mAbMHcVGnF0s9Y3Da612T9pQtyS3hrybvB5Dp-5L2e2PMn3y4QoPvvrnKOpzaQvX245tSBCxuOqeB5VYRXQekorwPDpYTYSCzm0AElvUjJqFNU7TmwF7CetdFtery6jTcuk/s1600/newProject.PNG&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;467&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijVqSM0mi2mAbMHcVGnF0s9Y3Da612T9pQtyS3hrybvB5Dp-5L2e2PMn3y4QoPvvrnKOpzaQvX245tSBCxuOqeB5VYRXQekorwPDpYTYSCzm0AElvUjJqFNU7TmwF7CetdFtery6jTcuk/s640/newProject.PNG&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; border-bottom-width: 0px; border-collapse: collapse; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline; word-wrap: break-word;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; border-bottom-width: 0px; border-collapse: collapse; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline; word-wrap: break-word;&quot;&gt;
Give project name &quot;&lt;strong style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; font-size: 14px; font-weight: bold; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline;&quot;&gt;GTKsample&lt;/strong&gt;&quot; or give name of your choice. And click next.&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;border-collapse: collapse; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkF6JtopaJwjWEftAmBdNpN1Ick6q7S7gGU8NgribKfWMhVxPrQ7TMqMhGIwO7A5IQZAKK_zolp1OjMOjHWm5Zr8okR8VLICHxJS5I1GT3sQRUx0W2pRJfbFSmMcPnp_rwIZl9gPqquAk/s1600/projectName.PNG&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;427&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkF6JtopaJwjWEftAmBdNpN1Ick6q7S7gGU8NgribKfWMhVxPrQ7TMqMhGIwO7A5IQZAKK_zolp1OjMOjHWm5Zr8okR8VLICHxJS5I1GT3sQRUx0W2pRJfbFSmMcPnp_rwIZl9gPqquAk/s640/projectName.PNG&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; border-bottom-width: 0px; border-collapse: collapse; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline; word-wrap: break-word;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; border-bottom-width: 0px; border-collapse: collapse; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline; word-wrap: break-word;&quot;&gt;
&amp;nbsp;Give path&amp;nbsp;&lt;strong style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; font-size: 14px; font-weight: bold; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline;&quot;&gt;C:\GTK&lt;/strong&gt;&amp;nbsp;for GTK location where you extracted the zip file. And click Next.&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;border-collapse: collapse; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjGzbW8keE9ahLitBbxkGVp6CsJJ34lCHPOisRK9nKt_VT1Krqz0yP47pxym-xA5vAEqXuuKXWJCJ8flpc25M0piCxF2za0P-ble49hKlhWUyy-9RvNdNA_Mvcd7HWc0RpMFgkhmI50JMc/s1600/GTKpath.PNG&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;516&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjGzbW8keE9ahLitBbxkGVp6CsJJ34lCHPOisRK9nKt_VT1Krqz0yP47pxym-xA5vAEqXuuKXWJCJ8flpc25M0piCxF2za0P-ble49hKlhWUyy-9RvNdNA_Mvcd7HWc0RpMFgkhmI50JMc/s640/GTKpath.PNG&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; border-bottom-width: 0px; border-collapse: collapse; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline; word-wrap: break-word;&quot;&gt;
And click Finish.&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;border-collapse: collapse; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgbK2La6naKzIfXI9ED_w3DZbDuuaL_F-TlC1OcsRuSQMtG40WOk6R4ZdXRGwco9GkwNqUs4I8h8-k7S5C1HxDWDqR7XNpkOMLSsSbhkMp78za20_p7T6VsPI2O6iBcYlQ21Cv_skjIYvI/s1600/finish.PNG&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;307&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgbK2La6naKzIfXI9ED_w3DZbDuuaL_F-TlC1OcsRuSQMtG40WOk6R4ZdXRGwco9GkwNqUs4I8h8-k7S5C1HxDWDqR7XNpkOMLSsSbhkMp78za20_p7T6VsPI2O6iBcYlQ21Cv_skjIYvI/s400/finish.PNG&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; border-bottom-width: 0px; border-collapse: collapse; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline; word-wrap: break-word;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; border-bottom-width: 0px; border-collapse: collapse; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline; word-wrap: break-word;&quot;&gt;
After creating gtk project you will see the sample program then build project, build must be successful.&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;border-collapse: collapse; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJTt861FcyWdcdUzgGTlZvOc4F1V9YCM5pZ7rUM0XGUKJ0AjS1TSJPoJe09xmGsDP3sQ17hoFbGkdyUu_k2IBNqB3vc-DUw-J01eLKgaum_x0eBVZ1vlHGSgO70nSxq4vF-fkJCtj9nkg/s1600/buildSampleProject.PNG&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;603&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJTt861FcyWdcdUzgGTlZvOc4F1V9YCM5pZ7rUM0XGUKJ0AjS1TSJPoJe09xmGsDP3sQ17hoFbGkdyUu_k2IBNqB3vc-DUw-J01eLKgaum_x0eBVZ1vlHGSgO70nSxq4vF-fkJCtj9nkg/s640/buildSampleProject.PNG&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; border-bottom-width: 0px; border-collapse: collapse; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline; word-wrap: break-word;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; border-bottom-width: 0px; border-collapse: collapse; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline; word-wrap: break-word;&quot;&gt;
&lt;b&gt;step 4:&lt;/b&gt; This is last step, upto step 3 build project must be successful. When you try to run the project you will get message something .dll file (runtime library) missing like below image because we haven&#39;t given path for runtime library(.dll file).&amp;nbsp;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;border-collapse: collapse; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgwNwpOPp0vY3l0rzpUSz4IT35Jp8qy3i2scKuVuKytnVAedzjdntNWlP94xXMozYUnTmlVbKQQImZpE6uXsqz0HeqO_REDkuLQT5Akplt2pA1cOIjLTt6XujX0pJmKQXmPu5VSEOE2mAA/s1600/dllMissing.PNG&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;225&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgwNwpOPp0vY3l0rzpUSz4IT35Jp8qy3i2scKuVuKytnVAedzjdntNWlP94xXMozYUnTmlVbKQQImZpE6uXsqz0HeqO_REDkuLQT5Akplt2pA1cOIjLTt6XujX0pJmKQXmPu5VSEOE2mAA/s400/dllMissing.PNG&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; border-bottom-width: 0px; border-collapse: collapse; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline; word-wrap: break-word;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; border-bottom-width: 0px; border-collapse: collapse; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline; word-wrap: break-word;&quot;&gt;
&amp;nbsp;For this goto the&amp;nbsp;&lt;strong style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; font-size: 14px; font-weight: bold; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline;&quot;&gt;C:\GTK&lt;/strong&gt;&amp;nbsp;directories where you extracted the zip file. Open the&amp;nbsp;&lt;strong style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; font-size: 14px; font-weight: bold; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline;&quot;&gt;bin&lt;/strong&gt;&amp;nbsp;folder only copy all the&amp;nbsp;&lt;strong style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; font-size: 14px; font-weight: bold; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline;&quot;&gt;.dll&lt;/strong&gt;&amp;nbsp;file and paste it in your project directory&amp;nbsp;&lt;strong style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; font-size: 14px; font-weight: bold; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline;&quot;&gt;GTKsample\bin\Debug\&lt;/strong&gt;&amp;nbsp;with project executable file.&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;border-collapse: collapse; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhCeQ4H3iikzE7mNhHtVwySlBLB-yM5uUi2RvPYBLuqGG6H2t0Xnfb1lCWLUa8ou1UAuiQ7SXQBRJjKC4MB0Lnqs28CVvAEedlPca9TbcSS2fEQRm0YueeagOfkpp4wLc4KtP0MkXtX_Xk/s1600/copydll.PNG&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;628&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhCeQ4H3iikzE7mNhHtVwySlBLB-yM5uUi2RvPYBLuqGG6H2t0Xnfb1lCWLUa8ou1UAuiQ7SXQBRJjKC4MB0Lnqs28CVvAEedlPca9TbcSS2fEQRm0YueeagOfkpp4wLc4KtP0MkXtX_Xk/s640/copydll.PNG&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; border-bottom-width: 0px; border-collapse: collapse; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline; word-wrap: break-word;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; border-bottom-width: 0px; border-collapse: collapse; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline; word-wrap: break-word;&quot;&gt;
&amp;nbsp;In this method every time you create the project you have to keep all the .dll file with project executable file i.e (inside project \bin\Debug\ folder). If you don&#39;t want this then copy and paste all the .dll file from bin folder to&amp;nbsp;&lt;strong style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; font-size: 14px; font-weight: bold; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline;&quot;&gt;C:\windows\system32&lt;/strong&gt;&amp;nbsp;directory.&amp;nbsp;&lt;/div&gt;
&lt;div style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; border-bottom-width: 0px; border-collapse: collapse; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline; word-wrap: break-word;&quot;&gt;
If you completed the step 4 then&amp;nbsp;the project. You must have successfully running project like below image.&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;border-collapse: collapse; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiFrdAGuZMdrhV82x5_PmwH9Qc2q_kV56-U3Meeb2trvNkdzsQO9iXCW2GqvghS02s98_hqDgaLxqq5bs1wYw3HhcN039VMCx5NoCu-dEi6UiJRfHPSvTiAXLA_5TmbjJFgHLOs3xHQ84k/s1600/finalOutput.PNG&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;221&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiFrdAGuZMdrhV82x5_PmwH9Qc2q_kV56-U3Meeb2trvNkdzsQO9iXCW2GqvghS02s98_hqDgaLxqq5bs1wYw3HhcN039VMCx5NoCu-dEi6UiJRfHPSvTiAXLA_5TmbjJFgHLOs3xHQ84k/s400/finalOutput.PNG&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; border-bottom-width: 0px; border-collapse: collapse; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif; font-size: 14px; line-height: 18px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline; word-wrap: break-word;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div style=&quot;background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline; word-wrap: break-word;&quot;&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: Arial, &#39;Liberation Sans&#39;, &#39;DejaVu Sans&#39;, sans-serif;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;border-collapse: collapse; font-size: 14px; line-height: 18px;&quot;&gt;Finally if you see the&amp;nbsp;successfully&amp;nbsp;running project like above image then you became successful to setup GTK project in Code::Blocks. If any problem occurs please comment below.&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;
&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://www.codeincodeblock.com/feeds/8039391642553945882/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.codeincodeblock.com/2013/05/setup-gtk-project-in-codeblocks-windows.html#comment-form' title='18 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/8039391642553945882'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/8039391642553945882'/><link rel='alternate' type='text/html' href='http://www.codeincodeblock.com/2013/05/setup-gtk-project-in-codeblocks-windows.html' title='Setup GTK project in Code::Blocks (windows 7)'/><author><name>Dinesh Subedi</name><uri>http://www.blogger.com/profile/15921581026092958477</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfxMED05n-0aBIoi4kgT-8kSHfpuRf1bFosaVy-JI-vEwMtJr0sNUFF4S2oj2axSo9IfljCyuPc4hieJ0HsUEPnmw7-8Rj6UTcQjG0Mwv0tiPhTTz6ginzbCdi48YU2oQ/s151/CIMG5697.JPG'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiXNpOQ5ekkeNYtfbPvkomGjNvfsCeD-8jb9JpcIVER-mGqYXPply7UV6rZB_TdI9YSDflmE8nes-T41CryAbN5ICwJ5p5aVVOF5M14vrKSX6dcGC1coFuvzd1FMXfzvIC9LsjL00JLLxI/s72-c/CdriveGTK.PNG" height="72" width="72"/><thr:total>18</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7720722570285165075.post-5664015778096411435</id><published>2013-05-20T02:01:00.000+10:00</published><updated>2015-05-10T19:48:52.659+10:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Modern OpenGL"/><title type='text'>Modern OpenGL tutorial Perspective Projection using GLM (OpenGL Mathematics)</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
In my previous article you may notice that in vertex data &amp;nbsp;for drawing a triangle, I have fixed the co-ordinate of z-axis to 1. If you change the value of z-axis greater than 1 or less than -1 then Image will not render on the screen because we haven&#39;t define the&amp;nbsp;perspective&amp;nbsp;projection matrix. In this project we are using GLM , &amp;nbsp;in previous article there is no especial use of it so I haven&#39;t talk about it before but here we use GLM function for&amp;nbsp;perspective&amp;nbsp;projection .GLM is header only library made by heavy use of C++&amp;nbsp;templates due to which performance can be reduce but make programming easier. GLM can be use with GLSL easily so we are using GLM.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Download&lt;/b&gt;&lt;br /&gt;
All the code in this series of articles is available from github:&amp;nbsp;&lt;a href=&quot;https://github.com/smokindinesh/Modern-OpenGL-Series&quot; target=&quot;_blank&quot;&gt;https://github.com/smokindinesh/Modern-OpenGL-Series&lt;/a&gt;&amp;nbsp;&amp;nbsp;You can download a zip of all the files&amp;nbsp;from that page, or you can clone the repository if you are familiar with git.&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
I will explain the only GLM part other things are similar to previous article . At last you can download the complete source code.&lt;br /&gt;
GLM variables are:&lt;br /&gt;
&lt;pre class=&quot;brush:cpp&quot;&gt;glm::vec2 SCREEN_SIZE(800, 600);//screen size
glm::mat4 projectionMatrix; // Store the projection matrix
glm::mat4 viewMatrix; // Store the view matrix
glm::mat4 modelMatrix; // Store the model matrix
&lt;/pre&gt;
Now defining the projectionMatrix , viewMatrix and modelMatrisx:&lt;/div&gt;
&lt;pre class=&quot;brush:cpp&quot;&gt;// Projection matrix : 45° Field of View, 4:3 ratio, display range : 0.1 unit &amp;lt;-&amp;gt; 100 units
    projectionMatrix = glm::perspective(45.0f, (float)SCREEN_SIZE.x / (float)SCREEN_SIZE.y, 1.0f, 200.0f);
    // Camera matrix
    viewMatrix       = glm::lookAt(
    glm::vec3(0,0,3), // Camera is at (4,3,3), in World Space
    glm::vec3(0,0,0), // and looks at the origin
    glm::vec3(0,1,0)  // Head is up (set to 0,-1,0 to look upside-down)
    );
    // Model matrix : an identity matrix (model will be at the origin)
    modelMatrix      = glm::mat4(1.0f);  // Changes for each model !
    // Our ModelViewProjection : multiplication of our 3 matrices

    // Remember, matrix multiplication is the other way around
    glm::mat4 MVP        = projectionMatrix * viewMatrix * modelMatrix;

    // Get a handle for our &quot;MVP&quot; uniform.
    // Only at initialisation time.
    GLuint MatrixID = glGetUniformLocation(programId, &quot;MVP&quot;);

    // Send our transformation to the currently bound shader,
    // in the &quot;MVP&quot; uniform
    // For each model you render, since the MVP will be different (at least the M part)
    glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &amp;amp;MVP[0][0]);
&lt;!-----&gt;&lt;/pre&gt;
Now our vertex shader:&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;pre class=&quot;brush:cpp&quot;&gt;#version 150 core

in vec3 vPosition;
uniform mat4 MVP;

void main()
{
gl_Position = MVP*vec4(vPosition,1.0);
}
&lt;/pre&gt;
Now I will explain the code a little. In function glm::perspective first argument is angle made by viewer eye and screen. Try to change its value form 45 to other and see what difference you observe. Second argument is aspect ratio of your screen. Third and forth value is near and far points it means all vertex point between them are render other vertex point are not render. So your vertex point should not be too small than near value i.e 1 and too big than far value i.e 200.&lt;br /&gt;
The function glm:lookAt is used to setup camera matrix. First argument is camera vector, second eye vector and third one is up vector ( the direction of your head )&lt;br /&gt;
&lt;br /&gt;
Next Chapter:&amp;nbsp;&lt;a href=&quot;http://codeincodeblock.blogspot.com/2013/05/modern-opengl-3x-rotation-scalling-and.html&quot;&gt;Rotation,Translation and Scalling&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://www.codeincodeblock.com/feeds/5664015778096411435/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.codeincodeblock.com/2013/05/modern-opengl-3x-perspective-projection.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/5664015778096411435'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/5664015778096411435'/><link rel='alternate' type='text/html' href='http://www.codeincodeblock.com/2013/05/modern-opengl-3x-perspective-projection.html' title='Modern OpenGL tutorial Perspective Projection using GLM (OpenGL Mathematics)'/><author><name>Dinesh Subedi</name><uri>http://www.blogger.com/profile/15921581026092958477</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfxMED05n-0aBIoi4kgT-8kSHfpuRf1bFosaVy-JI-vEwMtJr0sNUFF4S2oj2axSo9IfljCyuPc4hieJ0HsUEPnmw7-8Rj6UTcQjG0Mwv0tiPhTTz6ginzbCdi48YU2oQ/s151/CIMG5697.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7720722570285165075.post-3859176530200465153</id><published>2013-05-18T20:40:00.003+10:00</published><updated>2015-05-10T19:47:57.692+10:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Modern OpenGL"/><title type='text'>Modern OpenGL tutorial Drawing the basic shapes</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
This article is almost similar to my previous tutoirals series. In previous article we draw only triangle but here we are drawing other shapes.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Download&lt;/b&gt;&lt;br /&gt;
All the code in this series of articles is available from github:&amp;nbsp;&lt;a href=&quot;https://github.com/smokindinesh/Modern-OpenGL-Series&quot; target=&quot;_blank&quot;&gt;https://github.com/smokindinesh/Modern-OpenGL-Series&lt;/a&gt;&amp;nbsp;&amp;nbsp;You can download a zip of all the files&amp;nbsp;from that page, or you can clone the repository if you are familiar with git.&lt;br /&gt;
&lt;br /&gt;
Vertex data for drawing is given below:&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;pre class=&quot;brush:cpp&quot;&gt;// Put the 18 triangle verticies into the VBO
    GLfloat vertexData[] = {
        //  X     Y     Z

        //Pentagon
        0.25f, 0.25f, 1.0f,
        0.75f, 0.25f, 1.0f,
        0.25f, 0.5f, 1.0f,

        0.25f, 0.5f, 1.0f,
        0.75f, 0.25f, 1.0f,
        0.75f, 0.5f, 1.0f,

        0.25f, 0.5f, 1.0f,
        0.75f, 0.5f, 1.0f,
        0.5f, .75f, 1.0f,

        //Triangle
        -0.25f, 0.25f, 1.0f,
        -0.5f, 0.75f, 1.0f,
        -0.75f, 0.25f, 1.0f,
        //Trapezoid
        -0.2f, -0.25f, 1.0f,
        -0.35f, -0.75f, 1.0f,
        0.35f, -0.75f, 1.0f,

        0.2f, -0.25f, 1.0f,
        -0.2f, -0.25f, 1.0f,
        0.35f, -0.75f, 1.0f,
    };
&lt;/pre&gt;
&lt;pre class=&quot;brush:cpp&quot;&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;
&lt;/pre&gt;
Above you can see we are using three triangle to draw Pentagon and two triangle to draw Trapezoid.&lt;br /&gt;
Now we have to change little things in render function. OpenGL function to render the scene is&lt;/div&gt;
&lt;pre class=&quot;brush:cpp&quot;&gt;// draw the VAO
    glDrawArrays(GL_TRIANGLES, 0, 3);
&lt;/pre&gt;
The third argument is 3 that means to draw triangle we are passing only 3 vertices. But we are going to draw other shapes and total vertices are 18. So, we have to pass 18 in third argument.&lt;/div&gt;
&lt;pre class=&quot;brush:cpp&quot;&gt;// draw the VAO
    glDrawArrays(GL_TRIANGLES, 0, 18);
&lt;/pre&gt;
Output of the program:&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhuw97f1hvTrA2XFjmRW7IP4biSfONkkvQXuyn9UqSpyaME_K-He4P2UkuEyZ0jPkpQtv-F304k_70AzpO2eRRNHReAjTLpiA0tMgx9ZgGRrexxa0ZzBYllyPnSZaC3l8ZFsD5d4b4g1UE/s1600/output.PNG&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;250&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhuw97f1hvTrA2XFjmRW7IP4biSfONkkvQXuyn9UqSpyaME_K-He4P2UkuEyZ0jPkpQtv-F304k_70AzpO2eRRNHReAjTLpiA0tMgx9ZgGRrexxa0ZzBYllyPnSZaC3l8ZFsD5d4b4g1UE/s320/output.PNG&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
Next Chapter: &lt;a href=&quot;http://codeincodeblock.blogspot.com/2013/05/modern-opengl-3x-perspective-projection.html&quot;&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-size: large;&quot;&gt;Perspective Projection&lt;/span&gt;&lt;/a&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://www.codeincodeblock.com/feeds/3859176530200465153/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.codeincodeblock.com/2013/05/modern-opengl-3x-drawing-basic.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/3859176530200465153'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7720722570285165075/posts/default/3859176530200465153'/><link rel='alternate' type='text/html' href='http://www.codeincodeblock.com/2013/05/modern-opengl-3x-drawing-basic.html' title='Modern OpenGL tutorial Drawing the basic shapes'/><author><name>Dinesh Subedi</name><uri>http://www.blogger.com/profile/15921581026092958477</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfxMED05n-0aBIoi4kgT-8kSHfpuRf1bFosaVy-JI-vEwMtJr0sNUFF4S2oj2axSo9IfljCyuPc4hieJ0HsUEPnmw7-8Rj6UTcQjG0Mwv0tiPhTTz6ginzbCdi48YU2oQ/s151/CIMG5697.JPG'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhuw97f1hvTrA2XFjmRW7IP4biSfONkkvQXuyn9UqSpyaME_K-He4P2UkuEyZ0jPkpQtv-F304k_70AzpO2eRRNHReAjTLpiA0tMgx9ZgGRrexxa0ZzBYllyPnSZaC3l8ZFsD5d4b4g1UE/s72-c/output.PNG" height="72" width="72"/><thr:total>0</thr:total></entry></feed>